diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DateTimeIntervalFormGenerator.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DateTimeIntervalFormGenerator.java
index d7a9921c1..1745ec095 100644
--- a/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DateTimeIntervalFormGenerator.java
+++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/edit/n3editing/configuration/generators/DateTimeIntervalFormGenerator.java
@@ -1,141 +1,141 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.Arrays;
import javax.servlet.http.HttpSession;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.FieldVTwo;
public class DateTimeIntervalFormGenerator extends
BaseEditConfigurationGenerator implements EditConfigurationGenerator {
final static String vivoCore = "http://vivoweb.org/ontology/core#";
final static String toDateTimeInterval = vivoCore + "dateTimeInterval";
final static String intervalType = vivoCore + "DateTimeInterval";
final static String intervalToStart = vivoCore+"start";
final static String intervalToEnd = vivoCore + "end";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimeValueType = vivoCore + "DateTimeValue";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
- conf.setTemplate("dateTimeValueForm.ftl");
+ conf.setTemplate("dateTimeIntervalForm.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("toDateTimeInterval");
conf.setVarNameForObject("intervalNode");
conf.setN3Optional(Arrays.asList(n3ForStart, n3ForEnd));
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addSparqlForExistingLiteral(
"startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral(
"endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris(
"intervalNode", existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris(
"startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris(
"endField-precision", existingEndPrecisionQuery);
conf.addField(new FieldVTwo().setName("startField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
conf.addField(new FieldVTwo().setName("endField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
return conf;
}
final static String n3ForStart =
"?subject <" + toDateTimeInterval + " ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?startField-value . \n" +
"?startNode <" + dateTimePrecision + "> ?startField-precision . \n";
final static String n3ForEnd =
"?subject <" + toDateTimeInterval + "> ?intervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
"?endNode <" + dateTimeValue + "> ?endField-value . \n" +
"?endNode <" + dateTimePrecision + "> ?endField-precision .";
final static String existingStartDateQuery =
"SELECT ?existingDateStart WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimeValue + "> ?existingDateStart }";
final static String existingEndDateQuery =
"SELECT ?existingEndDate WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n " +
"?endNode <" + dateTimeValue + "> ?existingEndDate . }";
final static String existingIntervalNodeQuery =
"SELECT ?existingIntervalNode WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?existingIntervalNode a <" + intervalType + "> . }";
final static String existingStartNodeQuery =
"SELECT ?existingStartNode WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?existingStartNode . \n" +
"?existingStartNode a <" + dateTimeValueType + "> .} ";
final static String existingEndNodeQuery =
"SELECT ?existingEndNode WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToEnd + "> ?existingEndNode . \n" +
"?existingEndNode a <" + dateTimeValueType + "> .} ";
final static String existingStartPrecisionQuery =
"SELECT ?existingStartPrecision WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"?intervalNode <" + intervalToStart + "> ?startNode . \n" +
"?startNode a <" + dateTimeValueType + "> . \n" +
"?startNode <" + dateTimePrecision + "> ?existingStartPrecision . }";
final static String existingEndPrecisionQuery =
"SELECT ?existingEndPrecision WHERE { \n" +
"?subject <" + toDateTimeInterval + "> ?existingIntervalNode . \n" +
"?intervalNode a <" + intervalType + "> . \n" +
"intervalNode <" + intervalToEnd + "> ?endNode . \n" +
"?endNode a <" + dateTimeValueType + "> . \n" +
"?endNode <" + dateTimePrecision + "> ?existingEndPrecision . }";
}
| true | true | public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
conf.setTemplate("dateTimeValueForm.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("toDateTimeInterval");
conf.setVarNameForObject("intervalNode");
conf.setN3Optional(Arrays.asList(n3ForStart, n3ForEnd));
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addSparqlForExistingLiteral(
"startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral(
"endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris(
"intervalNode", existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris(
"startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris(
"endField-precision", existingEndPrecisionQuery);
conf.addField(new FieldVTwo().setName("startField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
conf.addField(new FieldVTwo().setName("endField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
return conf;
}
| public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
conf.setTemplate("dateTimeIntervalForm.ftl");
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("toDateTimeInterval");
conf.setVarNameForObject("intervalNode");
conf.setN3Optional(Arrays.asList(n3ForStart, n3ForEnd));
conf.addNewResource("intervalNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("startNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addNewResource("endNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addSparqlForExistingLiteral(
"startField-value", existingStartDateQuery);
conf.addSparqlForExistingLiteral(
"endField-value", existingEndDateQuery);
conf.addSparqlForExistingUris(
"intervalNode", existingIntervalNodeQuery);
conf.addSparqlForExistingUris("startNode", existingStartNodeQuery);
conf.addSparqlForExistingUris("endNode", existingEndNodeQuery);
conf.addSparqlForExistingUris(
"startField-precision", existingStartPrecisionQuery);
conf.addSparqlForExistingUris(
"endField-precision", existingEndPrecisionQuery);
conf.addField(new FieldVTwo().setName("startField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
conf.addField(new FieldVTwo().setName("endField").
setEditElement(new DateTimeWithPrecisionVTwo(null,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri())));
return conf;
}
|
diff --git a/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/run/Failures.java b/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/run/Failures.java
index 5c9136cb..8a89b2bf 100644
--- a/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/run/Failures.java
+++ b/com.piece_framework.makegood.core/src/com/piece_framework/makegood/core/run/Failures.java
@@ -1,62 +1,68 @@
/**
* Copyright (c) 2010 KUBO Atsuhiro <[email protected]>,
* All rights reserved.
*
* This file is part of MakeGood.
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License v1.0 which accompanies this
* distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package com.piece_framework.makegood.core.run;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import com.piece_framework.makegood.core.result.Result;
import com.piece_framework.makegood.core.result.TestCaseResult;
import com.piece_framework.makegood.core.result.TestSuiteResult;
public class Failures {
public static final int FIND_PREVIOUS = 1;
public static final int FIND_NEXT = 2;
private List<Result> orderedResults = new ArrayList<Result>();
private IdentityHashMap<Result, Integer> resultIndexes = new IdentityHashMap<Result, Integer>();
private List<Integer> failureIndexes = new ArrayList<Integer>();
public void addResult(Result result) {
orderedResults.add(result);
resultIndexes.put(result, orderedResults.size() - 1);
}
public void markCurrentResultAsFailure() {
failureIndexes.add(orderedResults.size() - 1);
}
public TestCaseResult find(Result criterion, int direction) {
Integer indexOfCriterion = resultIndexes.get(criterion);
if (indexOfCriterion == null) return null;
if (criterion instanceof TestSuiteResult) {
indexOfCriterion += criterion.getSize();
}
if (direction == FIND_NEXT) {
for (int i = failureIndexes.size() - 1; i >=0; --i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure >= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
+ if (failureIndexes.size() > 0) {
+ return (TestCaseResult) orderedResults.get(failureIndexes.get(failureIndexes.size() - 1));
+ }
} else if (direction == FIND_PREVIOUS) {
for (int i = 0; i < failureIndexes.size(); ++i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure <= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
+ if (failureIndexes.size() > 0) {
+ return (TestCaseResult) orderedResults.get(failureIndexes.get(0));
+ }
}
return null;
}
}
| false | true | public TestCaseResult find(Result criterion, int direction) {
Integer indexOfCriterion = resultIndexes.get(criterion);
if (indexOfCriterion == null) return null;
if (criterion instanceof TestSuiteResult) {
indexOfCriterion += criterion.getSize();
}
if (direction == FIND_NEXT) {
for (int i = failureIndexes.size() - 1; i >=0; --i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure >= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
} else if (direction == FIND_PREVIOUS) {
for (int i = 0; i < failureIndexes.size(); ++i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure <= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
}
return null;
}
| public TestCaseResult find(Result criterion, int direction) {
Integer indexOfCriterion = resultIndexes.get(criterion);
if (indexOfCriterion == null) return null;
if (criterion instanceof TestSuiteResult) {
indexOfCriterion += criterion.getSize();
}
if (direction == FIND_NEXT) {
for (int i = failureIndexes.size() - 1; i >=0; --i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure >= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
if (failureIndexes.size() > 0) {
return (TestCaseResult) orderedResults.get(failureIndexes.get(failureIndexes.size() - 1));
}
} else if (direction == FIND_PREVIOUS) {
for (int i = 0; i < failureIndexes.size(); ++i) {
Integer indexOfFailure = failureIndexes.get(i);
if (indexOfFailure <= indexOfCriterion) continue;
return (TestCaseResult) orderedResults.get(indexOfFailure);
}
if (failureIndexes.size() > 0) {
return (TestCaseResult) orderedResults.get(failureIndexes.get(0));
}
}
return null;
}
|
diff --git a/profiling/org.eclipse.linuxtools.profiling.launch.remote/src/org/eclipse/linuxtools/profiling/launch/remote/RemoteTab.java b/profiling/org.eclipse.linuxtools.profiling.launch.remote/src/org/eclipse/linuxtools/profiling/launch/remote/RemoteTab.java
index a6a5ef8e5..e65dfa8fc 100644
--- a/profiling/org.eclipse.linuxtools.profiling.launch.remote/src/org/eclipse/linuxtools/profiling/launch/remote/RemoteTab.java
+++ b/profiling/org.eclipse.linuxtools.profiling.launch.remote/src/org/eclipse/linuxtools/profiling/launch/remote/RemoteTab.java
@@ -1,226 +1,226 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Elliott Baron
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Elliott Baron <[email protected]> - initial API and implementation
* Red Hat Inc. - modify code to be shared among tools
*******************************************************************************/
package org.eclipse.linuxtools.profiling.launch.remote;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.linuxtools.internal.profiling.launch.remote.ProfileRemoteLaunchPlugin;
import org.eclipse.linuxtools.internal.profiling.launch.remote.RemoteLaunchConstants;
import org.eclipse.linuxtools.internal.profiling.launch.remote.RemoteMessages;
import org.eclipse.rse.core.RSECorePlugin;
import org.eclipse.rse.core.events.ISystemModelChangeEvent;
import org.eclipse.rse.core.events.ISystemModelChangeListener;
import org.eclipse.rse.core.model.IHost;
import org.eclipse.rse.core.model.ISystemRegistry;
import org.eclipse.rse.core.model.SystemStartHere;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
public abstract class RemoteTab extends AbstractLaunchConfigurationTab {
private TableViewer tableViewer;
private boolean isInitializing;
private IHost[] hosts;
private String name;
private class RemoteSystemLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
String text = null;
IHost host = (IHost) element;
switch (columnIndex) {
case 0:
text = host.getName();
break;
case 1:
text = host.getHostName();
break;
case 2:
text = host.getSystemType().getLabel();
break;
}
return text;
}
}
private class RemoteModelListener implements ISystemModelChangeListener {
public void systemModelResourceChanged(ISystemModelChangeEvent arg0) {
ISystemRegistry registry = SystemStartHere.getSystemRegistry();
hosts = registry.getHosts();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
refreshViewer();
}
});
}
}
public RemoteTab(String name) {
this.name = name;
// Query Locator service for available peers
ISystemRegistry registry = SystemStartHere.getSystemRegistry();
hosts = registry.getHosts();
registry.addSystemModelChangeListener(new RemoteModelListener());
}
protected void localCreateControl(Composite top) {}
public void createControl(Composite parent) {
Composite top = new Composite(parent, SWT.NONE);
top.setLayout(new GridLayout());
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Create Peers table
Label peersLabel = new Label(top, SWT.NONE);
peersLabel.setText(RemoteMessages.RemoteTab_label_hosts);
tableViewer = new TableViewer(top, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
String[] titles = { RemoteMessages.RemoteTab_header_name, RemoteMessages.RemoteTab_header_hostname, RemoteMessages.RemoteTab_header_type };
int[] bounds = { 200, 100, 250, 100 };
for (int i = 0; i < titles.length; i++) {
TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
column.getColumn().setText(titles[i]);
column.getColumn().setWidth(bounds[i]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
}
Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer.setContentProvider(new ArrayContentProvider());
tableViewer.setLabelProvider(new RemoteSystemLabelProvider());
tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateLaunchConfigurationDialog();
}
});
- while (RSECorePlugin.isInitComplete(RSECorePlugin.INIT_ALL)) {
+ while (!RSECorePlugin.isInitComplete(RSECorePlugin.INIT_ALL)) {
try {
RSECorePlugin.waitForInitCompletion();
} catch (InterruptedException e2) {
// do nothing
}
}
ISystemRegistry registry = SystemStartHere.getSystemRegistry();
hosts = registry.getHosts();
tableViewer.setInput(hosts);
localCreateControl(top);
setControl(top);
}
public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
configuration.setAttribute(RemoteLaunchConstants.ATTR_REMOTE_HOSTID, RemoteLaunchConstants.DEFAULT_REMOTE_HOSTID);
}
public void localInitializeFrom(ILaunchConfiguration configuration) throws CoreException {}
public void initializeFrom(ILaunchConfiguration configuration) {
isInitializing = true;
try {
String hostID = configuration.getAttribute(RemoteLaunchConstants.ATTR_REMOTE_HOSTID, RemoteLaunchConstants.DEFAULT_REMOTE_HOSTID);
if (hostID != null) {
IHost[] hosts = (IHost[]) tableViewer.getInput();
// Search for corresponding peer and select in table
for (int i = 0; i < hosts.length; i++) {
if (hosts[i].getName().equals(hostID)) {
tableViewer.setSelection(new StructuredSelection(hosts[i]));
}
}
}
localInitializeFrom(configuration);
} catch (CoreException e) {
e.printStackTrace();
}
isInitializing = false;
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
ISelection selected = tableViewer.getSelection();
if (selected == null) {
configuration.setAttribute(RemoteLaunchConstants.ATTR_REMOTE_HOSTID, (String) null);
}
else if (selected instanceof IStructuredSelection) {
IHost host = (IHost) ((IStructuredSelection) selected).getFirstElement();
if (host != null)
configuration.setAttribute(RemoteLaunchConstants.ATTR_REMOTE_HOSTID, host.getName());
}
}
@Override
public boolean isValid(ILaunchConfiguration launchConfig) {
setErrorMessage(null);
boolean valid = false;
ISelection selected = tableViewer.getSelection();
valid = selected != null && selected instanceof IStructuredSelection
&& !((IStructuredSelection) selected).isEmpty();
return valid;
}
public String getName() {
return name;
}
@Override
public Image getImage() {
return ProfileRemoteLaunchPlugin.imageDescriptorFromPlugin(ProfileRemoteLaunchPlugin.PLUGIN_ID, "icons/system_view.gif").createImage();
}
@Override
protected void updateLaunchConfigurationDialog() {
if (!isInitializing) {
super.updateLaunchConfigurationDialog();
}
}
private void refreshViewer() {
if (tableViewer != null && tableViewer.getContentProvider() != null) {
tableViewer.setInput(hosts);
tableViewer.refresh();
}
}
}
| true | true | public void createControl(Composite parent) {
Composite top = new Composite(parent, SWT.NONE);
top.setLayout(new GridLayout());
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Create Peers table
Label peersLabel = new Label(top, SWT.NONE);
peersLabel.setText(RemoteMessages.RemoteTab_label_hosts);
tableViewer = new TableViewer(top, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
String[] titles = { RemoteMessages.RemoteTab_header_name, RemoteMessages.RemoteTab_header_hostname, RemoteMessages.RemoteTab_header_type };
int[] bounds = { 200, 100, 250, 100 };
for (int i = 0; i < titles.length; i++) {
TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
column.getColumn().setText(titles[i]);
column.getColumn().setWidth(bounds[i]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
}
Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer.setContentProvider(new ArrayContentProvider());
tableViewer.setLabelProvider(new RemoteSystemLabelProvider());
tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateLaunchConfigurationDialog();
}
});
while (RSECorePlugin.isInitComplete(RSECorePlugin.INIT_ALL)) {
try {
RSECorePlugin.waitForInitCompletion();
} catch (InterruptedException e2) {
// do nothing
}
}
ISystemRegistry registry = SystemStartHere.getSystemRegistry();
hosts = registry.getHosts();
tableViewer.setInput(hosts);
localCreateControl(top);
setControl(top);
}
| public void createControl(Composite parent) {
Composite top = new Composite(parent, SWT.NONE);
top.setLayout(new GridLayout());
top.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Create Peers table
Label peersLabel = new Label(top, SWT.NONE);
peersLabel.setText(RemoteMessages.RemoteTab_label_hosts);
tableViewer = new TableViewer(top, SWT.BORDER | SWT.FULL_SELECTION);
tableViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
String[] titles = { RemoteMessages.RemoteTab_header_name, RemoteMessages.RemoteTab_header_hostname, RemoteMessages.RemoteTab_header_type };
int[] bounds = { 200, 100, 250, 100 };
for (int i = 0; i < titles.length; i++) {
TableViewerColumn column = new TableViewerColumn(tableViewer, SWT.NONE);
column.getColumn().setText(titles[i]);
column.getColumn().setWidth(bounds[i]);
column.getColumn().setResizable(true);
column.getColumn().setMoveable(true);
}
Table table = tableViewer.getTable();
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer.setContentProvider(new ArrayContentProvider());
tableViewer.setLabelProvider(new RemoteSystemLabelProvider());
tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateLaunchConfigurationDialog();
}
});
while (!RSECorePlugin.isInitComplete(RSECorePlugin.INIT_ALL)) {
try {
RSECorePlugin.waitForInitCompletion();
} catch (InterruptedException e2) {
// do nothing
}
}
ISystemRegistry registry = SystemStartHere.getSystemRegistry();
hosts = registry.getHosts();
tableViewer.setInput(hosts);
localCreateControl(top);
setControl(top);
}
|
diff --git a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/utils/SWTUtils.java b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/utils/SWTUtils.java
index 280e489..768f023 100644
--- a/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/utils/SWTUtils.java
+++ b/org.eclipse.swtbot.swt.finder/src/org/eclipse/swtbot/swt/finder/utils/SWTUtils.java
@@ -1,478 +1,481 @@
/*******************************************************************************
* Copyright (c) 2008 Ketan Padegaonkar and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ketan Padegaonkar - initial API and implementation
* Hans Schwaebli - http://swtbot.org/bugzilla/show_bug.cgi?id=108
*******************************************************************************/
package org.eclipse.swtbot.swt.finder.utils;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
import org.eclipse.swtbot.swt.finder.results.BoolResult;
import org.eclipse.swtbot.swt.finder.results.Result;
import org.eclipse.swtbot.swt.finder.utils.internal.Assert;
import org.eclipse.swtbot.swt.finder.utils.internal.NextWidgetFinder;
import org.eclipse.swtbot.swt.finder.utils.internal.PreviousWidgetFinder;
import org.eclipse.swtbot.swt.finder.utils.internal.ReflectionInvoker;
import org.eclipse.swtbot.swt.finder.utils.internal.SiblingFinder;
import org.eclipse.swtbot.swt.finder.utils.internal.WidgetIndexFinder;
import org.eclipse.swtbot.swt.finder.waits.DefaultCondition;
import org.eclipse.swtbot.swt.finder.waits.ICondition;
import org.eclipse.swtbot.swt.finder.widgets.TimeoutException;
/**
* @author Ketan Padegaonkar <KetanPadegaonkar [at] gmail [dot] com>
* @version $Id$
*/
public abstract class SWTUtils {
/** The logger. */
private static Logger log = Logger.getLogger(SWTUtils.class);
/**
* The display used for the GUI.
*/
private static Display display;
/**
* @param w the widget
* @return the siblings of the widget, or an empty array, if there are none.
*/
public static Widget[] siblings(final Widget w) {
if ((w == null) || w.isDisposed())
return new Widget[] {};
return UIThreadRunnable.syncExec(w.getDisplay(), new SiblingFinder(w));
}
/**
* Gets the index of the given widget in its current container.
*
* @param w the widget
* @return -1 if the the widget is <code>null</code> or if the widget does not have a parent; a number greater than
* or equal to zero indicating the index of the widget among its siblings
*/
public static int widgetIndex(final Widget w) {
if ((w == null) || w.isDisposed())
return -1;
return UIThreadRunnable.syncExec(w.getDisplay(), new WidgetIndexFinder(w));
}
/**
* Gets the previous sibling of the passed in widget.
*
* @param w the widget
* @return the previous sibling of w
*/
public static Widget previousWidget(final Widget w) {
if ((w == null) || w.isDisposed())
return null;
return UIThreadRunnable.syncExec(w.getDisplay(), new PreviousWidgetFinder(w));
}
/**
* Gets the next sibling of this passed in widget.
*
* @param w the widget.
* @return the sibling of the specified widget, or <code>null</code> if it has none.
*/
public static Widget nextWidget(Widget w) {
if ((w == null) || w.isDisposed())
return null;
return UIThreadRunnable.syncExec(w.getDisplay(), new NextWidgetFinder(w));
}
/**
* Gets the text of the given object.
*
* @param obj the object which should be a widget.
* @return the result of invocation of Widget#getText()
*/
public static String getText(final Object obj) {
if ((obj instanceof Widget) && !((Widget) obj).isDisposed()) {
Widget widget = (Widget) obj;
String text = UIThreadRunnable.syncExec(widget.getDisplay(), new ReflectionInvoker(obj, "getText")); //$NON-NLS-1$
text = text.replaceAll(Text.DELIMITER, "\n"); //$NON-NLS-1$
return text;
}
return ""; //$NON-NLS-1$
}
/**
* Gets the tooltip text for the given object.
*
* @param obj the object which should be a widget.
* @return the result of invocation of Widget#getToolTipText()
* @since 1.0
*/
public static String getToolTipText(final Object obj) {
if ((obj instanceof Widget) && !((Widget) obj).isDisposed()) {
Widget widget = (Widget) obj;
return UIThreadRunnable.syncExec(widget.getDisplay(), new ReflectionInvoker(obj, "getToolTipText")); //$NON-NLS-1$
}
return ""; //$NON-NLS-1$
}
/**
* Converts the given widget to a string.
*
* @param w the widget.
* @return the string representation of the widget.
*/
public static String toString(final Widget w) {
if ((w == null) || w.isDisposed())
return ""; //$NON-NLS-1$
return toString(w.getDisplay(), w);
}
/**
* Convers the display and object to a string.
*
* @param display the display on which the object should be evaluated.
* @param o the object to evaluate.
* @return the string representation of the object when evaluated in the display thread.
*/
public static String toString(Display display, final Object o) {
return ClassUtils.simpleClassName(o) + " {" + trimToLength(getText(o), 20) + "}"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Trims the string to a given length, adds an ellipsis("...") if the string is trimmed.
*
* @param result The string to limit.
* @param maxLength The length to limit it to.
* @return The resulting string.
*/
private static String trimToLength(String result, int maxLength) {
if (result.length() > maxLength)
result = result.substring(0, maxLength) + "..."; //$NON-NLS-1$
return result;
}
/**
* Checks if the widget has the given style.
*
* @param w the widget.
* @param style the style.
* @return <code>true</code> if the widget has the specified style bit set. Otherwise <code>false</code>.
*/
public static boolean hasStyle(final Widget w, final int style) {
if ((w == null) || w.isDisposed())
return false;
if (style == SWT.NONE)
return true;
return UIThreadRunnable.syncExec(w.getDisplay(), new BoolResult() {
public Boolean run() {
return (w.getStyle() & style) != 0;
}
});
}
/**
* Sleeps for the given number of milliseconds.
*
* @param millis the time in milliseconds to sleep.
*/
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException("Could not sleep", e); //$NON-NLS-1$
}
}
/**
* Gets all the thread in the VM.
*
* @return all the threads in the VM.
*/
public static Thread[] allThreads() {
ThreadGroup threadGroup = primaryThreadGroup();
Thread[] threads = new Thread[64];
int enumerate = threadGroup.enumerate(threads, true);
Thread[] result = new Thread[enumerate];
System.arraycopy(threads, 0, result, 0, enumerate);
return result;
}
/**
* Gets the primary thread group.
*
* @return the top level thread group.
*/
public static ThreadGroup primaryThreadGroup() {
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
while (threadGroup.getParent() != null)
threadGroup = threadGroup.getParent();
return threadGroup;
}
/**
* Caches the display for later use.
*
* @return the display.
*/
public static Display display() {
if ((display == null) || display.isDisposed()) {
display = null;
Thread[] allThreads = allThreads();
for (Thread thread : allThreads) {
Display d = Display.findDisplay(thread);
if (d != null)
display = d;
}
if (display == null)
throw new IllegalStateException("Could not find a display"); //$NON-NLS-1$
}
return display;
}
/**
* Checks if the widget text is an empty string.
*
* @param w the widget
* @return <code>true</code> if the widget does not have any text set on it. Othrewise <code>false</code>.
*/
// TODO recommend changing the name to isEmptyText since null isn't being check and if getText returned a null an
// exception would be thrown.
public static boolean isEmptyOrNullText(Widget w) {
return getText(w).trim().equals(""); //$NON-NLS-1$
}
/**
* Invokes the specified methodName on the object, and returns the result, or <code>null</code> if the method
* returns void.
*
* @param object the object
* @param methodName the method name
* @return the result of invoking the method on the object
* @throws NoSuchMethodException if the method methodName does not exist.
* @throws IllegalAccessException if the java access control does not allow invocation.
* @throws InvocationTargetException if the method methodName throws an exception.
* @see Method#invoke(Object, Object[])
* @since 1.0
*/
public static Object invokeMethod(final Object object, String methodName) throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
final Method method = object.getClass().getMethod(methodName, new Class[0]);
Widget widget = null;
final Object result;
if (object instanceof Widget) {
widget = (Widget) object;
result = UIThreadRunnable.syncExec(widget.getDisplay(), new Result<Object>() {
public Object run() {
try {
return method.invoke(object, new Object[0]);
} catch (Exception niceTry) {
}
return null;
}
});
} else
result = method.invoke(object, new Object[0]);
return result;
}
/**
* This captures a screen shot and saves it to the given file.
*
* @param fileName the filename to save screenshot to.
* @return <code>true</code> if the screenshot was created and saved, <code>false</code> otherwise.
* @since 1.0
*/
public static boolean captureScreenshot(final String fileName) {
new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1));
return UIThreadRunnable.syncExec(new BoolResult() {
public Boolean run() {
return captureScreenshotInternal(fileName);
}
});
}
/**
* This captures a screen shot of a widget and saves it to the given file.
*
* @param fileName the filename to save screenshot to.
* @param control the control
* @return <code>true</code> if the screenshot was created and saved, <code>false</code> otherwise.
* @since 2.0
*/
public static boolean captureScreenshot(final String fileName, final Control control) {
new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1));
return UIThreadRunnable.syncExec(new BoolResult() {
public Boolean run() {
if (control instanceof Shell)
return captureScreenshotInternal(fileName, control.getBounds());
Display display = control.getDisplay();
Rectangle bounds = control.getBounds();
Rectangle mappedToDisplay = display.map(control.getParent(), null, bounds);
return captureScreenshotInternal(fileName, mappedToDisplay);
}
});
}
/**
* This captures a screen shot of an area and saves it to the given file.
*
* @param fileName the filename to save screenshot to.
* @param bounds the area to capture.
* @return <code>true</code> if the screenshot was created and saved, <code>false</code> otherwise.
* @since 2.0
*/
public static boolean captureScreenshot(final String fileName, final Rectangle bounds) {
new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1));
return UIThreadRunnable.syncExec(new BoolResult() {
public Boolean run() {
return captureScreenshotInternal(fileName, bounds);
}
});
}
/**
* Captures a screen shot. Used internally.
* <p>
* NOTE: This method is not thread safe. Clients must ensure that they do invoke this from a UI thread.
* </p>
*
* @param fileName the filename to save screenshot to.
* @return <code>true</code> if the screenshot was created and saved, <code>false</code> otherwise.
*/
private static boolean captureScreenshotInternal(final String fileName) {
return captureScreenshotInternal(fileName, display.getBounds());
}
/**
* Captures a screen shot. Used internally.
* <p>
* NOTE: This method is not thread safe. Clients must ensure that they do invoke this from a UI thread.
* </p>
*
* @param fileName the filename to save screenshot to.
* @param bounds the area relative to the display that should be captured.
* @return <code>true</code> if the screenshot was created and saved, <code>false</code> otherwise.
*/
private static boolean captureScreenshotInternal(final String fileName, Rectangle bounds) {
GC gc = new GC(display);
Image image = null;
- new File(fileName).getParentFile().mkdirs();
+ File file = new File(fileName);
+ File parentDir = file.getParentFile();
+ if (parentDir != null)
+ parentDir.mkdirs();
try {
log.debug(MessageFormat.format("Capturing screenshot ''{0}''", fileName)); //$NON-NLS-1$
image = new Image(display, bounds.width, bounds.height);
gc.copyArea(image, bounds.x, bounds.y);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { image.getImageData() };
imageLoader.save(fileName, new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1)));
return true;
} catch (Exception e) {
log.warn("Could not capture screenshot: " + fileName + "'", e); //$NON-NLS-1$ //$NON-NLS-2$
- File brokenImage = new File(fileName).getAbsoluteFile();
+ File brokenImage = file.getAbsoluteFile();
if (brokenImage.exists()) {
try {
log.trace(MessageFormat.format("Broken screenshot set to be deleted on exit: {0}", fileName)); //$NON-NLS-1$
brokenImage.deleteOnExit();
} catch (Exception ex) {
log.info(MessageFormat.format("Could not set broken screenshot to be deleted on exit: {0}", fileName), ex); //$NON-NLS-1$
}
}
return false;
} finally {
gc.dispose();
if (image != null) {
image.dispose();
}
}
}
/**
* Waits until a display appears.
*
* @throws TimeoutException if the condition does not evaluate to true after {@link SWTBotPreferences#TIMEOUT}
* milliseconds.
*/
public static void waitForDisplayToAppear() {
waitForDisplayToAppear(SWTBotPreferences.TIMEOUT);
}
/**
* Waits until a display appears.
*
* @param timeout the timeout in ms.
* @throws TimeoutException if the condition does not evaluate to true after {@code timeout}ms milliseconds.
*/
public static void waitForDisplayToAppear(long timeout) {
waitUntil(new DefaultCondition() {
public String getFailureMessage() {
return "Could not find a display"; //$NON-NLS-1$
}
public boolean test() throws Exception {
return SWTUtils.display() != null;
}
}, timeout, 500);
}
private static void waitUntil(ICondition condition, long timeout, long interval) throws TimeoutException {
Assert.isTrue(interval >= 0, "interval value is negative"); //$NON-NLS-1$
Assert.isTrue(timeout >= 0, "timeout value is negative"); //$NON-NLS-1$
long limit = System.currentTimeMillis() + timeout;
while (true) {
try {
if (condition.test())
return;
} catch (Throwable e) {
// do nothing
}
sleep(interval);
if (System.currentTimeMillis() > limit)
throw new TimeoutException("Timeout after: " + timeout + " ms.: " + condition.getFailureMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* Return true if the current thread is the UI thread.
*
* @param display the display
* @return <code>true</code> if the current thread is the UI thread, <code>false</code> otherwise.
*/
public static boolean isUIThread(Display display) {
return display.getThread() == Thread.currentThread();
}
/**
* Return true if the current thread is the UI thread.
*
* @return <code>true</code> if this instance is running in the UI thread, <code>false</code> otherwise.
*/
public static boolean isUIThread() {
return isUIThread(display);
}
}
| false | true | private static boolean captureScreenshotInternal(final String fileName, Rectangle bounds) {
GC gc = new GC(display);
Image image = null;
new File(fileName).getParentFile().mkdirs();
try {
log.debug(MessageFormat.format("Capturing screenshot ''{0}''", fileName)); //$NON-NLS-1$
image = new Image(display, bounds.width, bounds.height);
gc.copyArea(image, bounds.x, bounds.y);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { image.getImageData() };
imageLoader.save(fileName, new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1)));
return true;
} catch (Exception e) {
log.warn("Could not capture screenshot: " + fileName + "'", e); //$NON-NLS-1$ //$NON-NLS-2$
File brokenImage = new File(fileName).getAbsoluteFile();
if (brokenImage.exists()) {
try {
log.trace(MessageFormat.format("Broken screenshot set to be deleted on exit: {0}", fileName)); //$NON-NLS-1$
brokenImage.deleteOnExit();
} catch (Exception ex) {
log.info(MessageFormat.format("Could not set broken screenshot to be deleted on exit: {0}", fileName), ex); //$NON-NLS-1$
}
}
return false;
} finally {
gc.dispose();
if (image != null) {
image.dispose();
}
}
}
| private static boolean captureScreenshotInternal(final String fileName, Rectangle bounds) {
GC gc = new GC(display);
Image image = null;
File file = new File(fileName);
File parentDir = file.getParentFile();
if (parentDir != null)
parentDir.mkdirs();
try {
log.debug(MessageFormat.format("Capturing screenshot ''{0}''", fileName)); //$NON-NLS-1$
image = new Image(display, bounds.width, bounds.height);
gc.copyArea(image, bounds.x, bounds.y);
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { image.getImageData() };
imageLoader.save(fileName, new ImageFormatConverter().imageTypeOf(fileName.substring(fileName.lastIndexOf('.') + 1)));
return true;
} catch (Exception e) {
log.warn("Could not capture screenshot: " + fileName + "'", e); //$NON-NLS-1$ //$NON-NLS-2$
File brokenImage = file.getAbsoluteFile();
if (brokenImage.exists()) {
try {
log.trace(MessageFormat.format("Broken screenshot set to be deleted on exit: {0}", fileName)); //$NON-NLS-1$
brokenImage.deleteOnExit();
} catch (Exception ex) {
log.info(MessageFormat.format("Could not set broken screenshot to be deleted on exit: {0}", fileName), ex); //$NON-NLS-1$
}
}
return false;
} finally {
gc.dispose();
if (image != null) {
image.dispose();
}
}
}
|
diff --git a/MEditor/src/cz/fi/muni/xkremser/editor/server/fedora/utils/RESTHelper.java b/MEditor/src/cz/fi/muni/xkremser/editor/server/fedora/utils/RESTHelper.java
index 36e28dfa..701ecb7f 100644
--- a/MEditor/src/cz/fi/muni/xkremser/editor/server/fedora/utils/RESTHelper.java
+++ b/MEditor/src/cz/fi/muni/xkremser/editor/server/fedora/utils/RESTHelper.java
@@ -1,339 +1,339 @@
/*
* Metadata Editor
* @author Jiri Kremser
*
*
*
* Metadata Editor - Rich internet application for editing metadata.
* Copyright (C) 2011 Jiri Kremser ([email protected])
* Moravian Library in Brno
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*
*/
package cz.fi.muni.xkremser.editor.server.fedora.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import com.google.gwt.user.server.Base64Utils;
import org.apache.log4j.Logger;
import cz.fi.muni.xkremser.editor.client.ConnectionException;
// TODO: Auto-generated Javadoc
public class RESTHelper {
/** The Constant GET. */
public static final int GET = 0;
/** The Constant PUT. */
public static final int PUT = 1;
/** The Constant POST. */
public static final int POST = 2;
/** The Constant DELETE. */
public static final int DELETE = 3;
/** The Constant LOGGER. */
private static final Logger LOGGER = Logger.getLogger(RESTHelper.class);
/**
* Input stream.
*
* @param urlString
* the url string
* @param user
* the user
* @param pass
* the pass
* @return the input stream
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static InputStream get(String urlString, String user, String pass, boolean robustMode)
throws IOException {
URLConnection uc = openConnection(urlString, user, pass, robustMode);
if (uc == null) return null;
return uc.getInputStream();
}
/**
* Open connection.
*
* @param urlString
* the url string
* @param user
* the user
* @param pass
* the pass
* @return the uRL connection
* @throws MalformedURLException
* the malformed url exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static URLConnection openConnection(String urlString, String user, String pass, boolean robustMode)
throws MalformedURLException, IOException {
return openConnection(urlString, user, pass, GET, null, robustMode);
}
/**
* Open connection.
*
* @param urlString
* the url string
* @param user
* the user
* @param pass
* the pass
* @param method
* the method
* @param content
* the content
* @return the uRL connection
* @throws MalformedURLException
* the malformed url exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static URLConnection openConnection(String urlString,
String user,
String pass,
final int method,
String content,
boolean robustMode) throws MalformedURLException, IOException {
URL url = new URL(urlString);
- boolean auth = false;
+ boolean notAuth = false;
String encoded = null;
- if (auth = (user == null || pass == null)) {
+ if (notAuth = (user == null || pass == null)) {
String userPassword = user + ":" + pass;
encoded = Base64Utils.toBase64(userPassword.getBytes());
}
URLConnection uc = null;
OutputStreamWriter out = null;
try {
uc = url.openConnection();
- if (auth) {
+ if (!notAuth) {
uc.setRequestProperty("Authorization", "Basic " + encoded);
}
switch (method) {
case GET:
break;
case PUT:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("PUT");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case POST:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("POST");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case DELETE:
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
((HttpURLConnection) uc).setRequestMethod("DELETE");
break;
}
int resp = ((HttpURLConnection) uc).getResponseCode();
if (resp != 200) {
if (robustMode) {
return null;
} else {
LOGGER.error("Unable to open connection on " + urlString + " response code: " + resp);
throw new ConnectionException("connection cannot be established");
}
}
} catch (IOException e) {
e.printStackTrace();
throw new ConnectionException("connection cannot be established");
}
return uc;
}
/**
* Put or post method.
*
* @param urlString
* the url string
* @param content
* the content
* @param user
* the user
* @param pass
* the pass
* @return true, if successful
*/
private static boolean putOrPost(String urlString,
String content,
String user,
String pass,
boolean robustMode,
boolean isPut) {
URLConnection conn = null;
try {
conn = openConnection(urlString, user, pass, isPut ? PUT : POST, content, robustMode);
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
try {
if (conn != null) LOGGER.debug(convertStreamToString(conn.getInputStream()));
} catch (IOException e1) {
e1.printStackTrace();
}
return true;
}
/**
* Put.
*
* @param urlString
* the url string
* @param content
* the content
* @param user
* the user
* @param pass
* the pass
* @return true, if successful
*/
public static boolean put(String urlString, String content, String user, String pass, boolean robustMode) {
return putOrPost(urlString, content, user, pass, robustMode, true);
}
/**
* Post.
*
* @param urlString
* the url string
* @param content
* the content
* @param user
* the user
* @param pass
* the pass
* @return true, if successful
*/
public static boolean post(String urlString, String content, String user, String pass, boolean robustMode) {
return putOrPost(urlString, content, user, pass, robustMode, false);
}
/**
* Delete.
*
* @param urlString
* the url string
* @param user
* the user
* @param pass
* the pass
* @return true, if successful
*/
public static boolean delete(String urlString, String user, String pass, boolean robustMode) {
HttpURLConnection uc = null;
try {
uc = (HttpURLConnection) openConnection(urlString, user, pass, robustMode);
if (uc == null) return false;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
try {
uc.setRequestMethod("DELETE");
} catch (ProtocolException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Convert stream to string.
*
* @param is
* the is
* @return the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
| false | true | public static URLConnection openConnection(String urlString,
String user,
String pass,
final int method,
String content,
boolean robustMode) throws MalformedURLException, IOException {
URL url = new URL(urlString);
boolean auth = false;
String encoded = null;
if (auth = (user == null || pass == null)) {
String userPassword = user + ":" + pass;
encoded = Base64Utils.toBase64(userPassword.getBytes());
}
URLConnection uc = null;
OutputStreamWriter out = null;
try {
uc = url.openConnection();
if (auth) {
uc.setRequestProperty("Authorization", "Basic " + encoded);
}
switch (method) {
case GET:
break;
case PUT:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("PUT");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case POST:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("POST");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case DELETE:
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
((HttpURLConnection) uc).setRequestMethod("DELETE");
break;
}
int resp = ((HttpURLConnection) uc).getResponseCode();
if (resp != 200) {
if (robustMode) {
return null;
} else {
LOGGER.error("Unable to open connection on " + urlString + " response code: " + resp);
throw new ConnectionException("connection cannot be established");
}
}
} catch (IOException e) {
e.printStackTrace();
throw new ConnectionException("connection cannot be established");
}
return uc;
}
| public static URLConnection openConnection(String urlString,
String user,
String pass,
final int method,
String content,
boolean robustMode) throws MalformedURLException, IOException {
URL url = new URL(urlString);
boolean notAuth = false;
String encoded = null;
if (notAuth = (user == null || pass == null)) {
String userPassword = user + ":" + pass;
encoded = Base64Utils.toBase64(userPassword.getBytes());
}
URLConnection uc = null;
OutputStreamWriter out = null;
try {
uc = url.openConnection();
if (!notAuth) {
uc.setRequestProperty("Authorization", "Basic " + encoded);
}
switch (method) {
case GET:
break;
case PUT:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("PUT");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case POST:
uc.setDoOutput(true);
((HttpURLConnection) uc).setRequestMethod("POST");
try {
out = new OutputStreamWriter(uc.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(content);
} catch (IOException e) {
e.printStackTrace();
}
out.flush();
break;
case DELETE:
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
((HttpURLConnection) uc).setRequestMethod("DELETE");
break;
}
int resp = ((HttpURLConnection) uc).getResponseCode();
if (resp != 200) {
if (robustMode) {
return null;
} else {
LOGGER.error("Unable to open connection on " + urlString + " response code: " + resp);
throw new ConnectionException("connection cannot be established");
}
}
} catch (IOException e) {
e.printStackTrace();
throw new ConnectionException("connection cannot be established");
}
return uc;
}
|
diff --git a/org.caleydo.util.r/src/org/caleydo/util/r/filter/FilterRepresentationPValue.java b/org.caleydo.util.r/src/org/caleydo/util/r/filter/FilterRepresentationPValue.java
index d9242b5a1..be5f6fbe9 100644
--- a/org.caleydo.util.r/src/org/caleydo/util/r/filter/FilterRepresentationPValue.java
+++ b/org.caleydo.util.r/src/org/caleydo/util/r/filter/FilterRepresentationPValue.java
@@ -1,170 +1,170 @@
package org.caleydo.util.r.filter;
import org.caleydo.core.data.collection.Histogram;
import org.caleydo.core.data.collection.ISet;
import org.caleydo.core.data.filter.ContentFilter;
import org.caleydo.core.data.filter.ContentMetaFilter;
import org.caleydo.core.data.filter.event.RemoveContentFilterEvent;
import org.caleydo.core.data.filter.representation.AFilterRepresentation;
import org.caleydo.core.data.virtualarray.ContentVirtualArray;
import org.caleydo.core.data.virtualarray.delta.ContentVADelta;
import org.caleydo.core.data.virtualarray.delta.VADeltaItem;
import org.caleydo.core.manager.GeneralManager;
import org.caleydo.core.manager.datadomain.DataDomainManager;
import org.caleydo.view.histogram.GLHistogram;
import org.caleydo.view.histogram.RcpGLHistogramView;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Slider;
public class FilterRepresentationPValue extends
AFilterRepresentation<ContentVADelta, ContentFilter> {
private ISet set;
private Histogram histogram;
private float pValue = 1f;
public void create() {
super.create();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
GridData gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
// gridData.horizontalAlignment = GridData.FILL;
gridData.widthHint = 400;
gridData.heightHint = 50;
Composite infoComposite = new Composite(parentComposite, SWT.NULL);
infoComposite.setLayoutData(gridData);
infoComposite.setLayout(new FillLayout(SWT.VERTICAL));
final Slider pValueSlider = new Slider(infoComposite, SWT.HORIZONTAL);
final Label pValueLabel = new Label(infoComposite, SWT.NULL);
+ pValue = histogram.getMax();
pValueLabel.setText("p-Value: " + Float.toString(pValue));
pValueSlider.setMinimum(0);
pValueSlider.setMaximum((int) (histogram.getMax() * 10000));
- System.out.println("Largest: " +histogram.getMax());
pValueSlider.setIncrement(1);
pValueSlider.setPageIncrement(5);
pValueSlider.setSelection((int) (pValue * 10000));
pValueSlider.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
pValue = (float) pValueSlider.getSelection() / 10000.00f;
System.out.println(pValue);
pValueLabel.setText("p-Value: " + Float.toString(pValue));
parentComposite.pack();
parentComposite.layout();
createVADelta();
filter.updateFilterManager();
// if (reducedVA != null)
// reducedNumberLabel.setText("# Genes: " +
// reducedVA.size());
}
});
Composite histoComposite = new Composite(parentComposite, SWT.NULL);
histoComposite.setLayout(new FillLayout(SWT.VERTICAL));
gridData.heightHint = 300;
// gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
histoComposite.setLayoutData(gridData);
RcpGLHistogramView histogramView = new RcpGLHistogramView();
histogramView.setDataDomain(DataDomainManager.get().getDataDomain(
"org.caleydo.datadomain.genetic"));
histogramView.createDefaultSerializedView();
histogramView.createPartControl(histoComposite);
((GLHistogram) (histogramView.getGLView())).setHistogram(histogram);
// Usually the canvas is registered to the GL animator in the
// PartListener.
// Because the GL histogram is no usual RCP view we have to do
// it on our
// own
GeneralManager.get().getViewGLCanvasManager()
.registerGLCanvasToAnimator(histogramView.getGLCanvas());
Monitor primary = parentComposite.getDisplay().getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = parentComposite.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
parentComposite.setLocation(x, y);
((Shell) parentComposite).open();
}
});
}
public void setHistogram(Histogram histogram) {
this.histogram = histogram;
}
@Override
protected void createVADelta() {
if (filter instanceof ContentMetaFilter) {
for (ContentFilter subFilter : ((ContentMetaFilter) filter).getFilterList()) {
createVADelta(subFilter);
}
} else
createVADelta(filter);
}
private void createVADelta(ContentFilter subFilter) {
ContentVADelta contentVADelta = new ContentVADelta(ISet.CONTENT, subFilter
.getDataDomain().getContentIDType());
ContentVirtualArray contentVA = subFilter.getDataDomain()
.getContentFilterManager().getBaseVA();
double[] tTestResult = ((FilterRepresentationPValue) subFilter.getFilterRep())
.getSet().getStatisticsResult().getOneSidedTTestResult();
for (int contentIndex = 0; contentIndex < contentVA.size(); contentIndex++) {
if (tTestResult != null && tTestResult[contentIndex] > pValue)
contentVADelta
.add(VADeltaItem.removeElement(contentVA.get(contentIndex)));
}
subFilter.setDelta(contentVADelta);
}
@Override
protected void triggerRemoveFilterEvent() {
RemoveContentFilterEvent filterEvent = new RemoveContentFilterEvent();
filterEvent.setDataDomainType(filter.getDataDomain().getDataDomainType());
filterEvent.setFilter(filter);
GeneralManager.get().getEventPublisher().triggerEvent(filterEvent);
}
public void setSet(ISet set) {
this.set = set;
}
public ISet getSet() {
return set;
}
}
| false | true | public void create() {
super.create();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
GridData gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
// gridData.horizontalAlignment = GridData.FILL;
gridData.widthHint = 400;
gridData.heightHint = 50;
Composite infoComposite = new Composite(parentComposite, SWT.NULL);
infoComposite.setLayoutData(gridData);
infoComposite.setLayout(new FillLayout(SWT.VERTICAL));
final Slider pValueSlider = new Slider(infoComposite, SWT.HORIZONTAL);
final Label pValueLabel = new Label(infoComposite, SWT.NULL);
pValueLabel.setText("p-Value: " + Float.toString(pValue));
pValueSlider.setMinimum(0);
pValueSlider.setMaximum((int) (histogram.getMax() * 10000));
System.out.println("Largest: " +histogram.getMax());
pValueSlider.setIncrement(1);
pValueSlider.setPageIncrement(5);
pValueSlider.setSelection((int) (pValue * 10000));
pValueSlider.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
pValue = (float) pValueSlider.getSelection() / 10000.00f;
System.out.println(pValue);
pValueLabel.setText("p-Value: " + Float.toString(pValue));
parentComposite.pack();
parentComposite.layout();
createVADelta();
filter.updateFilterManager();
// if (reducedVA != null)
// reducedNumberLabel.setText("# Genes: " +
// reducedVA.size());
}
});
Composite histoComposite = new Composite(parentComposite, SWT.NULL);
histoComposite.setLayout(new FillLayout(SWT.VERTICAL));
gridData.heightHint = 300;
// gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
histoComposite.setLayoutData(gridData);
RcpGLHistogramView histogramView = new RcpGLHistogramView();
histogramView.setDataDomain(DataDomainManager.get().getDataDomain(
"org.caleydo.datadomain.genetic"));
histogramView.createDefaultSerializedView();
histogramView.createPartControl(histoComposite);
((GLHistogram) (histogramView.getGLView())).setHistogram(histogram);
// Usually the canvas is registered to the GL animator in the
// PartListener.
// Because the GL histogram is no usual RCP view we have to do
// it on our
// own
GeneralManager.get().getViewGLCanvasManager()
.registerGLCanvasToAnimator(histogramView.getGLCanvas());
Monitor primary = parentComposite.getDisplay().getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = parentComposite.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
parentComposite.setLocation(x, y);
((Shell) parentComposite).open();
}
});
}
| public void create() {
super.create();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
GridData gridData = new GridData();
gridData.grabExcessHorizontalSpace = true;
// gridData.horizontalAlignment = GridData.FILL;
gridData.widthHint = 400;
gridData.heightHint = 50;
Composite infoComposite = new Composite(parentComposite, SWT.NULL);
infoComposite.setLayoutData(gridData);
infoComposite.setLayout(new FillLayout(SWT.VERTICAL));
final Slider pValueSlider = new Slider(infoComposite, SWT.HORIZONTAL);
final Label pValueLabel = new Label(infoComposite, SWT.NULL);
pValue = histogram.getMax();
pValueLabel.setText("p-Value: " + Float.toString(pValue));
pValueSlider.setMinimum(0);
pValueSlider.setMaximum((int) (histogram.getMax() * 10000));
pValueSlider.setIncrement(1);
pValueSlider.setPageIncrement(5);
pValueSlider.setSelection((int) (pValue * 10000));
pValueSlider.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
pValue = (float) pValueSlider.getSelection() / 10000.00f;
System.out.println(pValue);
pValueLabel.setText("p-Value: " + Float.toString(pValue));
parentComposite.pack();
parentComposite.layout();
createVADelta();
filter.updateFilterManager();
// if (reducedVA != null)
// reducedNumberLabel.setText("# Genes: " +
// reducedVA.size());
}
});
Composite histoComposite = new Composite(parentComposite, SWT.NULL);
histoComposite.setLayout(new FillLayout(SWT.VERTICAL));
gridData.heightHint = 300;
// gridData.verticalAlignment = GridData.FILL;
gridData.grabExcessVerticalSpace = true;
histoComposite.setLayoutData(gridData);
RcpGLHistogramView histogramView = new RcpGLHistogramView();
histogramView.setDataDomain(DataDomainManager.get().getDataDomain(
"org.caleydo.datadomain.genetic"));
histogramView.createDefaultSerializedView();
histogramView.createPartControl(histoComposite);
((GLHistogram) (histogramView.getGLView())).setHistogram(histogram);
// Usually the canvas is registered to the GL animator in the
// PartListener.
// Because the GL histogram is no usual RCP view we have to do
// it on our
// own
GeneralManager.get().getViewGLCanvasManager()
.registerGLCanvasToAnimator(histogramView.getGLCanvas());
Monitor primary = parentComposite.getDisplay().getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = parentComposite.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
parentComposite.setLocation(x, y);
((Shell) parentComposite).open();
}
});
}
|
diff --git a/src/org/x3chaos/rtd/RTDExecutor.java b/src/org/x3chaos/rtd/RTDExecutor.java
index d8e43cf..87be2df 100644
--- a/src/org/x3chaos/rtd/RTDExecutor.java
+++ b/src/org/x3chaos/rtd/RTDExecutor.java
@@ -1,255 +1,255 @@
package org.x3chaos.rtd;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.x3chaos.Utils;
import org.x3chaos.rtd.exception.InvalidOutcomeException;
public class RTDExecutor implements CommandExecutor {
private final RTDPlugin main;
/* Failure messages */
private static final String FAILURE_COOLDOWN = "You cannot roll for another %d seconds.";
/* Error messages */
private static final String[] ERROR_SYNTAX = {
"You would have rolled for %s, but there was an error.",
"Contact your server owner and report a problem with RTD's config.yml.",
"log=Check the syntax of all commands under outcome \"%s\"." };
private static final String[] ERROR_UNKNOWN = {
"You would have rolled for %s, but an unknown error occurred.",
"log=Alert the author of an unknown error in processing outcome \"%s\".",
"log=Include a Pastebin link to a full copy of config.yml." };
Server server;
Logger log;
public RTDExecutor(RTDPlugin main) {
this.main = main;
this.server = main.getServer();
this.log = main.getLogger();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String lbl, String[] args) {
// Get the outcome before anything else
Entry<String, List<String>> outcome = main.getRandomOutcome();
String outcomeName = outcome.getKey();
// Echo outcome name if console sender
if (!(sender instanceof Player)) {
sender.sendMessage("Outcome: " + outcomeName);
return true;
}
// Return false if there are any arguments
if (args.length != 0) return false;
/* Execute if above checks have been passed */
Player player = (Player) sender;
CommandSender console = server.getConsoleSender();
String typeOfCommand = "console";
String[] errorMessage = null;
Boolean success = true;
String failedCommand = "";
// Don't roll if still cooling down
long lastRoll = main.getLastRoll(player);
if (lastRoll != 0) {
lastRoll /= 1000;
if (isCoolingDown(lastRoll)) {
long left = getTimeLeft(lastRoll);
String message = String.format(FAILURE_COOLDOWN, left);
player.sendMessage(ChatColor.RED + message);
return true;
}
}
// Iterate through and execute each command
// List<String> commands = outcome.getValue();
List<String> commands = outcome.getValue();
for (int i = 0; i < commands.size(); i++) {
String command = commands.get(i);
// Replace {player}
if (command.contains("{player}")) {
- String name = player.getDisplayName();
+ String name = player.getName();
command = command.replace("{player}", name);
}
// Replace {world}
if (command.contains("{world}")) {
String world = player.getWorld().getName();
command = command.replace("{world}", world);
}
// Replace {rplayer}
if (command.contains("{rplayer}")) {
String rplayer = getRandomPlayer();
command = command.replace("{rplayer}", rplayer);
}
// Replace {rtime:xx-xx}
if (command.contains("{rtime:")) {
try {
command = doRandomTime(command);
} catch (InvalidOutcomeException ex) {
ex.setOutcome(outcome.getKey());
log.severe(ex.toString());
command = "";
}
}
// Determine command type (default: console)
if (command.startsWith("player=") || command.startsWith("console=")) {
String[] parts = command.split("=");
command = Utils.splitStringArray(parts, 1);
typeOfCommand = parts[0];
}
// Remove leading slash if present
if (command.startsWith("/")) command = command.substring(1);
// Execute command
log.info("Command: /" + command);
if (typeOfCommand.equals("player")) success = server.dispatchCommand(sender, command);
else success = server.dispatchCommand(console, command);
// If command returned false, log syntax error
if (!success) {
errorMessage = ERROR_SYNTAX;
failedCommand = command;
break;
}
// Set last roll to now. Doesn't count if there's an error.
main.setLastRoll(player, main.now());
}
// If nothing went wrong, we're done.
if (success) return true;
// Error is unknown if it's still null
if (errorMessage == null) errorMessage = ERROR_UNKNOWN;
// Report any errors to player and log
log.severe("Failed to execute command \"" + failedCommand + "\"");
for (int i = 0; i < errorMessage.length; i++) {
String message = errorMessage[i];
message = String.format(message, outcomeName);
if (message.startsWith("log=")) {
log.severe(message.split("=")[1]);
} else {
player.sendMessage(ChatColor.RED + message);
}
}
return true;
}
/**
* Determines whether the player is still cooling down
* @param lastRoll The player's last roll
* @return Whether the player is still cooling down
*/
private boolean isCoolingDown(long lastRoll) {
return isCoolingDown(lastRoll, main.now());
}
/**
* Determines whether the player is still cooling down
* @param lastRoll The player's last roll
* @param now The current time in millis
* @return Whether the player is still cooling down
*/
private boolean isCoolingDown(long lastRoll, long now) {
long since = now - lastRoll;
long cooldown = main.getCooldown();
return (since < cooldown);
}
/**
* Get time left for cooldown
* @param lastRoll The player's last roll
* @return How much time is left
*/
private long getTimeLeft(long lastRoll) {
long since = main.now() - lastRoll;
long cooldown = main.getCooldown();
return cooldown - since;
}
/**
* Gets a random player on the server
* @return A random player's display name
*/
private String getRandomPlayer() {
Player[] players = main.getServer().getOnlinePlayers();
int randomIndex = new Random().nextInt(players.length);
return players[randomIndex].getDisplayName();
}
/**
* Does the random time replacement. In a separate method because I hate nesting for loops.
* @param in the command input
* @return the command output
* @throws InvalidOutcomeException if parsing the rtime fails
*/
private String doRandomTime(String in) throws InvalidOutcomeException {
String result = "";
String[] split = in.split(" ");
for (int i = 0; i < split.length; i++) {
String arg = split[i];
String addition = "";
if (arg.matches("\\{rtime:\\d{1,5}-\\d{1,5}\\}")) {
try {
// parse the argument
addition = parseTimeArg(arg);
} catch (NumberFormatException ex) {
// create the exception, pass it to the block that calls doRandomTime()
throw new InvalidOutcomeException("invalid outcome variable " + arg);
}
} else {
// bypass the argument
addition = arg;
}
result += addition + " ";
}
return result.trim();
}
/**
* The actual rtime argument parsing method
* @param arg the argument to parse
* @return the time, parsed and converted to String
* @throws NumberFormatException
*/
private String parseTimeArg(String arg) throws NumberFormatException {
String[] rangeRaw = arg.split(":")[1].split("-");
int min, max;
min = Integer.parseInt(rangeRaw[0]);
max = rangeRaw[1].endsWith("}") ? Integer.parseInt(rangeRaw[1].substring(0,
rangeRaw[1].indexOf("}"))) : Integer.parseInt(rangeRaw[1]);
return String.valueOf(Utils.getRandomTime(min, max));
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String lbl, String[] args) {
// Get the outcome before anything else
Entry<String, List<String>> outcome = main.getRandomOutcome();
String outcomeName = outcome.getKey();
// Echo outcome name if console sender
if (!(sender instanceof Player)) {
sender.sendMessage("Outcome: " + outcomeName);
return true;
}
// Return false if there are any arguments
if (args.length != 0) return false;
/* Execute if above checks have been passed */
Player player = (Player) sender;
CommandSender console = server.getConsoleSender();
String typeOfCommand = "console";
String[] errorMessage = null;
Boolean success = true;
String failedCommand = "";
// Don't roll if still cooling down
long lastRoll = main.getLastRoll(player);
if (lastRoll != 0) {
lastRoll /= 1000;
if (isCoolingDown(lastRoll)) {
long left = getTimeLeft(lastRoll);
String message = String.format(FAILURE_COOLDOWN, left);
player.sendMessage(ChatColor.RED + message);
return true;
}
}
// Iterate through and execute each command
// List<String> commands = outcome.getValue();
List<String> commands = outcome.getValue();
for (int i = 0; i < commands.size(); i++) {
String command = commands.get(i);
// Replace {player}
if (command.contains("{player}")) {
String name = player.getDisplayName();
command = command.replace("{player}", name);
}
// Replace {world}
if (command.contains("{world}")) {
String world = player.getWorld().getName();
command = command.replace("{world}", world);
}
// Replace {rplayer}
if (command.contains("{rplayer}")) {
String rplayer = getRandomPlayer();
command = command.replace("{rplayer}", rplayer);
}
// Replace {rtime:xx-xx}
if (command.contains("{rtime:")) {
try {
command = doRandomTime(command);
} catch (InvalidOutcomeException ex) {
ex.setOutcome(outcome.getKey());
log.severe(ex.toString());
command = "";
}
}
// Determine command type (default: console)
if (command.startsWith("player=") || command.startsWith("console=")) {
String[] parts = command.split("=");
command = Utils.splitStringArray(parts, 1);
typeOfCommand = parts[0];
}
// Remove leading slash if present
if (command.startsWith("/")) command = command.substring(1);
// Execute command
log.info("Command: /" + command);
if (typeOfCommand.equals("player")) success = server.dispatchCommand(sender, command);
else success = server.dispatchCommand(console, command);
// If command returned false, log syntax error
if (!success) {
errorMessage = ERROR_SYNTAX;
failedCommand = command;
break;
}
// Set last roll to now. Doesn't count if there's an error.
main.setLastRoll(player, main.now());
}
// If nothing went wrong, we're done.
if (success) return true;
// Error is unknown if it's still null
if (errorMessage == null) errorMessage = ERROR_UNKNOWN;
// Report any errors to player and log
log.severe("Failed to execute command \"" + failedCommand + "\"");
for (int i = 0; i < errorMessage.length; i++) {
String message = errorMessage[i];
message = String.format(message, outcomeName);
if (message.startsWith("log=")) {
log.severe(message.split("=")[1]);
} else {
player.sendMessage(ChatColor.RED + message);
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String lbl, String[] args) {
// Get the outcome before anything else
Entry<String, List<String>> outcome = main.getRandomOutcome();
String outcomeName = outcome.getKey();
// Echo outcome name if console sender
if (!(sender instanceof Player)) {
sender.sendMessage("Outcome: " + outcomeName);
return true;
}
// Return false if there are any arguments
if (args.length != 0) return false;
/* Execute if above checks have been passed */
Player player = (Player) sender;
CommandSender console = server.getConsoleSender();
String typeOfCommand = "console";
String[] errorMessage = null;
Boolean success = true;
String failedCommand = "";
// Don't roll if still cooling down
long lastRoll = main.getLastRoll(player);
if (lastRoll != 0) {
lastRoll /= 1000;
if (isCoolingDown(lastRoll)) {
long left = getTimeLeft(lastRoll);
String message = String.format(FAILURE_COOLDOWN, left);
player.sendMessage(ChatColor.RED + message);
return true;
}
}
// Iterate through and execute each command
// List<String> commands = outcome.getValue();
List<String> commands = outcome.getValue();
for (int i = 0; i < commands.size(); i++) {
String command = commands.get(i);
// Replace {player}
if (command.contains("{player}")) {
String name = player.getName();
command = command.replace("{player}", name);
}
// Replace {world}
if (command.contains("{world}")) {
String world = player.getWorld().getName();
command = command.replace("{world}", world);
}
// Replace {rplayer}
if (command.contains("{rplayer}")) {
String rplayer = getRandomPlayer();
command = command.replace("{rplayer}", rplayer);
}
// Replace {rtime:xx-xx}
if (command.contains("{rtime:")) {
try {
command = doRandomTime(command);
} catch (InvalidOutcomeException ex) {
ex.setOutcome(outcome.getKey());
log.severe(ex.toString());
command = "";
}
}
// Determine command type (default: console)
if (command.startsWith("player=") || command.startsWith("console=")) {
String[] parts = command.split("=");
command = Utils.splitStringArray(parts, 1);
typeOfCommand = parts[0];
}
// Remove leading slash if present
if (command.startsWith("/")) command = command.substring(1);
// Execute command
log.info("Command: /" + command);
if (typeOfCommand.equals("player")) success = server.dispatchCommand(sender, command);
else success = server.dispatchCommand(console, command);
// If command returned false, log syntax error
if (!success) {
errorMessage = ERROR_SYNTAX;
failedCommand = command;
break;
}
// Set last roll to now. Doesn't count if there's an error.
main.setLastRoll(player, main.now());
}
// If nothing went wrong, we're done.
if (success) return true;
// Error is unknown if it's still null
if (errorMessage == null) errorMessage = ERROR_UNKNOWN;
// Report any errors to player and log
log.severe("Failed to execute command \"" + failedCommand + "\"");
for (int i = 0; i < errorMessage.length; i++) {
String message = errorMessage[i];
message = String.format(message, outcomeName);
if (message.startsWith("log=")) {
log.severe(message.split("=")[1]);
} else {
player.sendMessage(ChatColor.RED + message);
}
}
return true;
}
|
diff --git a/src/org/acplt/oncrpc/OncRpcUdpClient.java b/src/org/acplt/oncrpc/OncRpcUdpClient.java
index 263b260..7151b77 100644
--- a/src/org/acplt/oncrpc/OncRpcUdpClient.java
+++ b/src/org/acplt/oncrpc/OncRpcUdpClient.java
@@ -1,723 +1,728 @@
/*
* $Header$
*
* Copyright (c) 1999, 2000
* Lehrstuhl fuer Prozessleittechnik (PLT), RWTH Aachen
* D-52064 Aachen, Germany.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this program (see the file COPYING.LIB for more
* details); if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.acplt.oncrpc;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.DatagramSocket;
/**
* ONC/RPC client which communicates with ONC/RPC servers over the network
* using the datagram-oriented protocol UDP/IP.
*
* @version $Revision$ $Date$ $State$ $Locker$
* @author Harald Albrecht
*/
public class OncRpcUdpClient extends OncRpcClient {
/**
* Constructs a new <code>OncRpcUdpClient</code> object, which connects
* to the ONC/RPC server at <code>host</code> for calling remote procedures
* of the given { program, version }.
*
* <p>Note that the construction of an <code>OncRpcUdpProtocolClient</code>
* object will result in communication with the portmap process at
* <code>host</code> if <code>port</code> is <code>0</code>.
*
* @param host The host where the ONC/RPC server resides.
* @param program Program number of the ONC/RPC server to call.
* @param version Program version number.
* @param port The port number where the ONC/RPC server can be contacted.
* If <code>0</code>, then the <code>OncRpcUdpClient</code> object will
* ask the portmapper at <code>host</code> for the port number.
*
* @throws OncRpcException if an ONC/RPC error occurs.
* @throws IOException if an I/O error occurs.
*/
public OncRpcUdpClient(InetAddress host,
int program, int version,
int port)
throws OncRpcException, IOException {
this(host, program, version, port, 8192);
}
/**
* Constructs a new <code>OncRpcUdpClient</code> object, which connects
* to the ONC/RPC server at <code>host</code> for calling remote procedures
* of the given { program, version }.
*
* <p>Note that the construction of an <code>OncRpcUdpProtocolClient</code>
* object will result in communication with the portmap process at
* <code>host</code> if <code>port</code> is <code>0</code>.
*
* @param host The host where the ONC/RPC server resides.
* @param program Program number of the ONC/RPC server to call.
* @param version Program version number.
* @param port The port number where the ONC/RPC server can be contacted.
* If <code>0</code>, then the <code>OncRpcUdpClient</code> object will
* ask the portmapper at <code>host</code> for the port number.
* @param bufferSize The buffer size used for sending and receiving UDP
* datagrams.
*
* @throws OncRpcException if an ONC/RPC error occurs.
* @throws IOException if an I/O error occurs.
*/
public OncRpcUdpClient(InetAddress host,
int program, int version,
int port,
int bufferSize)
throws OncRpcException, IOException {
//
// Construct the inherited part of our object. This will also try to
// lookup the port of the desired ONC/RPC server, if no port number
// was specified (port = 0).
//
super(host, program, version, port, OncRpcProtocols.ONCRPC_UDP);
//
// Let the host operating system choose which port (and network
// interface) to use. Then set the buffer sizes for sending and
// receiving UDP datagrams. Finally set the destination of packets.
//
if ( bufferSize < 1024 ) {
bufferSize = 1024;
}
socket = new DatagramSocket();
socketHelper = new OncRpcUdpSocketHelper(socket);
if ( socketHelper.getSendBufferSize() < bufferSize ) {
socketHelper.setSendBufferSize(bufferSize);
}
if ( socketHelper.getReceiveBufferSize() < bufferSize ) {
socketHelper.setReceiveBufferSize(bufferSize);
}
//
// Note: we don't do a
// socket.connect(host, this.port);
// here anymore. XdrUdpEncodingStream long since then supported
// specifying the destination of an ONC/RPC UDP packet when
// start serialization. In addition, connecting a UDP socket disables
// the socket's ability to receive broadcasts. Without connecting you
// can send an ONC/RPC call to the broadcast address of the network
// and receive multiple replies.
//
// Create the necessary encoding and decoding streams, so we can
// communicate at all.
//
sendingXdr = new XdrUdpEncodingStream(socket, bufferSize);
receivingXdr = new XdrUdpDecodingStream(socket, bufferSize);
}
/**
* Close the connection to an ONC/RPC server and free all network-related
* resources. Well -- at least hope, that the Java VM will sometimes free
* some resources. Sigh.
*
* @throws OncRpcException if an ONC/RPC error occurs.
*/
public void close()
throws OncRpcException {
if ( socket != null ) {
socket.close();
socket = null;
}
if ( sendingXdr != null ) {
try {
sendingXdr.close();
} catch ( IOException e ) {
}
sendingXdr = null;
}
if ( receivingXdr != null ) {
try {
receivingXdr.close();
} catch ( IOException e ) {
}
receivingXdr = null;
}
}
/**
* Calls a remote procedure on an ONC/RPC server.
*
* <p>The <code>OncRpcUdpClient</code> uses a similar timeout scheme as
* the genuine Sun C implementation of ONC/RPC: it starts with a timeout
* of one second when waiting for a reply. If no reply is received within
* this time frame, the client doubles the timeout, sends a new request
* and then waits again for a reply. In every case the client will wait
* no longer than the total timeout set through the
* {@link #setTimeout(int)} method.
*
* @param procedureNumber Procedure number of the procedure to call.
* @param versionNumber Protocol version number.
* @param params The parameters of the procedure to call, contained
* in an object which implements the {@link XdrAble} interface.
* @param result The object receiving the result of the procedure call.
*
* @throws OncRpcException if an ONC/RPC error occurs.
*/
public synchronized void call(int procedureNumber, int versionNumber,
XdrAble params, XdrAble result)
throws OncRpcException {
Refresh:
for ( int refreshesLeft = 1; refreshesLeft >= 0;
--refreshesLeft ) {
//
// First, build the ONC/RPC call header. Then put the sending
// stream into a known state and encode the parameters to be
// sent. Finally tell the encoding stream to send all its data
// to the server. Then wait for an answer, receive it and decode
// it. So that's the bottom line of what we do right here.
//
nextXid();
//
// We only create our request message once and reuse it in case
// retransmission should be necessary -- with the exception being
// credential refresh. In this case we need to create a new
// request message.
//
OncRpcClientCallMessage callHeader =
new OncRpcClientCallMessage(xid,
program, versionNumber,
procedureNumber,
auth);
OncRpcClientReplyMessage replyHeader =
new OncRpcClientReplyMessage(auth);
long stopTime = System.currentTimeMillis() + timeout;
int resendTimeout = retransmissionTimeout;
//
// Now enter the great loop where we send calls out to the server
// and then sit there waiting for a reply. If none comes, we first
// resend our call after one second, then two seconds, four seconds,
// and so on, until we have reached the timeout for the call in total.
// Note that this setting only applies if exponential back-off
// retransmission has been selected. Per default we do not retransmit
// any more, in order to be in line with the SUNRPC implementations.
//
do {
try {
//
// Send call message to server. Remember that we've already
// "connected" the datagram socket, so java.net knows whom
// to send the datagram packets.
//
sendingXdr.beginEncoding(host, port);
callHeader.xdrEncode(sendingXdr);
params.xdrEncode(sendingXdr);
sendingXdr.endEncoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTSEND,
e.getLocalizedMessage()));
}
//
// Receive reply message from server -- at least try to do so...
// In case of batched calls we don't need no stinkin' answer, so
// we can do other, more interesting things.
//
if ( timeout == 0 ) {
return;
}
//
// Wait for an answer to arrive...
//
for ( ;; ) {
try {
int currentTimeout = (int)(stopTime - System.currentTimeMillis());
if ( currentTimeout > resendTimeout ) {
currentTimeout = resendTimeout;
- } else if ( currentTimeout < 0 ) {
- currentTimeout = 0;
+ } else if ( currentTimeout < 1 ) {
+ //
+ // as setSoTimeout interprets a timeout of zero as
+ // infinite (?�$@%&!!!) we need to ensure that we
+ // have a finite timeout, albeit maybe an infinitesimal
+ // finite one.
+ currentTimeout = 1;
}
socket.setSoTimeout(currentTimeout);
receivingXdr.beginDecoding();
//
// Only accept incomming reply if it comes from the same
// address we've sent the ONC/RPC call to. Otherwise throw
// away the datagram packet containing the reply and start
// over again, waiting for the next reply to arrive.
//
if ( host.equals(receivingXdr.getSenderAddress()) ) {
//
// First, pull off the reply message header of the
// XDR stream. In case we also received a verifier
// from the server and this verifier was invalid, broken
// or tampered with, we will get an
// OncRpcAuthenticationException right here, which will
// propagate up to the caller. If the server reported
// an authentication problem itself, then this will
// be handled as any other rejected ONC/RPC call.
//
try {
replyHeader.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Only deserialize the result, if the reply matches the call
// and if the reply signals a successful call. In case of an
// unsuccessful call (which mathes our call nevertheless) throw
// an exception.
//
if ( replyHeader.messageId == callHeader.messageId ) {
if ( !replyHeader.successfullyAccepted() ) {
receivingXdr.endDecoding();
//
// Check whether there was an authentication
// problem. In this case first try to refresh the
// credentials.
//
if ( (refreshesLeft > 0)
&& (replyHeader.replyStatus
== OncRpcReplyStatus.ONCRPC_MSG_DENIED)
&& (replyHeader.rejectStatus
== OncRpcRejectStatus.ONCRPC_AUTH_ERROR)
&& (auth != null)
&& auth.canRefreshCred() ) {
//
// Think about using a TAB size of four ;)
//
// Another instance of "CONTINUE considered
// useful"...
//
continue Refresh;
}
//
// Nope. No chance. This gets tough.
//
throw(replyHeader.newException());
}
//
// The reply header is okay and the call had been
// accepted by the ONC/RPC server, so we can now
// proceed to decode the outcome of the RPC.
//
try {
result.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Free pending resources of buffer and exit the call loop,
// returning the reply to the caller through the result
// object.
//
receivingXdr.endDecoding();
return;
} else {
//
// The message id did no match -- probably some
// old UDP datagram which just popped up from the
// middle of the Internet.
//
// Yet another case of "CONTINUE considered not
// harmful"...
//
// [Nothing to do here, just wait for the next datagram]
}
} else {
//
// IP address of received UDP datagram is not the same
// as the IP address of the ONC/RPC server.
//
// [Nothing to do here, just wait for the next datagram]
}
} catch ( InterruptedIOException e ) {
//
// Note that we only catch timeouts here, but no other
// exceptions. Those others will go up further until someone
// catches them. The timeouts are caught, so they can do no
// damage but instead we start another round of sending a
// request and waiting for a reply. Reminds me of NASA and
// their "Mars Polar Lander"...
//
// Note that we need to leave the inner waiting loop here,
// as we might need to resend the (lost) RPC request
// datagram.
//
break;
} catch ( IOException e ) {
//
// Argh. Trouble with the transport. Seems like we can't
// receive data. Gosh. Go away!
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
} catch ( OncRpcException e ) {
//
// Ooops. An ONC/RPC exception. Let us rethrow this one,
// as we won't have nothin' to do with it...
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
//
// Well, in case we got not a *reply* RPC message back,
// we keep listening for messages.
//
if ( e.getReason() != OncRpcException.RPC_WRONGMESSAGE ) {
throw(e);
}
}
//
// We can not make use of the reply we just received, so
// we need to dump it.
//
// This should raise no exceptions, when skipping the UDP
// record. So if one is raised, we will rethrow an ONC/RPC
// exception instead.
//
try {
receivingXdr.endDecoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
}
}
//
// We only reach this code part beyond the inner waiting
// loop if we run in a timeout and might need to retransmit
//
// According to the retransmission strategy choosen, update the
// current retransmission (resending) timeout.
//
if ( retransmissionMode == OncRpcUdpRetransmissionMode.EXPONENTIAL ) {
resendTimeout *= 2;
}
} while ( System.currentTimeMillis() < stopTime );
//
// That's it -- this shity server does not talk to us. Now, due to
// the indecent language used in the previous sentence, this software
// can not be exported any longer to some countries of the world.
// But this is surely not my problem, but rather theirs. So go away
// and hide yourself in the dark with all your zombies (or maybe
// kangaroos).
//
throw(new OncRpcTimeoutException());
} // for ( refreshesLeft )
}
/**
* Broadcast a remote procedure call to several ONC/RPC servers. For this
* you'll need to specify either a multicast address or the subnet's
* broadcast address when creating a <code>OncRpcUdpClient</code>. For
* every reply received, an event containing the reply is sent to the
* OncRpcBroadcastListener <code>listener</code>, which is the last
* parameter to the this method.
*
* <p>In contrast to the {@link #call(int, XdrAble, XdrAble)} method,
* <code>broadcastCall</code> will only send the ONC/RPC call once. It
* will then wait for answers until the timeout as set by
* {@link #setTimeout(int)} expires without resending the reply.
*
* <p>Note that you might experience unwanted results when using
* authentication types other than {@link OncRpcClientAuthNone}, causing
* messed up authentication protocol handling objects. This depends on
* the type of authentication used. For <code>AUTH_UNIX</code> nothing
* bad happens as long as none of the servers replies with a shorthand
* verifier. If it does, then this shorthand will be used on all subsequent
* ONC/RPC calls, something you probably do not want at all.
*
* @param procedureNumber Procedure number of the procedure to call.
* @param params The parameters of the procedure to call, contained
* in an object which implements the {@link XdrAble} interface.
* @param result The object receiving the result of the procedure call.
* Note that this object is reused to deserialize all incomming replies
* one after another.
* @param listener Listener which will get an {@link OncRpcBroadcastEvent}
* for every reply received.
*
* @throws OncRpcException if an ONC/RPC error occurs.
*/
public synchronized void broadcastCall(int procedureNumber,
XdrAble params, XdrAble result,
OncRpcBroadcastListener listener)
throws OncRpcException {
//
// First, build the ONC/RPC call header. Then put the sending
// stream into a known state and encode the parameters to be
// sent. Finally tell the encoding stream to broadcast all its data.
// Then wait for answers, receive and decode them one at a time.
//
nextXid();
OncRpcClientCallMessage callHeader =
new OncRpcClientCallMessage(xid,
program, version, procedureNumber,
auth);
OncRpcClientReplyMessage replyHeader =
new OncRpcClientReplyMessage(auth);
//
// Broadcast the call. Note that we send the call only once and will
// never resend it.
//
try {
//
// Send call message to server. Remember that we've already
// "connected" the datagram socket, so java.net knows whom
// to send the datagram packets.
//
sendingXdr.beginEncoding(host, port);
callHeader.xdrEncode(sendingXdr);
params.xdrEncode(sendingXdr);
sendingXdr.endEncoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTSEND,
e.getLocalizedMessage()));
}
//
// Now enter the great loop where sit waiting for replies to our
// broadcast call to come in. In every case, we wait until the
// (total) timeout expires.
//
long stopTime = System.currentTimeMillis() + timeout;
do {
try {
//
// Calculate timeout until the total timeout is reached, so
// we can try to meet the overall deadline.
//
int currentTimeout = (int)(stopTime - System.currentTimeMillis());
if ( currentTimeout < 0 ) {
currentTimeout = 0;
}
socket.setSoTimeout(currentTimeout);
//
// Then wait for datagrams to arrive...
//
receivingXdr.beginDecoding();
replyHeader.xdrDecode(receivingXdr);
//
// Only deserialize the result, if the reply matches the call
// and if the reply signals a successful call. In case of an
// unsuccessful call (which mathes our call nevertheless) throw
// an exception.
//
if ( replyHeader.messageId == callHeader.messageId ) {
if ( !replyHeader.successfullyAccepted() ) {
//
// We got a notification of a rejected call. We silently
// ignore such replies and continue listening for other
// replies.
//
receivingXdr.endDecoding();
/* fall through to time check */
}
result.xdrDecode(receivingXdr);
//
// Notify a potential listener of the reply.
//
if ( listener != null ) {
OncRpcBroadcastEvent evt = new OncRpcBroadcastEvent(
this,
receivingXdr.getSenderAddress(),
procedureNumber, params, result);
listener.replyReceived(evt);
}
//
// Free pending resources of buffer and exit the call loop,
// returning the reply to the caller through the result
// object.
//
receivingXdr.endDecoding();
/* fall through to time check */
} else {
//
// This should raise no exceptions, when skipping the UDP
// record. So if one is raised, we will rethrow an ONC/RPC
// exception instead.
//
try {
receivingXdr.endDecoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
}
/* fall through to time check */
}
} catch ( InterruptedIOException e ) {
//
// Note that we only catch timeouts here, but no other
// exceptions. Those others will go up further until someone
// catches them. If we get the timeout we know that it
// could be time to leave the stage and so we fall through
// to the total timeout check.
//
/* fall through to time check */
} catch ( IOException e ) {
//
// Argh. Trouble with the transport. Seems like we can't
// receive data. Gosh. Go away!
//
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
}
} while ( System.currentTimeMillis() < stopTime );
return;
}
/**
* Set the {@link OncRpcUdpRetransmissionMode retransmission mode} for
* lost remote procedure calls. The default retransmission mode is
* {@link OncRpcUdpRetransmissionMode#FIXED}.
*
* @param mode Retransmission mode (either fixed or exponential).
*/
public void setRetransmissionMode(int mode) {
retransmissionMode = mode;
}
/**
* Retrieve the current
* {@link OncRpcUdpRetransmissionMode retransmission mode} set for
* retransmission of lost ONC/RPC calls.
*
* @return Current retransmission mode.
*/
public int getRetransmissionMode() {
return retransmissionMode;
}
/**
* Set the retransmission timout for remote procedure calls to wait for
* an answer from the ONC/RPC server before resending the call. The
* default retransmission timeout is the 30 seconds. The retransmission
* timeout must be > 0. To disable retransmission of lost calls, set
* the retransmission timeout to be the same value as the timeout.
*
* @param milliseconds Timeout in milliseconds. A timeout of zero indicates
* batched calls.
*/
public void setRetransmissionTimeout(int milliseconds) {
if ( milliseconds <= 0 ) {
throw(new IllegalArgumentException("timeouts must be positive."));
}
retransmissionTimeout = milliseconds;
}
/**
* Retrieve the current retransmission timeout set for remote procedure
* calls.
*
* @return Current retransmission timeout.
*/
public int getRetransmissionTimeout() {
return retransmissionTimeout;
}
/**
* Set the character encoding for (de-)serializing strings.
*
* @param characterEncoding the encoding to use for (de-)serializing strings.
* If <code>null</code>, the system's default encoding is to be used.
*/
public void setCharacterEncoding(String characterEncoding) {
receivingXdr.setCharacterEncoding(characterEncoding);
sendingXdr.setCharacterEncoding(characterEncoding);
}
/**
* Get the character encoding for (de-)serializing strings.
*
* @return the encoding currently used for (de-)serializing strings.
* If <code>null</code>, then the system's default encoding is used.
*/
public String getCharacterEncoding() {
return receivingXdr.getCharacterEncoding();
}
/**
* UDP socket used for datagram-based communication with an ONC/RPC
* server.
*/
private DatagramSocket socket;
/**
* Socket helper object supplying missing methods for JDK 1.1
* backwards compatibility. So much for compile once, does not run
* everywhere.
*/
private OncRpcUdpSocketHelper socketHelper;
/**
* XDR encoding stream used for sending requests via UDP/IP to an ONC/RPC
* server.
*/
protected XdrUdpEncodingStream sendingXdr;
/**
* XDR decoding stream used when receiving replies via UDP/IP from an
* ONC/RPC server.
*/
protected XdrUdpDecodingStream receivingXdr;
/**
* Retransmission timeout used for resending ONC/RPC calls when an ONC/RPC
* server does not answer fast enough. The default retransmission timeout
* is identical to the overall timeout for ONC/RPC calls (thus UDP/IP-based
* clients will not retransmit lost calls).
*
* @see OncRpcUdpClient#retransmissionMode
* @see OncRpcClient#setTimeout
*/
protected int retransmissionTimeout = super.timeout;
/**
* Retransmission mode used when resending ONC/RPC calls. Default mode is
* {@link OncRpcUdpRetransmissionMode#FIXED fixed timeout mode}.
*
* @see OncRpcUdpRetransmissionMode
*/
protected int retransmissionMode = OncRpcUdpRetransmissionMode.FIXED;
}
// End of OncRpcUdpClient.java
| true | true | public synchronized void call(int procedureNumber, int versionNumber,
XdrAble params, XdrAble result)
throws OncRpcException {
Refresh:
for ( int refreshesLeft = 1; refreshesLeft >= 0;
--refreshesLeft ) {
//
// First, build the ONC/RPC call header. Then put the sending
// stream into a known state and encode the parameters to be
// sent. Finally tell the encoding stream to send all its data
// to the server. Then wait for an answer, receive it and decode
// it. So that's the bottom line of what we do right here.
//
nextXid();
//
// We only create our request message once and reuse it in case
// retransmission should be necessary -- with the exception being
// credential refresh. In this case we need to create a new
// request message.
//
OncRpcClientCallMessage callHeader =
new OncRpcClientCallMessage(xid,
program, versionNumber,
procedureNumber,
auth);
OncRpcClientReplyMessage replyHeader =
new OncRpcClientReplyMessage(auth);
long stopTime = System.currentTimeMillis() + timeout;
int resendTimeout = retransmissionTimeout;
//
// Now enter the great loop where we send calls out to the server
// and then sit there waiting for a reply. If none comes, we first
// resend our call after one second, then two seconds, four seconds,
// and so on, until we have reached the timeout for the call in total.
// Note that this setting only applies if exponential back-off
// retransmission has been selected. Per default we do not retransmit
// any more, in order to be in line with the SUNRPC implementations.
//
do {
try {
//
// Send call message to server. Remember that we've already
// "connected" the datagram socket, so java.net knows whom
// to send the datagram packets.
//
sendingXdr.beginEncoding(host, port);
callHeader.xdrEncode(sendingXdr);
params.xdrEncode(sendingXdr);
sendingXdr.endEncoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTSEND,
e.getLocalizedMessage()));
}
//
// Receive reply message from server -- at least try to do so...
// In case of batched calls we don't need no stinkin' answer, so
// we can do other, more interesting things.
//
if ( timeout == 0 ) {
return;
}
//
// Wait for an answer to arrive...
//
for ( ;; ) {
try {
int currentTimeout = (int)(stopTime - System.currentTimeMillis());
if ( currentTimeout > resendTimeout ) {
currentTimeout = resendTimeout;
} else if ( currentTimeout < 0 ) {
currentTimeout = 0;
}
socket.setSoTimeout(currentTimeout);
receivingXdr.beginDecoding();
//
// Only accept incomming reply if it comes from the same
// address we've sent the ONC/RPC call to. Otherwise throw
// away the datagram packet containing the reply and start
// over again, waiting for the next reply to arrive.
//
if ( host.equals(receivingXdr.getSenderAddress()) ) {
//
// First, pull off the reply message header of the
// XDR stream. In case we also received a verifier
// from the server and this verifier was invalid, broken
// or tampered with, we will get an
// OncRpcAuthenticationException right here, which will
// propagate up to the caller. If the server reported
// an authentication problem itself, then this will
// be handled as any other rejected ONC/RPC call.
//
try {
replyHeader.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Only deserialize the result, if the reply matches the call
// and if the reply signals a successful call. In case of an
// unsuccessful call (which mathes our call nevertheless) throw
// an exception.
//
if ( replyHeader.messageId == callHeader.messageId ) {
if ( !replyHeader.successfullyAccepted() ) {
receivingXdr.endDecoding();
//
// Check whether there was an authentication
// problem. In this case first try to refresh the
// credentials.
//
if ( (refreshesLeft > 0)
&& (replyHeader.replyStatus
== OncRpcReplyStatus.ONCRPC_MSG_DENIED)
&& (replyHeader.rejectStatus
== OncRpcRejectStatus.ONCRPC_AUTH_ERROR)
&& (auth != null)
&& auth.canRefreshCred() ) {
//
// Think about using a TAB size of four ;)
//
// Another instance of "CONTINUE considered
// useful"...
//
continue Refresh;
}
//
// Nope. No chance. This gets tough.
//
throw(replyHeader.newException());
}
//
// The reply header is okay and the call had been
// accepted by the ONC/RPC server, so we can now
// proceed to decode the outcome of the RPC.
//
try {
result.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Free pending resources of buffer and exit the call loop,
// returning the reply to the caller through the result
// object.
//
receivingXdr.endDecoding();
return;
} else {
//
// The message id did no match -- probably some
// old UDP datagram which just popped up from the
// middle of the Internet.
//
// Yet another case of "CONTINUE considered not
// harmful"...
//
// [Nothing to do here, just wait for the next datagram]
}
} else {
//
// IP address of received UDP datagram is not the same
// as the IP address of the ONC/RPC server.
//
// [Nothing to do here, just wait for the next datagram]
}
} catch ( InterruptedIOException e ) {
//
// Note that we only catch timeouts here, but no other
// exceptions. Those others will go up further until someone
// catches them. The timeouts are caught, so they can do no
// damage but instead we start another round of sending a
// request and waiting for a reply. Reminds me of NASA and
// their "Mars Polar Lander"...
//
// Note that we need to leave the inner waiting loop here,
// as we might need to resend the (lost) RPC request
// datagram.
//
break;
} catch ( IOException e ) {
//
// Argh. Trouble with the transport. Seems like we can't
// receive data. Gosh. Go away!
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
} catch ( OncRpcException e ) {
//
// Ooops. An ONC/RPC exception. Let us rethrow this one,
// as we won't have nothin' to do with it...
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
//
// Well, in case we got not a *reply* RPC message back,
// we keep listening for messages.
//
if ( e.getReason() != OncRpcException.RPC_WRONGMESSAGE ) {
throw(e);
}
}
//
// We can not make use of the reply we just received, so
// we need to dump it.
//
// This should raise no exceptions, when skipping the UDP
// record. So if one is raised, we will rethrow an ONC/RPC
// exception instead.
//
try {
receivingXdr.endDecoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
}
}
//
// We only reach this code part beyond the inner waiting
// loop if we run in a timeout and might need to retransmit
//
// According to the retransmission strategy choosen, update the
// current retransmission (resending) timeout.
//
if ( retransmissionMode == OncRpcUdpRetransmissionMode.EXPONENTIAL ) {
resendTimeout *= 2;
}
} while ( System.currentTimeMillis() < stopTime );
//
// That's it -- this shity server does not talk to us. Now, due to
// the indecent language used in the previous sentence, this software
// can not be exported any longer to some countries of the world.
// But this is surely not my problem, but rather theirs. So go away
// and hide yourself in the dark with all your zombies (or maybe
// kangaroos).
//
throw(new OncRpcTimeoutException());
} // for ( refreshesLeft )
}
| public synchronized void call(int procedureNumber, int versionNumber,
XdrAble params, XdrAble result)
throws OncRpcException {
Refresh:
for ( int refreshesLeft = 1; refreshesLeft >= 0;
--refreshesLeft ) {
//
// First, build the ONC/RPC call header. Then put the sending
// stream into a known state and encode the parameters to be
// sent. Finally tell the encoding stream to send all its data
// to the server. Then wait for an answer, receive it and decode
// it. So that's the bottom line of what we do right here.
//
nextXid();
//
// We only create our request message once and reuse it in case
// retransmission should be necessary -- with the exception being
// credential refresh. In this case we need to create a new
// request message.
//
OncRpcClientCallMessage callHeader =
new OncRpcClientCallMessage(xid,
program, versionNumber,
procedureNumber,
auth);
OncRpcClientReplyMessage replyHeader =
new OncRpcClientReplyMessage(auth);
long stopTime = System.currentTimeMillis() + timeout;
int resendTimeout = retransmissionTimeout;
//
// Now enter the great loop where we send calls out to the server
// and then sit there waiting for a reply. If none comes, we first
// resend our call after one second, then two seconds, four seconds,
// and so on, until we have reached the timeout for the call in total.
// Note that this setting only applies if exponential back-off
// retransmission has been selected. Per default we do not retransmit
// any more, in order to be in line with the SUNRPC implementations.
//
do {
try {
//
// Send call message to server. Remember that we've already
// "connected" the datagram socket, so java.net knows whom
// to send the datagram packets.
//
sendingXdr.beginEncoding(host, port);
callHeader.xdrEncode(sendingXdr);
params.xdrEncode(sendingXdr);
sendingXdr.endEncoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTSEND,
e.getLocalizedMessage()));
}
//
// Receive reply message from server -- at least try to do so...
// In case of batched calls we don't need no stinkin' answer, so
// we can do other, more interesting things.
//
if ( timeout == 0 ) {
return;
}
//
// Wait for an answer to arrive...
//
for ( ;; ) {
try {
int currentTimeout = (int)(stopTime - System.currentTimeMillis());
if ( currentTimeout > resendTimeout ) {
currentTimeout = resendTimeout;
} else if ( currentTimeout < 1 ) {
//
// as setSoTimeout interprets a timeout of zero as
// infinite (?�$@%&!!!) we need to ensure that we
// have a finite timeout, albeit maybe an infinitesimal
// finite one.
currentTimeout = 1;
}
socket.setSoTimeout(currentTimeout);
receivingXdr.beginDecoding();
//
// Only accept incomming reply if it comes from the same
// address we've sent the ONC/RPC call to. Otherwise throw
// away the datagram packet containing the reply and start
// over again, waiting for the next reply to arrive.
//
if ( host.equals(receivingXdr.getSenderAddress()) ) {
//
// First, pull off the reply message header of the
// XDR stream. In case we also received a verifier
// from the server and this verifier was invalid, broken
// or tampered with, we will get an
// OncRpcAuthenticationException right here, which will
// propagate up to the caller. If the server reported
// an authentication problem itself, then this will
// be handled as any other rejected ONC/RPC call.
//
try {
replyHeader.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Only deserialize the result, if the reply matches the call
// and if the reply signals a successful call. In case of an
// unsuccessful call (which mathes our call nevertheless) throw
// an exception.
//
if ( replyHeader.messageId == callHeader.messageId ) {
if ( !replyHeader.successfullyAccepted() ) {
receivingXdr.endDecoding();
//
// Check whether there was an authentication
// problem. In this case first try to refresh the
// credentials.
//
if ( (refreshesLeft > 0)
&& (replyHeader.replyStatus
== OncRpcReplyStatus.ONCRPC_MSG_DENIED)
&& (replyHeader.rejectStatus
== OncRpcRejectStatus.ONCRPC_AUTH_ERROR)
&& (auth != null)
&& auth.canRefreshCred() ) {
//
// Think about using a TAB size of four ;)
//
// Another instance of "CONTINUE considered
// useful"...
//
continue Refresh;
}
//
// Nope. No chance. This gets tough.
//
throw(replyHeader.newException());
}
//
// The reply header is okay and the call had been
// accepted by the ONC/RPC server, so we can now
// proceed to decode the outcome of the RPC.
//
try {
result.xdrDecode(receivingXdr);
} catch ( OncRpcException e ) {
//
// ** SF bug #1262106 **
//
// We ran into some sort of trouble. Usually this will have
// been a buffer underflow. Whatever, end the decoding process
// and ensure this way that the next call has a chance to start
// from a clean state.
//
receivingXdr.endDecoding();
throw(e);
}
//
// Free pending resources of buffer and exit the call loop,
// returning the reply to the caller through the result
// object.
//
receivingXdr.endDecoding();
return;
} else {
//
// The message id did no match -- probably some
// old UDP datagram which just popped up from the
// middle of the Internet.
//
// Yet another case of "CONTINUE considered not
// harmful"...
//
// [Nothing to do here, just wait for the next datagram]
}
} else {
//
// IP address of received UDP datagram is not the same
// as the IP address of the ONC/RPC server.
//
// [Nothing to do here, just wait for the next datagram]
}
} catch ( InterruptedIOException e ) {
//
// Note that we only catch timeouts here, but no other
// exceptions. Those others will go up further until someone
// catches them. The timeouts are caught, so they can do no
// damage but instead we start another round of sending a
// request and waiting for a reply. Reminds me of NASA and
// their "Mars Polar Lander"...
//
// Note that we need to leave the inner waiting loop here,
// as we might need to resend the (lost) RPC request
// datagram.
//
break;
} catch ( IOException e ) {
//
// Argh. Trouble with the transport. Seems like we can't
// receive data. Gosh. Go away!
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
} catch ( OncRpcException e ) {
//
// Ooops. An ONC/RPC exception. Let us rethrow this one,
// as we won't have nothin' to do with it...
//
try {
receivingXdr.endDecoding(); // skip UDP record
} catch ( IOException ioe ) {
}
//
// Well, in case we got not a *reply* RPC message back,
// we keep listening for messages.
//
if ( e.getReason() != OncRpcException.RPC_WRONGMESSAGE ) {
throw(e);
}
}
//
// We can not make use of the reply we just received, so
// we need to dump it.
//
// This should raise no exceptions, when skipping the UDP
// record. So if one is raised, we will rethrow an ONC/RPC
// exception instead.
//
try {
receivingXdr.endDecoding();
} catch ( IOException e ) {
throw(new OncRpcException(OncRpcException.RPC_CANTRECV,
e.getLocalizedMessage()));
}
}
//
// We only reach this code part beyond the inner waiting
// loop if we run in a timeout and might need to retransmit
//
// According to the retransmission strategy choosen, update the
// current retransmission (resending) timeout.
//
if ( retransmissionMode == OncRpcUdpRetransmissionMode.EXPONENTIAL ) {
resendTimeout *= 2;
}
} while ( System.currentTimeMillis() < stopTime );
//
// That's it -- this shity server does not talk to us. Now, due to
// the indecent language used in the previous sentence, this software
// can not be exported any longer to some countries of the world.
// But this is surely not my problem, but rather theirs. So go away
// and hide yourself in the dark with all your zombies (or maybe
// kangaroos).
//
throw(new OncRpcTimeoutException());
} // for ( refreshesLeft )
}
|
diff --git a/qcadoo-model/src/main/java/com/qcadoo/model/api/expression/ExpressionUtils.java b/qcadoo-model/src/main/java/com/qcadoo/model/api/expression/ExpressionUtils.java
index 69f3ff7c3..a83982ebe 100644
--- a/qcadoo-model/src/main/java/com/qcadoo/model/api/expression/ExpressionUtils.java
+++ b/qcadoo-model/src/main/java/com/qcadoo/model/api/expression/ExpressionUtils.java
@@ -1,73 +1,73 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo Framework
* Version: 0.4.0
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.model.api.expression;
import java.util.List;
import java.util.Locale;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.FieldDefinition;
import com.qcadoo.model.internal.ExpressionServiceImpl;
/**
* Utility to evaluate expression for entity.
*
* @version 0.4.0
*/
public final class ExpressionUtils {
private ExpressionUtils() {
}
/**
* Evaluate expression - result is value of field (or comma separated fields values). Returns null when generated value is
* null.
*
* @param entity
* entity
* @param fields
* fields
* @param locale
* locale
* @return evaluated expression or null
*/
public static String getValue(final Entity entity, final List<FieldDefinition> fields, final Locale locale) {
- return ExpressionServiceImpl.getInstance().getValue(entity, fieldDefinitions, locale);
+ return ExpressionServiceImpl.getInstance().getValue(entity, fields, locale);
}
/**
* Evaluate expression value using entity fields values. Returns null when generated value is null.
*
* @param entity
* entity
* @param locale
* locale
* @return evaluated expression or null
*/
public static String getValue(final Entity entity, final String expression, final Locale locale) {
return ExpressionServiceImpl.getInstance().getValue(entity, expression, locale);
}
}
| true | true | public static String getValue(final Entity entity, final List<FieldDefinition> fields, final Locale locale) {
return ExpressionServiceImpl.getInstance().getValue(entity, fieldDefinitions, locale);
}
| public static String getValue(final Entity entity, final List<FieldDefinition> fields, final Locale locale) {
return ExpressionServiceImpl.getInstance().getValue(entity, fields, locale);
}
|
diff --git a/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java b/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java
index 452c18769..9c2ad540a 100644
--- a/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java
+++ b/jersey-server/src/main/java/com/sun/jersey/server/wadl/WadlGeneratorImpl.java
@@ -1,192 +1,194 @@
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://jersey.dev.java.net/CDDL+GPL.html
* or jersey/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at jersey/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.jersey.server.wadl;
import com.sun.jersey.api.model.AbstractMethod;
import javax.ws.rs.FormParam;
import javax.ws.rs.core.MediaType;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import com.sun.jersey.api.model.AbstractResource;
import com.sun.jersey.api.model.AbstractResourceMethod;
import com.sun.jersey.api.model.Parameter;
import com.sun.research.ws.wadl.Application;
import com.sun.research.ws.wadl.Param;
import com.sun.research.ws.wadl.ParamStyle;
import com.sun.research.ws.wadl.RepresentationType;
import com.sun.research.ws.wadl.Request;
import com.sun.research.ws.wadl.Resource;
import com.sun.research.ws.wadl.Resources;
import com.sun.research.ws.wadl.Response;
/**
* This WadlGenerator creates the basic wadl artifacts.<br>
* Created on: Jun 16, 2008<br>
*
* @author <a href="mailto:[email protected]">Martin Grotzke</a>
* @version $Id$
*/
public class WadlGeneratorImpl implements WadlGenerator {
public String getRequiredJaxbContextPath() {
final String name = Application.class.getName();
return name.substring(0, name.lastIndexOf('.'));
}
public void init() throws Exception {
}
public void setWadlGeneratorDelegate( WadlGenerator delegate ) {
throw new UnsupportedOperationException( "No delegate supported." );
}
public Resources createResources() {
return new Resources();
}
public Application createApplication() {
return new Application();
}
public com.sun.research.ws.wadl.Method createMethod(
AbstractResource r, final AbstractResourceMethod m ) {
com.sun.research.ws.wadl.Method wadlMethod =
new com.sun.research.ws.wadl.Method();
wadlMethod.setName(m.getHttpMethod());
wadlMethod.setId( m.getMethod().getName() );
return wadlMethod;
}
public RepresentationType createRequestRepresentation( AbstractResource r, AbstractResourceMethod m, MediaType mediaType ) {
RepresentationType wadlRepresentation = new RepresentationType();
wadlRepresentation.setMediaType(mediaType.toString());
return wadlRepresentation;
}
public Request createRequest(AbstractResource r, AbstractResourceMethod m) {
return new Request();
}
public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) {
+ if (p.getSource() == Parameter.Source.UNKNOWN)
+ return null;
Param wadlParam = new Param();
wadlParam.setName(p.getSourceName());
/* the form param right now has no Parameter.Source representation
* and requires some special handling
*/
if ( p.getAnnotation().annotationType() == FormParam.class ) {
wadlParam.setStyle( ParamStyle.QUERY );
}
else {
switch (p.getSource()) {
case QUERY:
wadlParam.setStyle(ParamStyle.QUERY);
break;
case MATRIX:
wadlParam.setStyle(ParamStyle.MATRIX);
break;
case PATH:
wadlParam.setStyle(ParamStyle.TEMPLATE);
break;
case HEADER:
wadlParam.setStyle(ParamStyle.HEADER);
break;
default:
break;
}
}
if (p.hasDefaultValue())
wadlParam.setDefault(p.getDefaultValue());
Class<?> pClass = p.getParameterClass();
if (pClass.isArray()) {
wadlParam.setRepeating(true);
pClass = pClass.getComponentType();
}
if (pClass.equals(int.class) || pClass.equals(Integer.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs"));
else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs"));
else if (pClass.equals(long.class) || pClass.equals(Long.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs"));
else if (pClass.equals(short.class) || pClass.equals(Short.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs"));
else if (pClass.equals(byte.class) || pClass.equals(Byte.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs"));
else if (pClass.equals(float.class) || pClass.equals(Float.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs"));
else if (pClass.equals(double.class) || pClass.equals(Double.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs"));
else
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs"));
return wadlParam;
}
public Resource createResource( AbstractResource r, String path ) {
Resource wadlResource = new Resource();
if (path != null)
wadlResource.setPath(path);
else if (r.isRootResource())
wadlResource.setPath(r.getPath().getValue());
return wadlResource;
}
public Response createResponse( AbstractResource r, AbstractResourceMethod m ) {
final Response response = new Response();
for (MediaType mediaType: m.getSupportedOutputTypes()) {
RepresentationType wadlRepresentation = createResponseRepresentation( r, m, mediaType );
JAXBElement<RepresentationType> element = new JAXBElement<RepresentationType>(
new QName("http://research.sun.com/wadl/2006/10","representation"),
RepresentationType.class,
wadlRepresentation);
response.getRepresentationOrFault().add(element);
}
return response;
}
public RepresentationType createResponseRepresentation( AbstractResource r, AbstractResourceMethod m, MediaType mediaType ) {
RepresentationType wadlRepresentation = new RepresentationType();
wadlRepresentation.setMediaType(mediaType.toString());
return wadlRepresentation;
}
}
| true | true | public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) {
Param wadlParam = new Param();
wadlParam.setName(p.getSourceName());
/* the form param right now has no Parameter.Source representation
* and requires some special handling
*/
if ( p.getAnnotation().annotationType() == FormParam.class ) {
wadlParam.setStyle( ParamStyle.QUERY );
}
else {
switch (p.getSource()) {
case QUERY:
wadlParam.setStyle(ParamStyle.QUERY);
break;
case MATRIX:
wadlParam.setStyle(ParamStyle.MATRIX);
break;
case PATH:
wadlParam.setStyle(ParamStyle.TEMPLATE);
break;
case HEADER:
wadlParam.setStyle(ParamStyle.HEADER);
break;
default:
break;
}
}
if (p.hasDefaultValue())
wadlParam.setDefault(p.getDefaultValue());
Class<?> pClass = p.getParameterClass();
if (pClass.isArray()) {
wadlParam.setRepeating(true);
pClass = pClass.getComponentType();
}
if (pClass.equals(int.class) || pClass.equals(Integer.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs"));
else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs"));
else if (pClass.equals(long.class) || pClass.equals(Long.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs"));
else if (pClass.equals(short.class) || pClass.equals(Short.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs"));
else if (pClass.equals(byte.class) || pClass.equals(Byte.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs"));
else if (pClass.equals(float.class) || pClass.equals(Float.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs"));
else if (pClass.equals(double.class) || pClass.equals(Double.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs"));
else
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs"));
return wadlParam;
}
| public Param createParam( AbstractResource r, AbstractMethod m, final Parameter p ) {
if (p.getSource() == Parameter.Source.UNKNOWN)
return null;
Param wadlParam = new Param();
wadlParam.setName(p.getSourceName());
/* the form param right now has no Parameter.Source representation
* and requires some special handling
*/
if ( p.getAnnotation().annotationType() == FormParam.class ) {
wadlParam.setStyle( ParamStyle.QUERY );
}
else {
switch (p.getSource()) {
case QUERY:
wadlParam.setStyle(ParamStyle.QUERY);
break;
case MATRIX:
wadlParam.setStyle(ParamStyle.MATRIX);
break;
case PATH:
wadlParam.setStyle(ParamStyle.TEMPLATE);
break;
case HEADER:
wadlParam.setStyle(ParamStyle.HEADER);
break;
default:
break;
}
}
if (p.hasDefaultValue())
wadlParam.setDefault(p.getDefaultValue());
Class<?> pClass = p.getParameterClass();
if (pClass.isArray()) {
wadlParam.setRepeating(true);
pClass = pClass.getComponentType();
}
if (pClass.equals(int.class) || pClass.equals(Integer.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs"));
else if (pClass.equals(boolean.class) || pClass.equals(Boolean.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs"));
else if (pClass.equals(long.class) || pClass.equals(Long.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs"));
else if (pClass.equals(short.class) || pClass.equals(Short.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs"));
else if (pClass.equals(byte.class) || pClass.equals(Byte.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs"));
else if (pClass.equals(float.class) || pClass.equals(Float.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs"));
else if (pClass.equals(double.class) || pClass.equals(Double.class))
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs"));
else
wadlParam.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs"));
return wadlParam;
}
|
diff --git a/dependencies/i18n/src/main/java/org/apache/abdera/i18n/text/io/PeekAheadInputStream.java b/dependencies/i18n/src/main/java/org/apache/abdera/i18n/text/io/PeekAheadInputStream.java
index 33326817..25d0ad16 100644
--- a/dependencies/i18n/src/main/java/org/apache/abdera/i18n/text/io/PeekAheadInputStream.java
+++ b/dependencies/i18n/src/main/java/org/apache/abdera/i18n/text/io/PeekAheadInputStream.java
@@ -1,75 +1,75 @@
package org.apache.abdera.i18n.text.io;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
import java.io.IOException;
import java.io.InputStream;
/**
* A version of RewindableInputStream that provides methods for peeking ahead
* in the stream (equivalent to read() followed by an appropriate unread()
*/
public class PeekAheadInputStream
extends RewindableInputStream {
public PeekAheadInputStream(
InputStream in) {
super(in);
}
public PeekAheadInputStream(
InputStream in,
int initialSize) {
super(in,initialSize);
}
/**
* Peek the next byte in the stream
*/
public int peek()
throws IOException {
int m = read();
unread(m);
return m;
}
/**
* Peek the next bytes in the stream. Returns the number of bytes peeked.
* Will return -1 if the end of the stream is reached
*/
public int peek(
byte[] buf)
throws IOException {
return peek(buf, 0, buf.length);
}
/**
* Peek the next bytes in the stream. Returns the number of bytes peeked.
* Will return -1 if the end of the stream is reached
*/
public int peek(
byte[] buf,
int off,
int len)
throws IOException {
int r = read(buf, off, len);
- unread(buf,off,len);
+ unread(buf,off,r);
return r;
}
}
| true | true | public int peek(
byte[] buf,
int off,
int len)
throws IOException {
int r = read(buf, off, len);
unread(buf,off,len);
return r;
}
| public int peek(
byte[] buf,
int off,
int len)
throws IOException {
int r = read(buf, off, len);
unread(buf,off,r);
return r;
}
|
diff --git a/src/org/ebookdroid/core/EventChildLoaded.java b/src/org/ebookdroid/core/EventChildLoaded.java
index 6b10557b..a4ae7767 100644
--- a/src/org/ebookdroid/core/EventChildLoaded.java
+++ b/src/org/ebookdroid/core/EventChildLoaded.java
@@ -1,114 +1,114 @@
package org.ebookdroid.core;
import org.ebookdroid.common.bitmaps.ByteBufferManager;
import org.ebookdroid.common.bitmaps.GLBitmaps;
import android.graphics.RectF;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class EventChildLoaded extends AbstractEvent {
private final Queue<EventChildLoaded> eventQueue;
public Page page;
public PageTree nodes;
public PageTreeNode child;
public EventChildLoaded(final Queue<EventChildLoaded> eventQueue) {
this.eventQueue = eventQueue;
}
final void init(final AbstractViewController ctrl, final PageTreeNode child) {
this.viewState = ViewState.get(ctrl);
this.ctrl = ctrl;
this.page = child.page;
this.nodes = page.nodes;
this.child = child;
}
final void release() {
this.ctrl = null;
this.viewState = null;
this.child = null;
this.nodes = null;
this.page = null;
this.bitmapsToRecycle.clear();
this.nodesToDecode.clear();
eventQueue.offer(this);
}
/**
* {@inheritDoc}
*
* @see org.ebookdroid.core.AbstractEvent#process()
*/
@Override
public final ViewState process() {
try {
if (ctrl == null || viewState.book == null) {
return null;
}
final RectF bounds = viewState.getBounds(page);
final PageTreeNode parent = child.parent;
if (parent != null) {
recycleParent(parent, bounds);
}
recycleChildren();
ctrl.pageUpdated(viewState, page);
- if (viewState.isNodeVisible(child, viewState.getBounds(page))) {
+ if (viewState.isPageVisible(page) && viewState.isNodeVisible(child, viewState.getBounds(page))) {
ctrl.redrawView(viewState);
}
return viewState;
} finally {
release();
}
}
protected void recycleParent(final PageTreeNode parent, final RectF bounds) {
final boolean hiddenByChildren = nodes.isHiddenByChildren(parent, viewState, bounds);
// if (LCTX.isDebugEnabled()) {
// LCTX.d("Node " + parent.fullId + " is: " + (hiddenByChildren ? "" : "not") + " hidden by children");
// }
if (!viewState.isNodeVisible(parent, bounds) || hiddenByChildren) {
final List<GLBitmaps> bitmapsToRecycle = new ArrayList<GLBitmaps>();
final boolean res = nodes.recycleParents(child, bitmapsToRecycle);
ByteBufferManager.release(bitmapsToRecycle);
if (res) {
if (LCTX.isDebugEnabled()) {
LCTX.d("Recycle parent nodes for: " + child.fullId + " " + bitmapsToRecycle.size());
}
}
}
}
protected void recycleChildren() {
final boolean res = nodes.recycleChildren(child, bitmapsToRecycle);
ByteBufferManager.release(bitmapsToRecycle);
if (res) {
if (LCTX.isDebugEnabled()) {
LCTX.d("Recycle children nodes for: " + child.fullId + " " + bitmapsToRecycle.size());
}
}
}
@Override
public boolean process(final PageTree nodes) {
return false;
}
@Override
public boolean process(final PageTreeNode node) {
return false;
}
}
| true | true | public final ViewState process() {
try {
if (ctrl == null || viewState.book == null) {
return null;
}
final RectF bounds = viewState.getBounds(page);
final PageTreeNode parent = child.parent;
if (parent != null) {
recycleParent(parent, bounds);
}
recycleChildren();
ctrl.pageUpdated(viewState, page);
if (viewState.isNodeVisible(child, viewState.getBounds(page))) {
ctrl.redrawView(viewState);
}
return viewState;
} finally {
release();
}
}
| public final ViewState process() {
try {
if (ctrl == null || viewState.book == null) {
return null;
}
final RectF bounds = viewState.getBounds(page);
final PageTreeNode parent = child.parent;
if (parent != null) {
recycleParent(parent, bounds);
}
recycleChildren();
ctrl.pageUpdated(viewState, page);
if (viewState.isPageVisible(page) && viewState.isNodeVisible(child, viewState.getBounds(page))) {
ctrl.redrawView(viewState);
}
return viewState;
} finally {
release();
}
}
|
diff --git a/bpel-obj/src/main/java/org/apache/ode/bpel/o/OElementVarType.java b/bpel-obj/src/main/java/org/apache/ode/bpel/o/OElementVarType.java
index 762b345d..a25f0a5b 100644
--- a/bpel-obj/src/main/java/org/apache/ode/bpel/o/OElementVarType.java
+++ b/bpel-obj/src/main/java/org/apache/ode/bpel/o/OElementVarType.java
@@ -1,42 +1,45 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.bpel.o;
import javax.xml.namespace.QName;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class OElementVarType extends OVarType {
private static final long serialVersionUID = 1L;
public QName elementType;
public OElementVarType(OProcess owner, QName typeName) {
super(owner);
elementType = typeName;
}
public Node newInstance(Document doc) {
Element el = doc.createElementNS(elementType.getNamespaceURI(),
elementType.getLocalPart());
- return el;
+ // Pre-filling the element with an empty node to avoid an empty nodeset
+ // when selecting the element child nodes
+ el.appendChild(doc.createElement("empty"));
+ return el;
}
}
| true | true | public Node newInstance(Document doc) {
Element el = doc.createElementNS(elementType.getNamespaceURI(),
elementType.getLocalPart());
return el;
}
| public Node newInstance(Document doc) {
Element el = doc.createElementNS(elementType.getNamespaceURI(),
elementType.getLocalPart());
// Pre-filling the element with an empty node to avoid an empty nodeset
// when selecting the element child nodes
el.appendChild(doc.createElement("empty"));
return el;
}
|
diff --git a/aciertoteam-i18n/src/main/java/com/aciertoteam/i18n/UserSessionLocale.java b/aciertoteam-i18n/src/main/java/com/aciertoteam/i18n/UserSessionLocale.java
index 34f9b22..78dd7f5 100644
--- a/aciertoteam-i18n/src/main/java/com/aciertoteam/i18n/UserSessionLocale.java
+++ b/aciertoteam-i18n/src/main/java/com/aciertoteam/i18n/UserSessionLocale.java
@@ -1,84 +1,85 @@
package com.aciertoteam.i18n;
import com.aciertoteam.common.service.EntityService;
import com.aciertoteam.geo.IpDetector;
import com.aciertoteam.geo.entity.Country;
import com.aciertoteam.geo.entity.Language;
import com.aciertoteam.geo.services.GeoIpService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Locale;
/**
* User session locale holder. TODO get locale from user country
*
* @author ishestiporov
*/
public class UserSessionLocale implements Serializable, InitializingBean {
private static final long serialVersionUID = 1L;
private Locale defaultLocale = Locale.getDefault();
private Locale locale;
@Autowired
private GeoIpService geoIpService;
@Autowired
private IpDetector ipDetector;
@Autowired
private EntityService entityService;
private void defineDefaultLocale(HttpServletRequest request) {
Country country = geoIpService.defineCountry(ipDetector.getIpAddress(request));
setLocale(getLocale(country));
}
public Locale getLocale(Country country) {
Language defaultLanguage = entityService.findByField(Language.class, "code", "en");
Language countryLanguage = country.getDefaultLanguage(country);
Language language = countryLanguage == null ? defaultLanguage : countryLanguage;
return new Locale(language.getCode(), language.getCountryCode());
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return locale;
}
/**
* Returns user set locale or the default one if user session locale is not
* set.
*/
public Locale getResolvedLocale() {
return locale != null ? locale : defaultLocale;
}
public Locale getDefaultLocale() {
return defaultLocale;
}
public void setDefaultLocale(Locale defaultLocale) {
this.defaultLocale = defaultLocale;
}
@Override
public void afterPropertiesSet() throws Exception {
- RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
- if (requestAttributes instanceof ServletRequestAttributes) {
- HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
- defineDefaultLocale(request);
- }
- }
+ if (RequestContextHolder.getRequestAttributes() != null) {
+ RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
+ if (requestAttributes instanceof ServletRequestAttributes) {
+ HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
+ defineDefaultLocale(request);
+ }
+ } }
}
| true | true | public void afterPropertiesSet() throws Exception {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
defineDefaultLocale(request);
}
}
| public void afterPropertiesSet() throws Exception {
if (RequestContextHolder.getRequestAttributes() != null) {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
defineDefaultLocale(request);
}
} }
|
diff --git a/src/main/java/org/dynmap/JsonTimerTask.java b/src/main/java/org/dynmap/JsonTimerTask.java
index e0ad0e55..dd88ffcf 100644
--- a/src/main/java/org/dynmap/JsonTimerTask.java
+++ b/src/main/java/org/dynmap/JsonTimerTask.java
@@ -1,170 +1,172 @@
package org.dynmap;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;
import org.dynmap.web.Json;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonTimerTask extends TimerTask {
protected static final Logger log = Logger.getLogger("Minecraft");
private final DynmapPlugin plugin;
private Server server;
private MapManager mapManager;
private Configuration configuration;
private ConfigurationNode regions;
private static final JSONParser parser = new JSONParser();
private long lastTimestamp = 0;
public JsonTimerTask(DynmapPlugin instance, Configuration config) {
this.plugin = instance;
this.server = this.plugin.getServer();
this.mapManager = this.plugin.getMapManager();
this.configuration = config;
for(ConfigurationNode type : configuration.getNodeList("web.components", null))
if(type.getString("type").equalsIgnoreCase("regions")) {
this.regions = type;
break;
}
}
public void run() {
long jsonInterval = configuration.getInt("jsonfile-interval", 1) * 1000;
long current = System.currentTimeMillis();
File outputFile;
//Handles Reading WebChat
if (configuration.getNode("web").getBoolean("allowwebchat", false)) {
File webChatPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_webchat.json");
if (webChatPath.isAbsolute())
outputFile = webChatPath;
else {
outputFile = new File(plugin.getDataFolder(), webChatPath.toString());
}
if (webChatPath.exists() && lastTimestamp != 0) {
JSONArray jsonMsgs = null;
try {
FileReader inputFileReader = new FileReader(webChatPath);
jsonMsgs = (JSONArray) parser.parse(inputFileReader);
inputFileReader.close();
} catch (IOException ex) {
log.log(Level.SEVERE, "Exception while reading JSON-file.", ex);
} catch (ParseException ex) {
log.log(Level.SEVERE, "Exception while parsing JSON-file.", ex);
}
if (jsonMsgs != null) {
Iterator<?> iter = jsonMsgs.iterator();
while (iter.hasNext()) {
JSONObject o = (JSONObject) iter.next();
if (Long.parseLong(String.valueOf(o.get("timestamp"))) >= (lastTimestamp)) {
plugin.webChat(String.valueOf(o.get("name")), String.valueOf(o.get("message")));
}
}
}
}
}
//Handles Updates
for (World world : this.server.getWorlds()) {
//Parse region file for multi world style
- if(regions.getBoolean("useworldpath", false))
- parseRegionFile(world.getName() + "/" + regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
+ if (regions != null)
+ if (regions.getBoolean("useworldpath", false))
+ parseRegionFile(world.getName() + "/" + regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
current = System.currentTimeMillis();
Client.Update update = new Client.Update();
update.timestamp = current;
update.servertime = world.getTime() % 24000;
Player[] players = plugin.playerList.getVisiblePlayers();
update.players = new Client.Player[players.length];
for (int i = 0; i < players.length; i++) {
Player p = players[i];
Location pl = p.getLocation();
update.players[i] = new Client.Player(p.getDisplayName(), pl.getWorld().getName(), pl.getX(), pl.getY(), pl.getZ());
}
update.updates = mapManager.getWorldUpdates(world.getName(), current - (jsonInterval + 10000));
File webWorldPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_" + world.getName() + ".json");
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(update).getBytes());
fos.close();
} catch (FileNotFoundException ex) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
}
}
lastTimestamp = System.currentTimeMillis();
//Parse regions file for non worlds style
- if (!regions.getBoolean("useworldpath", false))
- parseRegionFile(regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml"));
+ if (null != regions)
+ if (!regions.getBoolean("useworldpath", false))
+ parseRegionFile(regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml"));
}
//handles parsing and writing region json files
private void parseRegionFile(String regionFile, String outputFileName)
{
File outputFile;
Configuration regionConfig = null;
if(regions.getBoolean("useworldpath", false))
{
if(new File("plugins/"+regions.getString("name", "WorldGuard"), regionFile).exists())
regionConfig = new Configuration(new File("plugins/"+regions.getString("name", "WorldGuard"), regionFile));
else if(new File("plugins/"+regions.getString("name", "WorldGuard")+"/worlds", regionFile).exists())
regionConfig = new Configuration(new File("plugins/"+regions.getString("name", "WorldGuard")+"/worlds", regionFile));
}
else
regionConfig = new Configuration(new File("plugins/"+regions.getString("name", "WorldGuard"), regionFile));
//File didn't exist
if(regionConfig == null)
return;
regionConfig.load();
outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf("."))+".json";
File webWorldPath = new File(this.configuration.getString("webpath", "web")+"/standalone/", outputFileName);
Map<?, ?> regionData = (Map<?, ?>) regionConfig.getProperty(regions.getString("basenode", "regions"));
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(regionData).getBytes());
fos.close();
} catch (FileNotFoundException ex) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
}
}
}
| false | true | public void run() {
long jsonInterval = configuration.getInt("jsonfile-interval", 1) * 1000;
long current = System.currentTimeMillis();
File outputFile;
//Handles Reading WebChat
if (configuration.getNode("web").getBoolean("allowwebchat", false)) {
File webChatPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_webchat.json");
if (webChatPath.isAbsolute())
outputFile = webChatPath;
else {
outputFile = new File(plugin.getDataFolder(), webChatPath.toString());
}
if (webChatPath.exists() && lastTimestamp != 0) {
JSONArray jsonMsgs = null;
try {
FileReader inputFileReader = new FileReader(webChatPath);
jsonMsgs = (JSONArray) parser.parse(inputFileReader);
inputFileReader.close();
} catch (IOException ex) {
log.log(Level.SEVERE, "Exception while reading JSON-file.", ex);
} catch (ParseException ex) {
log.log(Level.SEVERE, "Exception while parsing JSON-file.", ex);
}
if (jsonMsgs != null) {
Iterator<?> iter = jsonMsgs.iterator();
while (iter.hasNext()) {
JSONObject o = (JSONObject) iter.next();
if (Long.parseLong(String.valueOf(o.get("timestamp"))) >= (lastTimestamp)) {
plugin.webChat(String.valueOf(o.get("name")), String.valueOf(o.get("message")));
}
}
}
}
}
//Handles Updates
for (World world : this.server.getWorlds()) {
//Parse region file for multi world style
if(regions.getBoolean("useworldpath", false))
parseRegionFile(world.getName() + "/" + regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
current = System.currentTimeMillis();
Client.Update update = new Client.Update();
update.timestamp = current;
update.servertime = world.getTime() % 24000;
Player[] players = plugin.playerList.getVisiblePlayers();
update.players = new Client.Player[players.length];
for (int i = 0; i < players.length; i++) {
Player p = players[i];
Location pl = p.getLocation();
update.players[i] = new Client.Player(p.getDisplayName(), pl.getWorld().getName(), pl.getX(), pl.getY(), pl.getZ());
}
update.updates = mapManager.getWorldUpdates(world.getName(), current - (jsonInterval + 10000));
File webWorldPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_" + world.getName() + ".json");
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(update).getBytes());
fos.close();
} catch (FileNotFoundException ex) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
}
}
lastTimestamp = System.currentTimeMillis();
//Parse regions file for non worlds style
if (!regions.getBoolean("useworldpath", false))
parseRegionFile(regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml"));
}
| public void run() {
long jsonInterval = configuration.getInt("jsonfile-interval", 1) * 1000;
long current = System.currentTimeMillis();
File outputFile;
//Handles Reading WebChat
if (configuration.getNode("web").getBoolean("allowwebchat", false)) {
File webChatPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_webchat.json");
if (webChatPath.isAbsolute())
outputFile = webChatPath;
else {
outputFile = new File(plugin.getDataFolder(), webChatPath.toString());
}
if (webChatPath.exists() && lastTimestamp != 0) {
JSONArray jsonMsgs = null;
try {
FileReader inputFileReader = new FileReader(webChatPath);
jsonMsgs = (JSONArray) parser.parse(inputFileReader);
inputFileReader.close();
} catch (IOException ex) {
log.log(Level.SEVERE, "Exception while reading JSON-file.", ex);
} catch (ParseException ex) {
log.log(Level.SEVERE, "Exception while parsing JSON-file.", ex);
}
if (jsonMsgs != null) {
Iterator<?> iter = jsonMsgs.iterator();
while (iter.hasNext()) {
JSONObject o = (JSONObject) iter.next();
if (Long.parseLong(String.valueOf(o.get("timestamp"))) >= (lastTimestamp)) {
plugin.webChat(String.valueOf(o.get("name")), String.valueOf(o.get("message")));
}
}
}
}
}
//Handles Updates
for (World world : this.server.getWorlds()) {
//Parse region file for multi world style
if (regions != null)
if (regions.getBoolean("useworldpath", false))
parseRegionFile(world.getName() + "/" + regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
current = System.currentTimeMillis();
Client.Update update = new Client.Update();
update.timestamp = current;
update.servertime = world.getTime() % 24000;
Player[] players = plugin.playerList.getVisiblePlayers();
update.players = new Client.Player[players.length];
for (int i = 0; i < players.length; i++) {
Player p = players[i];
Location pl = p.getLocation();
update.players[i] = new Client.Player(p.getDisplayName(), pl.getWorld().getName(), pl.getX(), pl.getY(), pl.getZ());
}
update.updates = mapManager.getWorldUpdates(world.getName(), current - (jsonInterval + 10000));
File webWorldPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_" + world.getName() + ".json");
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(update).getBytes());
fos.close();
} catch (FileNotFoundException ex) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
}
}
lastTimestamp = System.currentTimeMillis();
//Parse regions file for non worlds style
if (null != regions)
if (!regions.getBoolean("useworldpath", false))
parseRegionFile(regions.getString("filename", "regions.yml"), regions.getString("filename", "regions.yml"));
}
|
diff --git a/plugins/core/com.vectorsf.jvoice.core.reconciliator/src/com/vectorsf/jvoice/core/reconciliator/CheckDeltaChange.java b/plugins/core/com.vectorsf.jvoice.core.reconciliator/src/com/vectorsf/jvoice/core/reconciliator/CheckDeltaChange.java
index 98e18f35..9d3f8ab2 100644
--- a/plugins/core/com.vectorsf.jvoice.core.reconciliator/src/com/vectorsf/jvoice/core/reconciliator/CheckDeltaChange.java
+++ b/plugins/core/com.vectorsf.jvoice.core.reconciliator/src/com/vectorsf/jvoice/core/reconciliator/CheckDeltaChange.java
@@ -1,204 +1,204 @@
package com.vectorsf.jvoice.core.reconciliator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import com.vectorsf.jvoice.base.model.service.BaseModel;
import com.vectorsf.jvoice.core.project.JVoiceProjectNature;
import com.vectorsf.jvoice.model.base.Configuration;
import com.vectorsf.jvoice.model.base.JVBean;
import com.vectorsf.jvoice.model.base.JVPackage;
import com.vectorsf.jvoice.model.base.JVProject;
public class CheckDeltaChange implements IResourceDeltaVisitor {
private final static IPath pkgPath = new Path(BaseModel.JV_PATH);
private final static IPath configPath = new Path(BaseModel.PROPERTIES_PATH);
private JVProject jvProject;
private JVPackage currentPackage;
public CheckDeltaChange(JVProject prj, IFolder packageFolder) {
jvProject = prj;
currentPackage = null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
*/
@Override
public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
switch (resource.getType()) {
case IResource.FOLDER:
// SI es un paquete de configuración no debe aparecer en la lista
if (isValidFolder(resource) && !isConfigurationFolder(resource)) {
IPath relPath = getRelativePath(resource);
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
currentPackage = pkg;
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getPackages().remove(currentPackage);
removeResources(currentPackage);
- return false;
+ return true;
}
} else {
currentPackage = JVoiceModelReconcilier.getInstance().createPackage((IFolder) resource);
jvProject.getPackages().add(currentPackage);
return true;
}
}
return true;
case IResource.FILE:
if (isInterestingDelta(delta)) {
IPath relPath = getRelativePath(resource.getParent());
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
URI uri = URI.createPlatformResourceURI(resource.getFullPath().toString(),
true);
final List<JVBean> beans = pkg.getBeans();
if (delta.getKind() == IResourceDelta.ADDED) {
beans.add(JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
JVBean bean = getBeanFromResource(eResource);
int index = beans.indexOf(bean);
if (index!= -1) {
beans.remove(index);
eResource.unload();
beans.add(index, JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
}
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
// se busca el elemento en el paquete y se elimina
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
beans.remove(getBeanFromResource(eResource));
resourceSet.getResources().remove(eResource);
}
}
// Se trata de un archivo de configuración
} else if (resource.getFileExtension().equalsIgnoreCase("properties")) {
if (!isConfigurationFolder(resource.getParent())){
return false;
}
String name = resource.getName().substring(0, resource.getName().lastIndexOf('.'));
// si es un evento de adición al paquete, por culpa del bug de eclipse que lanza el delta 2 veces
// tenemos que comprobar que lo hemos agregado ya antes, para no duplicarlo
if (delta.getKind() == IResourceDelta.ADDED) {
Configuration config = jvProject.getConfiguration(name);
if (config == null) {
jvProject.getConfiguration().add(
JVoiceModelReconcilier.getInstance().createConfigurationFromFile((IFile) resource));
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getConfiguration().remove(jvProject.getConfiguration(name));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
Configuration config = jvProject.getConfiguration(name);
JVoiceModelReconcilier.getInstance().reloadConfigurationProperties((IFile) resource, config);
}
}
}
return true;
case IResource.PROJECT:
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
if (delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() == IResourceDelta.DESCRIPTION) {
IProject project = (IProject) resource;
if (!project.isOpen() || !project.hasNature(JVoiceProjectNature.NATURE_ID)) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
}
}
return true;
}
private JVBean getBeanFromResource(Resource eResource) {
for(EObject e: eResource.getContents())
{
if (e instanceof JVBean) {
return (JVBean) e;
}
}
return null;
}
private void removeResources(JVProject jvProject) {
for (JVPackage pck : jvProject.getPackages()) {
removeResources(pck);
}
}
private void removeResources(JVPackage jvPackage) {
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
for (JVBean bean : jvPackage.getBeans()) {
resourceSet.getResources().remove(bean.eResource());
}
}
private boolean isInterestingDelta(IResourceDelta delta) {
return delta.getKind() == IResourceDelta.ADDED || delta.getKind() == IResourceDelta.REMOVED
|| delta.getKind() == IResourceDelta.CHANGED && (delta.getFlags() & IResourceDelta.CONTENT) != 0;
}
private boolean isValidFolder(IResource resource) {
if (pkgPath.isPrefixOf(resource.getProjectRelativePath()) && !pkgPath.equals(resource.getProjectRelativePath())) {
return true;
} else {
return false;
}
}
private IPath getRelativePath(IResource resource) {
if (pkgPath.isPrefixOf(resource.getProjectRelativePath()) && !pkgPath.equals(resource.getProjectRelativePath())) {
return resource.getProjectRelativePath().makeRelativeTo(pkgPath);
} else {
return null;
}
}
private boolean isConfigurationFolder(IResource resource) {
if (configPath.isPrefixOf(resource.getProjectRelativePath())
&& configPath.equals(resource.getProjectRelativePath())) {
return true;
}
return false;
}
}
| true | true | public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
switch (resource.getType()) {
case IResource.FOLDER:
// SI es un paquete de configuración no debe aparecer en la lista
if (isValidFolder(resource) && !isConfigurationFolder(resource)) {
IPath relPath = getRelativePath(resource);
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
currentPackage = pkg;
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getPackages().remove(currentPackage);
removeResources(currentPackage);
return false;
}
} else {
currentPackage = JVoiceModelReconcilier.getInstance().createPackage((IFolder) resource);
jvProject.getPackages().add(currentPackage);
return true;
}
}
return true;
case IResource.FILE:
if (isInterestingDelta(delta)) {
IPath relPath = getRelativePath(resource.getParent());
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
URI uri = URI.createPlatformResourceURI(resource.getFullPath().toString(),
true);
final List<JVBean> beans = pkg.getBeans();
if (delta.getKind() == IResourceDelta.ADDED) {
beans.add(JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
JVBean bean = getBeanFromResource(eResource);
int index = beans.indexOf(bean);
if (index!= -1) {
beans.remove(index);
eResource.unload();
beans.add(index, JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
}
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
// se busca el elemento en el paquete y se elimina
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
beans.remove(getBeanFromResource(eResource));
resourceSet.getResources().remove(eResource);
}
}
// Se trata de un archivo de configuración
} else if (resource.getFileExtension().equalsIgnoreCase("properties")) {
if (!isConfigurationFolder(resource.getParent())){
return false;
}
String name = resource.getName().substring(0, resource.getName().lastIndexOf('.'));
// si es un evento de adición al paquete, por culpa del bug de eclipse que lanza el delta 2 veces
// tenemos que comprobar que lo hemos agregado ya antes, para no duplicarlo
if (delta.getKind() == IResourceDelta.ADDED) {
Configuration config = jvProject.getConfiguration(name);
if (config == null) {
jvProject.getConfiguration().add(
JVoiceModelReconcilier.getInstance().createConfigurationFromFile((IFile) resource));
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getConfiguration().remove(jvProject.getConfiguration(name));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
Configuration config = jvProject.getConfiguration(name);
JVoiceModelReconcilier.getInstance().reloadConfigurationProperties((IFile) resource, config);
}
}
}
return true;
case IResource.PROJECT:
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
if (delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() == IResourceDelta.DESCRIPTION) {
IProject project = (IProject) resource;
if (!project.isOpen() || !project.hasNature(JVoiceProjectNature.NATURE_ID)) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
}
}
return true;
}
| public boolean visit(IResourceDelta delta) throws CoreException {
IResource resource = delta.getResource();
switch (resource.getType()) {
case IResource.FOLDER:
// SI es un paquete de configuración no debe aparecer en la lista
if (isValidFolder(resource) && !isConfigurationFolder(resource)) {
IPath relPath = getRelativePath(resource);
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
currentPackage = pkg;
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getPackages().remove(currentPackage);
removeResources(currentPackage);
return true;
}
} else {
currentPackage = JVoiceModelReconcilier.getInstance().createPackage((IFolder) resource);
jvProject.getPackages().add(currentPackage);
return true;
}
}
return true;
case IResource.FILE:
if (isInterestingDelta(delta)) {
IPath relPath = getRelativePath(resource.getParent());
JVPackage pkg = jvProject.getPackage(relPath.toString().replace("/", "."));
if (pkg != null) {
URI uri = URI.createPlatformResourceURI(resource.getFullPath().toString(),
true);
final List<JVBean> beans = pkg.getBeans();
if (delta.getKind() == IResourceDelta.ADDED) {
beans.add(JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
JVBean bean = getBeanFromResource(eResource);
int index = beans.indexOf(bean);
if (index!= -1) {
beans.remove(index);
eResource.unload();
beans.add(index, JVoiceModelReconcilier.getInstance().createBean((IFile) resource));
}
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
// se busca el elemento en el paquete y se elimina
ResourceSet resourceSet = BaseModel.getInstance().getResourceSet();
Resource eResource = resourceSet.getResource(uri, false);
if (eResource != null)
{
beans.remove(getBeanFromResource(eResource));
resourceSet.getResources().remove(eResource);
}
}
// Se trata de un archivo de configuración
} else if (resource.getFileExtension().equalsIgnoreCase("properties")) {
if (!isConfigurationFolder(resource.getParent())){
return false;
}
String name = resource.getName().substring(0, resource.getName().lastIndexOf('.'));
// si es un evento de adición al paquete, por culpa del bug de eclipse que lanza el delta 2 veces
// tenemos que comprobar que lo hemos agregado ya antes, para no duplicarlo
if (delta.getKind() == IResourceDelta.ADDED) {
Configuration config = jvProject.getConfiguration(name);
if (config == null) {
jvProject.getConfiguration().add(
JVoiceModelReconcilier.getInstance().createConfigurationFromFile((IFile) resource));
}
} else if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getConfiguration().remove(jvProject.getConfiguration(name));
} else if (delta.getKind() == IResourceDelta.CHANGED) {
Configuration config = jvProject.getConfiguration(name);
JVoiceModelReconcilier.getInstance().reloadConfigurationProperties((IFile) resource, config);
}
}
}
return true;
case IResource.PROJECT:
if (delta.getKind() == IResourceDelta.REMOVED) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
if (delta.getKind() == IResourceDelta.CHANGED && delta.getFlags() == IResourceDelta.DESCRIPTION) {
IProject project = (IProject) resource;
if (!project.isOpen() || !project.hasNature(JVoiceProjectNature.NATURE_ID)) {
jvProject.getModel().getProjects().remove(jvProject);
removeResources(jvProject);
return false;
}
}
}
return true;
}
|
diff --git a/src/gov/nih/nci/rembrandt/web/taglib/ClinicalPlotTag.java b/src/gov/nih/nci/rembrandt/web/taglib/ClinicalPlotTag.java
index 04d28628..f5a00291 100755
--- a/src/gov/nih/nci/rembrandt/web/taglib/ClinicalPlotTag.java
+++ b/src/gov/nih/nci/rembrandt/web/taglib/ClinicalPlotTag.java
@@ -1,369 +1,370 @@
package gov.nih.nci.rembrandt.web.taglib;
import gov.nih.nci.caintegrator.application.cache.BusinessTierCache;
import gov.nih.nci.caintegrator.dto.de.KarnofskyClinicalEvalDE;
import gov.nih.nci.caintegrator.enumeration.ClinicalFactorType;
import gov.nih.nci.caintegrator.enumeration.DiseaseType;
import gov.nih.nci.caintegrator.ui.graphing.chart.CaIntegratorChartFactory;
import gov.nih.nci.caintegrator.ui.graphing.data.clinical.ClinicalDataPoint;
import gov.nih.nci.caintegrator.ui.graphing.util.ImageMapUtil;
import gov.nih.nci.rembrandt.cache.RembrandtPresentationTierCache;
import gov.nih.nci.rembrandt.queryservice.resultset.DimensionalViewContainer;
import gov.nih.nci.rembrandt.queryservice.resultset.Resultant;
import gov.nih.nci.rembrandt.queryservice.resultset.ResultsContainer;
import gov.nih.nci.rembrandt.queryservice.resultset.sample.SampleResultset;
import gov.nih.nci.rembrandt.queryservice.resultset.sample.SampleViewResultsContainer;
import gov.nih.nci.rembrandt.web.bean.ReportBean;
import gov.nih.nci.rembrandt.web.factory.ApplicationFactory;
import gov.nih.nci.rembrandt.web.helper.RembrandtImageFileHandler;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import org.apache.log4j.Logger;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
/**
* this class generates a Clinical Plot tag which will take a taskId, the components
* with which to compare, and possibly a colorBy attribute which colors the
* samples either by Disease or Gender. Disease is colored by default.
* @author rossok
*
*/
/**
* caIntegrator License
*
* Copyright 2001-2005 Science Applications International Corporation ("SAIC").
* The software subject to this notice and license includes both human readable source code form and machine readable,
* binary, object code form ("the caIntegrator Software"). The caIntegrator Software was developed in conjunction with
* the National Cancer Institute ("NCI") by NCI employees and employees of SAIC.
* To the extent government employees are authors, any rights in such works shall be subject to Title 17 of the United States
* Code, section 105.
* This caIntegrator Software License (the "License") is between NCI and You. "You (or "Your") shall mean a person or an
* entity, and all other entities that control, are controlled by, or are under common control with the entity. "Control"
* for purposes of this definition means (i) the direct or indirect power to cause the direction or management of such entity,
* whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii)
* beneficial ownership of such entity.
* This License is granted provided that You agree to the conditions described below. NCI grants You a non-exclusive,
* worldwide, perpetual, fully-paid-up, no-charge, irrevocable, transferable and royalty-free right and license in its rights
* in the caIntegrator Software to (i) use, install, access, operate, execute, copy, modify, translate, market, publicly
* display, publicly perform, and prepare derivative works of the caIntegrator Software; (ii) distribute and have distributed
* to and by third parties the caIntegrator Software and any modifications and derivative works thereof;
* and (iii) sublicense the foregoing rights set out in (i) and (ii) to third parties, including the right to license such
* rights to further third parties. For sake of clarity, and not by way of limitation, NCI shall have no right of accounting
* or right of payment from You or Your sublicensees for the rights granted under this License. This License is granted at no
* charge to You.
* 1. Your redistributions of the source code for the Software must retain the above copyright notice, this list of conditions
* and the disclaimer and limitation of liability of Article 6, below. Your redistributions in object code form must reproduce
* the above copyright notice, this list of conditions and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
* 2. Your end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This
* product includes software developed by SAIC and the National Cancer Institute." If You do not include such end-user
* documentation, You shall include this acknowledgment in the Software itself, wherever such third-party acknowledgments
* normally appear.
* 3. You may not use the names "The National Cancer Institute", "NCI" "Science Applications International Corporation" and
* "SAIC" to endorse or promote products derived from this Software. This License does not authorize You to use any
* trademarks, service marks, trade names, logos or product names of either NCI or SAIC, except as required to comply with
* the terms of this License.
* 4. For sake of clarity, and not by way of limitation, You may incorporate this Software into Your proprietary programs and
* into any third party proprietary programs. However, if You incorporate the Software into third party proprietary
* programs, You agree that You are solely responsible for obtaining any permission from such third parties required to
* incorporate the Software into such third party proprietary programs and for informing Your sublicensees, including
* without limitation Your end-users, of their obligation to secure any required permissions from such third parties
* before incorporating the Software into such third party proprietary software programs. In the event that You fail
* to obtain such permissions, You agree to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such permissions.
* 5. For sake of clarity, and not by way of limitation, You may add Your own copyright statement to Your modifications and
* to the derivative works, and You may provide additional or different license terms and conditions in Your sublicenses
* of modifications of the Software, or any derivative works of the Software as a whole, provided Your use, reproduction,
* and distribution of the Work otherwise complies with the conditions stated in this License.
* 6. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED.
* IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
public class ClinicalPlotTag extends AbstractGraphingTag {
private String beanName = "";
private String taskId = "";
private String colorBy = "";
private String components ="";
private Collection<ClinicalDataPoint> clinicalData = new ArrayList();
private List<JFreeChart> jFreeChartsList;
private JFreeChart chart = null;
private static Logger logger = Logger.getLogger(ClinicalPlotTag.class);
private RembrandtPresentationTierCache presentationTierCache = ApplicationFactory.getPresentationTierCache();
private BusinessTierCache businessTierCache = ApplicationFactory.getBusinessTierCache();
public int doStartTag() {
chart = null;
clinicalData.clear();
ServletRequest request = pageContext.getRequest();
HttpSession session = pageContext.getSession();
Object o = request.getAttribute(beanName);
JspWriter out = pageContext.getOut();
ServletResponse response = pageContext.getResponse();
try {
//
//retrieve the Finding from cache and build the list of Clinical Data points
//ClinicalFinding clinicalFinding = (ClinicalFinding)businessTierCache.getSessionFinding(session.getId(),taskId);
ReportBean clincalReportBean = presentationTierCache.getReportBean(session.getId(),taskId);
Resultant clinicalResultant = clincalReportBean.getResultant();
ResultsContainer resultsContainer = clinicalResultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
if(sampleViewContainer!=null){
Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
clinicalFactors.add(ClinicalFactorType.AgeAtDx);
//clinicalFactors.add(ClinicalFactorType.Survival);
Collection<SampleResultset> samples = sampleViewContainer.getSampleResultsets();
if(samples!=null){
int numDxvsKa=0;
int numDxvsSl = 0;
for (SampleResultset rs:samples){
//String id = rs.getBiospecimen().getValueObject();
String id = rs.getSampleIDDE().getValueObject();
ClinicalDataPoint clinicalDataPoint = new ClinicalDataPoint(id);
String diseaseName = rs.getDisease().getValueObject();
if(diseaseName!=null){
clinicalDataPoint.setDiseaseName(diseaseName);
}
else{
clinicalDataPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
}
Long sl = rs.getSurvivalLength();
double survivalDays = -1.0;
double survivalMonths = -1.0;
if (sl != null) {
survivalDays = sl.doubleValue();
survivalMonths = survivalDays/30.0;
//if ((survivalMonths > 0.0)&&(survivalMonths < 1000.0)) {
clinicalDataPoint.setSurvival(survivalDays);
//}
}
Long dxAge = rs.getAge();
if (dxAge != null) {
clinicalDataPoint.setAgeAtDx(dxAge.doubleValue());
}
KarnofskyClinicalEvalDE ka = rs.getKarnofskyClinicalEvalDE();
if (ka != null) {
String kaStr = ka.getValueObject();
if (kaStr != null) {
- if(kaStr.contains(",")) {
- String [] kaStrArray = kaStr.split(",");
+ if(kaStr.contains("|")) {
+ kaStr =kaStr.trim();
+ String [] kaStrArray = kaStr.split("\\|");
for(int i =0;i<kaStrArray.length;i++){
if (i==0) {
//first score is baseline just use this for now
//later we will need to use all score in a series for each patient
double kaVal = Double.parseDouble(kaStrArray[i].trim());
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
else{
double kaVal = Double.parseDouble(kaStr);
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
if ((dxAge!= null)&&(ka!=null)) {
numDxvsKa++;
}
if ((dxAge!=null) && (sl!=null)) {
numDxvsSl++;
}
// Object dx = rs.getAgeGroup();
// if(sl !=null && dx !=null){
// clinicalDataPoint.setSurvival(new Double(sl.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
// Object ks = rs.getKarnofskyClinicalEvalDE();
// Object dx = rs.getAgeGroup();
// if(ks !=null && dx !=null){
// clinicalDataPoint.setNeurologicalAssessment(new Double(ks.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
clinicalData.add(clinicalDataPoint);
}
}
}
System.out.println("Done creating points!");
//-------------------------------------------------------------
//GET THE CLINICAL DATA AND POPULATE THE clinicalData list
//Note the ClinicalFinding is currently an empty class
//----------------------------------------------------------
//check the components to see which graph to get
if(components.equalsIgnoreCase("SurvivalvsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.SurvivalLength, "Survival Length (Months)",ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
if(components.equalsIgnoreCase("KarnofskyScorevsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.KarnofskyAssessment, "Karnofsky Score", ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(),"png",600,500);
//The final complete path to be used by the webapplication
String finalPath = imageHandler.getSessionTempFolder();
String finalURLpath = imageHandler.getFinalURLPath();
/*
* Create the actual charts, writing it to the session temp folder
*/
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String mapName = imageHandler.createUniqueMapName();
ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath),chart, 600,500,info);
/* This is here to put the thread into a loop while it waits for the
* image to be available. It has an unsophisticated timer but at
* least it is something to avoid an endless loop.
**/
boolean imageReady = false;
int timeout = 1000;
FileInputStream inputStream = null;
while(!imageReady) {
timeout--;
try {
inputStream = new FileInputStream(finalPath);
inputStream.available();
imageReady = true;
inputStream.close();
}catch(IOException ioe) {
imageReady = false;
if(inputStream != null){
inputStream.close();
}
}
if(timeout <= 1) {
break;
}
}
out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName,false,info));
//finalURLpath = finalURLpath.replace("\\", "/");
finalURLpath = finalURLpath.replace("\\", "/");
long randomness = System.currentTimeMillis(); //prevent image caching
out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"?"+randomness+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
//out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
}catch (IOException e) {
logger.error(e);
}catch(Exception e) {
logger.error(e);
}catch(Throwable t) {
logger.error(t);
}
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException {
return doAfterEndTag(EVAL_PAGE);
}
public void reset() {
//chartDefinition = createChartDefinition();
}
/**
* @return Returns the bean.
*/
public String getBean() {
return beanName;
}
/**
* @param bean The bean to set.
*/
public void setBean(String bean) {
this.beanName = bean;
}
/**
* @return Returns the taskId.
*/
public String getTaskId() {
return taskId;
}
/**
* @param taskId The taskId to set.
*/
public void setTaskId(String taskId) {
this.taskId = taskId;
}
/**
* @return Returns the colorBy.
*/
public String getColorBy() {
return colorBy;
}
/**
* @param colorBy The colorBy to set.
*/
public void setColorBy(String colorBy) {
this.colorBy = colorBy;
}
/**
* @return Returns the components.
*/
public String getComponents() {
return components;
}
/**
* @param components The components to set.
*/
public void setComponents(String components) {
this.components = components;
}
}
| true | true | public int doStartTag() {
chart = null;
clinicalData.clear();
ServletRequest request = pageContext.getRequest();
HttpSession session = pageContext.getSession();
Object o = request.getAttribute(beanName);
JspWriter out = pageContext.getOut();
ServletResponse response = pageContext.getResponse();
try {
//
//retrieve the Finding from cache and build the list of Clinical Data points
//ClinicalFinding clinicalFinding = (ClinicalFinding)businessTierCache.getSessionFinding(session.getId(),taskId);
ReportBean clincalReportBean = presentationTierCache.getReportBean(session.getId(),taskId);
Resultant clinicalResultant = clincalReportBean.getResultant();
ResultsContainer resultsContainer = clinicalResultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
if(sampleViewContainer!=null){
Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
clinicalFactors.add(ClinicalFactorType.AgeAtDx);
//clinicalFactors.add(ClinicalFactorType.Survival);
Collection<SampleResultset> samples = sampleViewContainer.getSampleResultsets();
if(samples!=null){
int numDxvsKa=0;
int numDxvsSl = 0;
for (SampleResultset rs:samples){
//String id = rs.getBiospecimen().getValueObject();
String id = rs.getSampleIDDE().getValueObject();
ClinicalDataPoint clinicalDataPoint = new ClinicalDataPoint(id);
String diseaseName = rs.getDisease().getValueObject();
if(diseaseName!=null){
clinicalDataPoint.setDiseaseName(diseaseName);
}
else{
clinicalDataPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
}
Long sl = rs.getSurvivalLength();
double survivalDays = -1.0;
double survivalMonths = -1.0;
if (sl != null) {
survivalDays = sl.doubleValue();
survivalMonths = survivalDays/30.0;
//if ((survivalMonths > 0.0)&&(survivalMonths < 1000.0)) {
clinicalDataPoint.setSurvival(survivalDays);
//}
}
Long dxAge = rs.getAge();
if (dxAge != null) {
clinicalDataPoint.setAgeAtDx(dxAge.doubleValue());
}
KarnofskyClinicalEvalDE ka = rs.getKarnofskyClinicalEvalDE();
if (ka != null) {
String kaStr = ka.getValueObject();
if (kaStr != null) {
if(kaStr.contains(",")) {
String [] kaStrArray = kaStr.split(",");
for(int i =0;i<kaStrArray.length;i++){
if (i==0) {
//first score is baseline just use this for now
//later we will need to use all score in a series for each patient
double kaVal = Double.parseDouble(kaStrArray[i].trim());
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
else{
double kaVal = Double.parseDouble(kaStr);
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
if ((dxAge!= null)&&(ka!=null)) {
numDxvsKa++;
}
if ((dxAge!=null) && (sl!=null)) {
numDxvsSl++;
}
// Object dx = rs.getAgeGroup();
// if(sl !=null && dx !=null){
// clinicalDataPoint.setSurvival(new Double(sl.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
// Object ks = rs.getKarnofskyClinicalEvalDE();
// Object dx = rs.getAgeGroup();
// if(ks !=null && dx !=null){
// clinicalDataPoint.setNeurologicalAssessment(new Double(ks.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
clinicalData.add(clinicalDataPoint);
}
}
}
System.out.println("Done creating points!");
//-------------------------------------------------------------
//GET THE CLINICAL DATA AND POPULATE THE clinicalData list
//Note the ClinicalFinding is currently an empty class
//----------------------------------------------------------
//check the components to see which graph to get
if(components.equalsIgnoreCase("SurvivalvsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.SurvivalLength, "Survival Length (Months)",ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
if(components.equalsIgnoreCase("KarnofskyScorevsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.KarnofskyAssessment, "Karnofsky Score", ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(),"png",600,500);
//The final complete path to be used by the webapplication
String finalPath = imageHandler.getSessionTempFolder();
String finalURLpath = imageHandler.getFinalURLPath();
/*
* Create the actual charts, writing it to the session temp folder
*/
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String mapName = imageHandler.createUniqueMapName();
ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath),chart, 600,500,info);
/* This is here to put the thread into a loop while it waits for the
* image to be available. It has an unsophisticated timer but at
* least it is something to avoid an endless loop.
**/
boolean imageReady = false;
int timeout = 1000;
FileInputStream inputStream = null;
while(!imageReady) {
timeout--;
try {
inputStream = new FileInputStream(finalPath);
inputStream.available();
imageReady = true;
inputStream.close();
}catch(IOException ioe) {
imageReady = false;
if(inputStream != null){
inputStream.close();
}
}
if(timeout <= 1) {
break;
}
}
out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName,false,info));
//finalURLpath = finalURLpath.replace("\\", "/");
finalURLpath = finalURLpath.replace("\\", "/");
long randomness = System.currentTimeMillis(); //prevent image caching
out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"?"+randomness+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
//out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
}catch (IOException e) {
logger.error(e);
}catch(Exception e) {
logger.error(e);
}catch(Throwable t) {
logger.error(t);
}
return EVAL_BODY_INCLUDE;
}
| public int doStartTag() {
chart = null;
clinicalData.clear();
ServletRequest request = pageContext.getRequest();
HttpSession session = pageContext.getSession();
Object o = request.getAttribute(beanName);
JspWriter out = pageContext.getOut();
ServletResponse response = pageContext.getResponse();
try {
//
//retrieve the Finding from cache and build the list of Clinical Data points
//ClinicalFinding clinicalFinding = (ClinicalFinding)businessTierCache.getSessionFinding(session.getId(),taskId);
ReportBean clincalReportBean = presentationTierCache.getReportBean(session.getId(),taskId);
Resultant clinicalResultant = clincalReportBean.getResultant();
ResultsContainer resultsContainer = clinicalResultant.getResultsContainer();
SampleViewResultsContainer sampleViewContainer = null;
if(resultsContainer instanceof DimensionalViewContainer){
DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
}
if(sampleViewContainer!=null){
Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
clinicalFactors.add(ClinicalFactorType.AgeAtDx);
//clinicalFactors.add(ClinicalFactorType.Survival);
Collection<SampleResultset> samples = sampleViewContainer.getSampleResultsets();
if(samples!=null){
int numDxvsKa=0;
int numDxvsSl = 0;
for (SampleResultset rs:samples){
//String id = rs.getBiospecimen().getValueObject();
String id = rs.getSampleIDDE().getValueObject();
ClinicalDataPoint clinicalDataPoint = new ClinicalDataPoint(id);
String diseaseName = rs.getDisease().getValueObject();
if(diseaseName!=null){
clinicalDataPoint.setDiseaseName(diseaseName);
}
else{
clinicalDataPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
}
Long sl = rs.getSurvivalLength();
double survivalDays = -1.0;
double survivalMonths = -1.0;
if (sl != null) {
survivalDays = sl.doubleValue();
survivalMonths = survivalDays/30.0;
//if ((survivalMonths > 0.0)&&(survivalMonths < 1000.0)) {
clinicalDataPoint.setSurvival(survivalDays);
//}
}
Long dxAge = rs.getAge();
if (dxAge != null) {
clinicalDataPoint.setAgeAtDx(dxAge.doubleValue());
}
KarnofskyClinicalEvalDE ka = rs.getKarnofskyClinicalEvalDE();
if (ka != null) {
String kaStr = ka.getValueObject();
if (kaStr != null) {
if(kaStr.contains("|")) {
kaStr =kaStr.trim();
String [] kaStrArray = kaStr.split("\\|");
for(int i =0;i<kaStrArray.length;i++){
if (i==0) {
//first score is baseline just use this for now
//later we will need to use all score in a series for each patient
double kaVal = Double.parseDouble(kaStrArray[i].trim());
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
else{
double kaVal = Double.parseDouble(kaStr);
clinicalDataPoint.setKarnofskyScore(kaVal);
}
}
}
if ((dxAge!= null)&&(ka!=null)) {
numDxvsKa++;
}
if ((dxAge!=null) && (sl!=null)) {
numDxvsSl++;
}
// Object dx = rs.getAgeGroup();
// if(sl !=null && dx !=null){
// clinicalDataPoint.setSurvival(new Double(sl.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
// Object ks = rs.getKarnofskyClinicalEvalDE();
// Object dx = rs.getAgeGroup();
// if(ks !=null && dx !=null){
// clinicalDataPoint.setNeurologicalAssessment(new Double(ks.toString()));
// clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
// }
clinicalData.add(clinicalDataPoint);
}
}
}
System.out.println("Done creating points!");
//-------------------------------------------------------------
//GET THE CLINICAL DATA AND POPULATE THE clinicalData list
//Note the ClinicalFinding is currently an empty class
//----------------------------------------------------------
//check the components to see which graph to get
if(components.equalsIgnoreCase("SurvivalvsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.SurvivalLength, "Survival Length (Months)",ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
if(components.equalsIgnoreCase("KarnofskyScorevsAgeAtDx")){
chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,ClinicalFactorType.KarnofskyAssessment, "Karnofsky Score", ClinicalFactorType.AgeAtDx, "Age At Diagnosis (Years)");
}
RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(),"png",600,500);
//The final complete path to be used by the webapplication
String finalPath = imageHandler.getSessionTempFolder();
String finalURLpath = imageHandler.getFinalURLPath();
/*
* Create the actual charts, writing it to the session temp folder
*/
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
String mapName = imageHandler.createUniqueMapName();
ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath),chart, 600,500,info);
/* This is here to put the thread into a loop while it waits for the
* image to be available. It has an unsophisticated timer but at
* least it is something to avoid an endless loop.
**/
boolean imageReady = false;
int timeout = 1000;
FileInputStream inputStream = null;
while(!imageReady) {
timeout--;
try {
inputStream = new FileInputStream(finalPath);
inputStream.available();
imageReady = true;
inputStream.close();
}catch(IOException ioe) {
imageReady = false;
if(inputStream != null){
inputStream.close();
}
}
if(timeout <= 1) {
break;
}
}
out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName,false,info));
//finalURLpath = finalURLpath.replace("\\", "/");
finalURLpath = finalURLpath.replace("\\", "/");
long randomness = System.currentTimeMillis(); //prevent image caching
out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"?"+randomness+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
//out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"\" usemap=\"#"+mapName + "\" border=\"0\" />");
}catch (IOException e) {
logger.error(e);
}catch(Exception e) {
logger.error(e);
}catch(Throwable t) {
logger.error(t);
}
return EVAL_BODY_INCLUDE;
}
|
diff --git a/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java b/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java
index acac911..4bf2ee8 100644
--- a/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java
+++ b/src/net/sf/antcontrib/cpptasks/types/LibrarySet.java
@@ -1,347 +1,347 @@
/*
*
* Copyright 2001-2006 The Ant-Contrib project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.antcontrib.cpptasks.types;
import java.io.File;
import net.sf.antcontrib.cpptasks.CUtil;
import net.sf.antcontrib.cpptasks.FileVisitor;
import net.sf.antcontrib.cpptasks.compiler.Linker;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.DataType;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.PatternSet;
/**
* A set of library names. Libraries can also be added to a link by specifying
* them in a fileset.
*
* For most Unix-like compilers, libset will result in a series of -l and -L
* linker arguments. For Windows compilers, the library names will be used to
* locate the appropriate library files which will be added to the linkers
* input file list as if they had been specified in a fileset.
*
* @author Mark A Russell <a
* href="mailto:[email protected]">mark_russell@csg_systems.com
* </a>
* @author Adam Murdoch
* @author Curt Arnold
*/
public class LibrarySet extends DataType {
private String dataset;
private boolean explicitCaseSensitive;
private String ifCond;
private String[] libnames;
private final FileSet set = new FileSet();
private String unlessCond;
private LibraryTypeEnum libraryType;
public LibrarySet() {
libnames = new String[0];
}
public void execute() throws org.apache.tools.ant.BuildException {
throw new org.apache.tools.ant.BuildException(
"Not an actual task, but looks like one for documentation purposes");
}
/**
* Gets the dataset. Used on OS390 if the libs are in a dataset.
*
* @return Returns a String
*/
public String getDataset() {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.getDataset();
}
return dataset;
}
public File getDir(final Project project) {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.getDir(project);
}
return set.getDir(project);
}
protected FileSet getFileSet() {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.getFileSet();
}
return set;
}
public String[] getLibs() {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.getLibs();
}
String[] retval = (String[]) libnames.clone();
return retval;
}
/**
* Gets preferred library type
*
* @return library type, may be null.
*/
public LibraryTypeEnum getType() {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.getType();
}
return libraryType;
}
/**
* Returns true if the define's if and unless conditions (if any) are
* satisfied.
*/
public boolean isActive(final org.apache.tools.ant.Project p) {
if (p == null) {
throw new NullPointerException("p");
}
if (ifCond != null) {
String ifValue = p.getProperty(ifCond);
if (ifValue != null) {
if (ifValue.equals("no") || ifValue.equals("false")) {
throw new BuildException(
"property "
+ ifCond
+ " used as if condition has value "
+ ifValue
+ " which suggests a misunderstanding of if attributes");
}
} else {
return false;
}
}
if (unlessCond != null) {
String unlessValue = p.getProperty(unlessCond);
if (unlessValue != null) {
if (unlessValue.equals("no") || unlessValue.equals("false")) {
throw new BuildException(
"property "
+ unlessCond
+ " used as unless condition has value "
+ unlessValue
+ " which suggests a misunderstanding of unless attributes");
}
return false;
}
}
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
return master.isActive(project);
}
if (libnames.length == 0) {
p.log("libnames not specified or empty.", Project.MSG_WARN);
return false;
}
return true;
}
/**
* Sets case sensitivity of the file system. If not set, will default to
* the linker's case sensitivity.
*
* @param isCaseSensitive
* "true"|"on"|"yes" if file system is case sensitive,
* "false"|"off"|"no" when not.
*/
public void setCaseSensitive(final boolean isCaseSensitive) {
if (isReference()) {
throw tooManyAttributes();
}
explicitCaseSensitive = true;
set.setCaseSensitive(isCaseSensitive);
}
/**
* Sets the dataset. Used on OS390 if the libs are in a dataset.
*
* @param dataset
* The dataset to set
*/
public void setDataset(final String dataset) {
if (isReference()) {
throw tooManyAttributes();
}
this.dataset = dataset;
}
/**
* Library directory.
*
* @param dir
* library directory
*
*/
public void setDir(final File dir) throws BuildException {
if (isReference()) {
throw tooManyAttributes();
}
set.setDir(dir);
}
/**
* Sets the property name for the 'if' condition.
*
* The library set will be ignored unless the property is defined.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") will throw an exception when
* evaluated.
*
* @param propName
* property name
*/
public void setIf(String propName) {
ifCond = propName;
}
/**
* Comma-separated list of library names without leading prefixes, such as
* "lib", or extensions, such as ".so" or ".a".
*
*/
public void setLibs(final CUtil.StringArrayBuilder libs) throws BuildException {
if (isReference()) {
throw tooManyAttributes();
}
libnames = libs.getValue();
//
// earlier implementations would warn of suspicious library names
// (like libpthread for pthread or kernel.lib for kernel).
// visitLibraries now provides better feedback and ld type linkers
// should provide adequate feedback so the check here is not necessary.
}
public void setProject(final Project project) {
set.setProject(project);
super.setProject(project);
}
/**
* Set the property name for the 'unless' condition.
*
* If named property is set, the library set will be ignored.
*
* The value of the property is insignificant, but values that would imply
* misinterpretation ("false", "no") of the behavior will throw an
* exception when evaluated.
*
* @param propName
* name of property
*/
public void setUnless(String propName) {
unlessCond = propName;
}
/**
* Sets the preferred library type. Supported values "shared", "static", and
* "framework". "framework" is equivalent to "shared" on non-Darwin platforms.
*/
public void setType(final LibraryTypeEnum type) {
if (isReference()) {
throw tooManyAttributes();
}
this.libraryType = type;
}
public void visitLibraries(final Project project,
final Linker linker,
final File[] libpath,
final FileVisitor visitor) throws BuildException {
if (isReference()) {
- LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
+ LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
master.visitLibraries(project, linker, libpath, visitor);
}
//
// if there was a libs attribute then
// add the corresponding patterns to the FileSet
//
if (libnames != null) {
for (int i = 0; i < libnames.length; i++) {
String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType);
if (patterns.length > 0) {
FileSet localSet = (FileSet) set.clone();
//
// unless explicitly set
// will default to the linker case sensitivity
//
if (!explicitCaseSensitive) {
boolean linkerCaseSensitive = linker.isCaseSensitive();
localSet.setCaseSensitive(linkerCaseSensitive);
}
//
// add all the patterns for this libname
//
for (int j = 0; j < patterns.length; j++) {
PatternSet.NameEntry entry = localSet.createInclude();
entry.setName(patterns[j]);
}
int matches = 0;
//
// if there was no specified directory then
// run through the libpath backwards
//
if (localSet.getDir(project) == null) {
//
// scan libpath in reverse order
// to give earlier entries priority
//
for (int j = libpath.length - 1; j >= 0; j--) {
FileSet clone = (FileSet) localSet.clone();
clone.setDir(libpath[j]);
DirectoryScanner scanner = clone.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
} else {
DirectoryScanner scanner = localSet.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
//
// TODO: following section works well for Windows
// style linkers but unnecessary fails
// Unix style linkers. Will need to revisit.
//
- if (matches == 0 && false) {
+ if (matches == 0) {
StringBuffer msg = new StringBuffer("No file matching ");
if (patterns.length == 1) {
msg.append("pattern (");
msg.append(patterns[0]);
msg.append(")");
} else {
msg.append("patterns (\"");
msg.append(patterns[0]);
for (int k = 1; k < patterns.length; k++) {
msg.append(", ");
msg.append(patterns[k]);
}
msg.append(")");
}
msg.append(" for library name \"");
msg.append(libnames[i]);
msg.append("\" was found.");
throw new BuildException(msg.toString());
}
}
}
}
}
}
| false | true | public void visitLibraries(final Project project,
final Linker linker,
final File[] libpath,
final FileVisitor visitor) throws BuildException {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
master.visitLibraries(project, linker, libpath, visitor);
}
//
// if there was a libs attribute then
// add the corresponding patterns to the FileSet
//
if (libnames != null) {
for (int i = 0; i < libnames.length; i++) {
String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType);
if (patterns.length > 0) {
FileSet localSet = (FileSet) set.clone();
//
// unless explicitly set
// will default to the linker case sensitivity
//
if (!explicitCaseSensitive) {
boolean linkerCaseSensitive = linker.isCaseSensitive();
localSet.setCaseSensitive(linkerCaseSensitive);
}
//
// add all the patterns for this libname
//
for (int j = 0; j < patterns.length; j++) {
PatternSet.NameEntry entry = localSet.createInclude();
entry.setName(patterns[j]);
}
int matches = 0;
//
// if there was no specified directory then
// run through the libpath backwards
//
if (localSet.getDir(project) == null) {
//
// scan libpath in reverse order
// to give earlier entries priority
//
for (int j = libpath.length - 1; j >= 0; j--) {
FileSet clone = (FileSet) localSet.clone();
clone.setDir(libpath[j]);
DirectoryScanner scanner = clone.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
} else {
DirectoryScanner scanner = localSet.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
//
// TODO: following section works well for Windows
// style linkers but unnecessary fails
// Unix style linkers. Will need to revisit.
//
if (matches == 0 && false) {
StringBuffer msg = new StringBuffer("No file matching ");
if (patterns.length == 1) {
msg.append("pattern (");
msg.append(patterns[0]);
msg.append(")");
} else {
msg.append("patterns (\"");
msg.append(patterns[0]);
for (int k = 1; k < patterns.length; k++) {
msg.append(", ");
msg.append(patterns[k]);
}
msg.append(")");
}
msg.append(" for library name \"");
msg.append(libnames[i]);
msg.append("\" was found.");
throw new BuildException(msg.toString());
}
}
}
}
}
| public void visitLibraries(final Project project,
final Linker linker,
final File[] libpath,
final FileVisitor visitor) throws BuildException {
if (isReference()) {
LibrarySet master = ((LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet"));
master.visitLibraries(project, linker, libpath, visitor);
}
//
// if there was a libs attribute then
// add the corresponding patterns to the FileSet
//
if (libnames != null) {
for (int i = 0; i < libnames.length; i++) {
String[] patterns = linker.getLibraryPatterns(new String[] { libnames[i] }, libraryType);
if (patterns.length > 0) {
FileSet localSet = (FileSet) set.clone();
//
// unless explicitly set
// will default to the linker case sensitivity
//
if (!explicitCaseSensitive) {
boolean linkerCaseSensitive = linker.isCaseSensitive();
localSet.setCaseSensitive(linkerCaseSensitive);
}
//
// add all the patterns for this libname
//
for (int j = 0; j < patterns.length; j++) {
PatternSet.NameEntry entry = localSet.createInclude();
entry.setName(patterns[j]);
}
int matches = 0;
//
// if there was no specified directory then
// run through the libpath backwards
//
if (localSet.getDir(project) == null) {
//
// scan libpath in reverse order
// to give earlier entries priority
//
for (int j = libpath.length - 1; j >= 0; j--) {
FileSet clone = (FileSet) localSet.clone();
clone.setDir(libpath[j]);
DirectoryScanner scanner = clone.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
} else {
DirectoryScanner scanner = localSet.getDirectoryScanner(project);
File basedir = scanner.getBasedir();
String[] files = scanner.getIncludedFiles();
matches += files.length;
for (int k = 0; k < files.length; k++) {
visitor.visit(basedir, files[k]);
}
}
//
// TODO: following section works well for Windows
// style linkers but unnecessary fails
// Unix style linkers. Will need to revisit.
//
if (matches == 0) {
StringBuffer msg = new StringBuffer("No file matching ");
if (patterns.length == 1) {
msg.append("pattern (");
msg.append(patterns[0]);
msg.append(")");
} else {
msg.append("patterns (\"");
msg.append(patterns[0]);
for (int k = 1; k < patterns.length; k++) {
msg.append(", ");
msg.append(patterns[k]);
}
msg.append(")");
}
msg.append(" for library name \"");
msg.append(libnames[i]);
msg.append("\" was found.");
throw new BuildException(msg.toString());
}
}
}
}
}
|
diff --git a/bianca/src/main/java/com/clevercloud/bianca/env/DoubleValue.java b/bianca/src/main/java/com/clevercloud/bianca/env/DoubleValue.java
index d1c2aac5..f847844c 100644
--- a/bianca/src/main/java/com/clevercloud/bianca/env/DoubleValue.java
+++ b/bianca/src/main/java/com/clevercloud/bianca/env/DoubleValue.java
@@ -1,534 +1,534 @@
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
* Copyright (c) 2011-2012 Clever Cloud SAS -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
* @author Marc-Antoine Perennou <[email protected]>
*/
package com.clevercloud.bianca.env;
import com.clevercloud.bianca.marshal.Marshal;
import com.clevercloud.vfs.WriteStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.IdentityHashMap;
/**
* Represents a PHP double value.
*/
public class DoubleValue extends NumberValue
implements Serializable {
public static final DoubleValue ZERO = new DoubleValue(0);
private final double _value;
public DoubleValue(double value) {
_value = value;
}
public static DoubleValue create(double value) {
return new DoubleValue(value);
}
public static Value create(Number value) {
if (value == null) {
// php/3c2d
return NullValue.NULL;
} else {
return new DoubleValue(value.doubleValue());
}
}
/**
* Returns the type.
*/
@Override
public String getType() {
// php/0142
return "double";
}
/**
* Returns the ValueType.
*/
@Override
public ValueType getValueType() {
return ValueType.DOUBLE;
}
/**
* Returns true for a double.
*/
@Override
public boolean isDoubleConvertible() {
return true;
}
/**
* Returns true for integer looking doubles.
*/
@Override
public boolean isLongConvertible() {
return _value == (double) ((long) _value);
}
/**
* Returns true for a long-value.
*/
@Override
public boolean isLong() {
return false;
}
/**
* Returns true for a double-value.
*/
@Override
public boolean isDouble() {
return true;
}
/**
* Returns true for is_numeric
*/
@Override
public boolean isNumeric() {
return true;
}
/**
* Returns true for a scalar
*/
public boolean isScalar() {
return true;
}
//
// marshal cost
//
/**
* Cost to convert to a double
*/
@Override
public int toDoubleMarshalCost() {
return Marshal.COST_EQUAL;
}
/**
* Cost to convert to a long
*/
@Override
public int toLongMarshalCost() {
return Marshal.COST_NUMERIC_LOSSY;
}
/**
* Cost to convert to an integer
*/
@Override
public int toIntegerMarshalCost() {
return Marshal.COST_NUMERIC_LOSSY;
}
/**
* Cost to convert to a short
*/
@Override
public int toShortMarshalCost() {
return Marshal.COST_NUMERIC_LOSSY;
}
/**
* Cost to convert to a byte
*/
@Override
public int toByteMarshalCost() {
return Marshal.COST_NUMERIC_LOSSY;
}
//
// conversions
//
/**
* Converts to a boolean.
*/
@Override
public boolean toBoolean() {
return _value != 0;
}
/**
* Converts to a long.
*/
@Override
public long toLong() {
if ((_value > (double) Long.MAX_VALUE)
|| (_value < (double) Long.MIN_VALUE)) {
return 0;
} else {
return (long) _value;
}
}
/**
* Converts to a double.
*/
@Override
public double toDouble() {
return _value;
}
/**
* Converts to a double.
*/
@Override
public DoubleValue toDoubleValue() {
return this;
}
/**
* Converts to a string builder
*/
@Override
public StringValue toStringBuilder(Env env) {
return new StringValue().append(toString());
}
/**
* Converts to a key.
*/
@Override
public Value toKey() {
return LongValue.create((long) _value);
}
/**
* Converts to a java object.
*/
@Override
public Object toJavaObject() {
return new Double(_value);
}
/**
* Negates the value.
*/
@Override
public Value neg() {
return new DoubleValue(-_value);
}
/**
* Returns the value
*/
@Override
public Value pos() {
return this;
}
/**
* Multiplies to the following value.
*/
@Override
public Value add(Value rValue) {
return new DoubleValue(_value + rValue.toDouble());
}
/**
* Multiplies to the following value.
*/
@Override
public Value add(long lValue) {
return new DoubleValue(lValue + _value);
}
/**
* Increment the following value.
*/
@Override
public Value addOne() {
return new DoubleValue(_value + 1);
}
/**
* Increment the following value.
*/
@Override
public Value subOne() {
double next = _value - 1;
/*
if (next == (long) next)
return LongValue.create(next);
else
*/
return new DoubleValue(next);
}
/**
* Increment the following value.
*/
@Override
public Value preincr() {
return new DoubleValue(_value + 1);
}
/**
* Increment the following value.
*/
@Override
public Value predecr() {
return new DoubleValue(_value - 1);
}
/**
* Increment the following value.
*/
@Override
public Value postincr() {
return new DoubleValue(_value + 1);
}
/**
* Increment the following value.
*/
@Override
public Value postdecr() {
return new DoubleValue(_value - 1);
}
/**
* Increment the following value.
*/
@Override
public Value increment(int incr) {
return new DoubleValue(_value + incr);
}
/**
* Multiplies to the following value.
*/
@Override
public Value mul(Value rValue) {
return new DoubleValue(_value * rValue.toDouble());
}
/**
* Multiplies to the following value.
*/
@Override
public Value mul(long lValue) {
return new DoubleValue(lValue * _value);
}
/**
* Absolute value.
*/
@Override
public Value abs() {
if (_value >= 0) {
return this;
} else {
return DoubleValue.create(-_value);
}
}
/**
* Returns true for equality
*/
@Override
public boolean eql(Value rValue) {
rValue = rValue.toValue();
if (!(rValue instanceof DoubleValue)) {
return false;
}
double rDouble = ((DoubleValue) rValue)._value;
return _value == rDouble;
}
/**
* Converts to a string.
* @param env
*/
@Override
public String toString() {
long longValue = (long) _value;
double abs = _value < 0 ? -_value : _value;
int exp = (int) Math.log10(abs);
// php/0c02
if (longValue == _value && exp < 18) {
return String.valueOf(longValue);
}
if (-5 < exp && exp < 18) {
int digits = 13 - exp;
if (digits > 13) {
digits = 13;
} else if (digits < 0) {
digits = 0;
}
String v = String.format("%." + digits + "f", _value);
int len = v.length();
int nonzero = -1;
boolean dot = false;
for (len--; len >= 0; len--) {
int ch = v.charAt(len);
- if (ch == '.') {
+ if (ch == '.' || ch == ',') {
dot = true;
}
if (ch != '0' && nonzero < 0) {
- if (ch == '.') {
+ if (ch == '.' || ch == ',') {
nonzero = len - 1;
} else {
nonzero = len;
}
}
}
if (dot && nonzero >= 0) {
return v.substring(0, nonzero + 1);
} else {
return v;
}
} else {
return String.format("%.13E", _value);
}
}
/**
* Converts to an object.
*/
public Object toObject() {
return toString();
}
/**
* Prints the value.
* @param env
*/
@Override
public void print(Env env) {
env.print(toString());
}
/**
* Serializes the value.
*/
@Override
public void serialize(Env env, StringBuilder sb) {
sb.append("d:");
sb.append(_value);
sb.append(";");
}
/**
* Exports the value.
*/
@Override
public void varExport(StringBuilder sb) {
sb.append(toString());
}
//
// Java generator code
//
/**
* Generates code to recreate the expression.
*
* @param out the writer to the Java source code.
*/
@Override
public void generate(PrintWriter out)
throws IOException {
if (_value == 0) {
out.print("DoubleValue.ZERO");
} else if (_value == Double.POSITIVE_INFINITY) {
out.print("new DoubleValue(Double.POSITIVE_INFINITY)");
} else if (_value == Double.NEGATIVE_INFINITY) {
out.print("new DoubleValue(Double.NEGATIVE_INFINITY)");
} else {
out.print("new DoubleValue(" + _value + ")");
}
}
/**
* Returns the hash code
*/
@Override
public int hashCode() {
return (int) (37 + 65521 * _value);
}
/**
* Compare for equality.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof DoubleValue)) {
return false;
}
DoubleValue value = (DoubleValue) o;
return _value == value._value;
}
@Override
public void varDumpImpl(Env env,
WriteStream out,
int depth,
IdentityHashMap<Value, String> valueSet)
throws IOException {
out.print("float(" + toString() + ")");
}
//
// Java Serialization
//
private Object readResolve() {
if (_value == 0) {
return ZERO;
} else {
return this;
}
}
}
| false | true | public String toString() {
long longValue = (long) _value;
double abs = _value < 0 ? -_value : _value;
int exp = (int) Math.log10(abs);
// php/0c02
if (longValue == _value && exp < 18) {
return String.valueOf(longValue);
}
if (-5 < exp && exp < 18) {
int digits = 13 - exp;
if (digits > 13) {
digits = 13;
} else if (digits < 0) {
digits = 0;
}
String v = String.format("%." + digits + "f", _value);
int len = v.length();
int nonzero = -1;
boolean dot = false;
for (len--; len >= 0; len--) {
int ch = v.charAt(len);
if (ch == '.') {
dot = true;
}
if (ch != '0' && nonzero < 0) {
if (ch == '.') {
nonzero = len - 1;
} else {
nonzero = len;
}
}
}
if (dot && nonzero >= 0) {
return v.substring(0, nonzero + 1);
} else {
return v;
}
} else {
return String.format("%.13E", _value);
}
}
| public String toString() {
long longValue = (long) _value;
double abs = _value < 0 ? -_value : _value;
int exp = (int) Math.log10(abs);
// php/0c02
if (longValue == _value && exp < 18) {
return String.valueOf(longValue);
}
if (-5 < exp && exp < 18) {
int digits = 13 - exp;
if (digits > 13) {
digits = 13;
} else if (digits < 0) {
digits = 0;
}
String v = String.format("%." + digits + "f", _value);
int len = v.length();
int nonzero = -1;
boolean dot = false;
for (len--; len >= 0; len--) {
int ch = v.charAt(len);
if (ch == '.' || ch == ',') {
dot = true;
}
if (ch != '0' && nonzero < 0) {
if (ch == '.' || ch == ',') {
nonzero = len - 1;
} else {
nonzero = len;
}
}
}
if (dot && nonzero >= 0) {
return v.substring(0, nonzero + 1);
} else {
return v;
}
} else {
return String.format("%.13E", _value);
}
}
|
diff --git a/stripes/src/net/sourceforge/stripes/tag/layout/LayoutComponentTag.java b/stripes/src/net/sourceforge/stripes/tag/layout/LayoutComponentTag.java
index afe0a2c0..f48483bd 100644
--- a/stripes/src/net/sourceforge/stripes/tag/layout/LayoutComponentTag.java
+++ b/stripes/src/net/sourceforge/stripes/tag/layout/LayoutComponentTag.java
@@ -1,273 +1,274 @@
/* Copyright 2005-2006 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.tag.layout;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.jsp.JspException;
import net.sourceforge.stripes.exception.StripesJspException;
import net.sourceforge.stripes.util.Log;
/**
* Defines a component in a layout. Used both to define the components in a layout definition
* and to provide overridden component definitions during a layout rendering request.
*
* @author Tim Fennell, Ben Gunter
* @since Stripes 1.1
*/
public class LayoutComponentTag extends LayoutTag {
private static final Log log = Log.getInstance(LayoutComponentTag.class);
/** Regular expression that matches valid Java identifiers. */
private static final Pattern javaIdentifierPattern = Pattern
.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*");
private String name;
private LayoutContext context;
private boolean silent;
private Boolean componentRenderPhase;
/** Gets the name of the component. */
public String getName() { return name; }
/** Sets the name of the component. */
public void setName(String name) { this.name = name; }
/**
* Get the current layout context.
*
* @throws StripesJspException If a {@link LayoutContext} is not found.
*/
public LayoutContext getContext() throws StripesJspException {
if (context == null) {
context = LayoutContext.lookup(pageContext);
if (context == null) {
throw new StripesJspException("A component tag named \"" + getName() + "\" in "
+ getCurrentPagePath() + " was unable to find a layout context.");
}
log.trace("Component ", getName() + " has context ", context.getRenderPage(), " -> ",
context.getDefinitionPage());
}
return context;
}
/**
* True if this tag is a component that must execute so that the current component tag can
* execute. That is, this tag is a parent of the current component.
*
* @throws StripesJspException if thrown by {@link #getContext()}.
*/
protected boolean isPathComponent() throws StripesJspException {
List<String> path = getContext().getComponentPath();
return path == null ? false : isPathComponent(this, path.iterator());
}
/**
* Recursive method called from {@link #isPathComponent()} that returns true if the specified
* tag's name is present in the component path iterator at the same position where this tag
* occurs in the render/component tag tree. For example, if the path iterator contains the
* component names {@code ["foo", "bar"]} then this method will return true if the tag's name is
* {@code "bar"} and it is a child of a render tag that is a child of a component tag whose name
* is {@code "foo"}.
*
* @param tag The tag to check
* @param path The path to the check the tag against
* @return
*/
protected boolean isPathComponent(LayoutComponentTag tag, Iterator<String> path) {
LayoutTag parent = tag.getLayoutParent();
if (parent instanceof LayoutRenderTag) {
parent = parent.getLayoutParent();
if (parent == null || parent instanceof LayoutComponentTag
&& isPathComponent((LayoutComponentTag) parent, path) && path.hasNext()) {
return tag.getName().equals(path.next());
}
}
return false;
}
/**
* True if this tag is the component to be rendered on this pass from
* {@link LayoutDefinitionTag}.
*
* @throws StripesJspException If a {@link LayoutContext} is not found.
*/
public boolean isCurrentComponent() throws StripesJspException {
String name = getContext().getComponent();
return name != null && name.equals(getName());
}
/**
* <p>
* If this tag is nested within a {@link LayoutDefinitionTag}, then evaluate the corresponding
* {@link LayoutComponentTag} nested within the {@link LayoutRenderTag} that invoked the parent
* {@link LayoutDefinitionTag}. If, after evaluating the corresponding tag, the component has
* not been rendered then evaluate this tag's body by returning {@code EVAL_BODY_INCLUDE}.
* </p>
* <p>
* If this tag is nested within a {@link LayoutRenderTag} and this tag is the current component,
* as indicated by {@link LayoutContext#getComponent()}, then evaluate this tag's body by
* returning {@code EVAL_BODY_INCLUDE}.
* </p>
* <p>
* In all other cases, skip this tag's body by returning SKIP_BODY.
* </p>
*
* @return {@code EVAL_BODY_INCLUDE} or {@code SKIP_BODY}, as described above.
*/
@Override
public int doStartTag() throws JspException {
try {
LayoutContext context = getContext();
silent = context.getOut().isSilent();
if (context.isComponentRenderPhase()) {
if (isChildOfRender()) {
if (isCurrentComponent()) {
log.debug("Render ", getName(), " in ", context.getRenderPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
else if (isPathComponent()) {
log.debug("Silently execute '", getName(), "' in ", context.getRenderPage());
context.getOut().setSilent(true, pageContext);
return EVAL_BODY_INCLUDE;
}
else {
log.debug("No-op for ", getName(), " in ", context.getRenderPage());
}
}
else if (isChildOfDefinition()) {
log.debug("No-op for ", getName(), " in ", context.getDefinitionPage());
}
else if (isChildOfComponent()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for nested render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
}
else {
if (isChildOfRender()) {
if (!javaIdentifierPattern.matcher(getName()).matches()) {
log.warn("The layout-component name '", getName(),
"' is not a valid Java identifier. While this may work, it can ",
"cause bugs that are difficult to track down. Please consider ",
"using valid Java identifiers for component names ",
"(no hyphens, no spaces, etc.)");
}
log.debug("Register component ", getName(), " with ", context.getRenderPage());
context.getComponents().put(getName(), new LayoutComponentRenderer(getName()));
}
else if (isChildOfDefinition()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for direct render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
componentRenderPhase = context.isComponentRenderPhase();
context.setComponentRenderPhase(true);
+ context.setComponent(getName());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
else if (isChildOfComponent()) {
/*
* This condition cannot be true since component tags do not execute except in
* component render phase, thus any component tags embedded with them will not
* execute either. I've left this block here just as a placeholder for this
* explanation.
*/
}
}
context.getOut().setSilent(true, pageContext);
return SKIP_BODY;
}
catch (Exception e) {
log.error(e, "Unhandled exception trying to render component \"", getName(),
"\" to a string in context ", context.getRenderPage(), " -> ", context
.getDefinitionPage());
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new StripesJspException(e);
}
}
/**
* If this tag is the component that needs to be rendered, as indicated by
* {@link LayoutContext#getComponent()}, then set the current component name back to null to
* indicate that the component has rendered.
*
* @return SKIP_PAGE if this component is the current component, otherwise EVAL_PAGE.
*/
@Override
public int doEndTag() throws JspException {
try {
// Set current component name back to null as a signal to the component tag within the
// definition tag that the component did, indeed, render and it should not output the
// default contents.
LayoutContext context = getContext();
if (isCurrentComponent())
context.setComponent(null);
// If the component render phase flag was changed, then restore it now
if (componentRenderPhase != null)
context.setComponentRenderPhase(componentRenderPhase);
// Restore output's silent flag
context.getOut().setSilent(silent, pageContext);
return EVAL_PAGE;
}
finally {
this.context = null;
this.silent = false;
this.componentRenderPhase = null;
}
}
}
| true | true | public int doStartTag() throws JspException {
try {
LayoutContext context = getContext();
silent = context.getOut().isSilent();
if (context.isComponentRenderPhase()) {
if (isChildOfRender()) {
if (isCurrentComponent()) {
log.debug("Render ", getName(), " in ", context.getRenderPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
else if (isPathComponent()) {
log.debug("Silently execute '", getName(), "' in ", context.getRenderPage());
context.getOut().setSilent(true, pageContext);
return EVAL_BODY_INCLUDE;
}
else {
log.debug("No-op for ", getName(), " in ", context.getRenderPage());
}
}
else if (isChildOfDefinition()) {
log.debug("No-op for ", getName(), " in ", context.getDefinitionPage());
}
else if (isChildOfComponent()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for nested render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
}
else {
if (isChildOfRender()) {
if (!javaIdentifierPattern.matcher(getName()).matches()) {
log.warn("The layout-component name '", getName(),
"' is not a valid Java identifier. While this may work, it can ",
"cause bugs that are difficult to track down. Please consider ",
"using valid Java identifiers for component names ",
"(no hyphens, no spaces, etc.)");
}
log.debug("Register component ", getName(), " with ", context.getRenderPage());
context.getComponents().put(getName(), new LayoutComponentRenderer(getName()));
}
else if (isChildOfDefinition()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for direct render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
componentRenderPhase = context.isComponentRenderPhase();
context.setComponentRenderPhase(true);
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
else if (isChildOfComponent()) {
/*
* This condition cannot be true since component tags do not execute except in
* component render phase, thus any component tags embedded with them will not
* execute either. I've left this block here just as a placeholder for this
* explanation.
*/
}
}
context.getOut().setSilent(true, pageContext);
return SKIP_BODY;
}
catch (Exception e) {
log.error(e, "Unhandled exception trying to render component \"", getName(),
"\" to a string in context ", context.getRenderPage(), " -> ", context
.getDefinitionPage());
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new StripesJspException(e);
}
}
| public int doStartTag() throws JspException {
try {
LayoutContext context = getContext();
silent = context.getOut().isSilent();
if (context.isComponentRenderPhase()) {
if (isChildOfRender()) {
if (isCurrentComponent()) {
log.debug("Render ", getName(), " in ", context.getRenderPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
else if (isPathComponent()) {
log.debug("Silently execute '", getName(), "' in ", context.getRenderPage());
context.getOut().setSilent(true, pageContext);
return EVAL_BODY_INCLUDE;
}
else {
log.debug("No-op for ", getName(), " in ", context.getRenderPage());
}
}
else if (isChildOfDefinition()) {
log.debug("No-op for ", getName(), " in ", context.getDefinitionPage());
}
else if (isChildOfComponent()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for nested render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
}
else {
if (isChildOfRender()) {
if (!javaIdentifierPattern.matcher(getName()).matches()) {
log.warn("The layout-component name '", getName(),
"' is not a valid Java identifier. While this may work, it can ",
"cause bugs that are difficult to track down. Please consider ",
"using valid Java identifiers for component names ",
"(no hyphens, no spaces, etc.)");
}
log.debug("Register component ", getName(), " with ", context.getRenderPage());
context.getComponents().put(getName(), new LayoutComponentRenderer(getName()));
}
else if (isChildOfDefinition()) {
// Use a layout component renderer to do the heavy lifting
log.debug("Invoke component renderer for direct render of \"", getName(), "\"");
LayoutComponentRenderer renderer = (LayoutComponentRenderer) pageContext
.getAttribute(getName());
if (renderer == null)
log.debug("No component renderer in page context for '" + getName() + "'");
boolean rendered = renderer != null && renderer.write();
// If the component did not render then we need to output the default contents
// from the layout definition.
if (!rendered) {
log.debug("Component was not present in ", context.getRenderPage(),
" so using default content from ", context.getDefinitionPage());
componentRenderPhase = context.isComponentRenderPhase();
context.setComponentRenderPhase(true);
context.setComponent(getName());
context.getOut().setSilent(false, pageContext);
return EVAL_BODY_INCLUDE;
}
}
else if (isChildOfComponent()) {
/*
* This condition cannot be true since component tags do not execute except in
* component render phase, thus any component tags embedded with them will not
* execute either. I've left this block here just as a placeholder for this
* explanation.
*/
}
}
context.getOut().setSilent(true, pageContext);
return SKIP_BODY;
}
catch (Exception e) {
log.error(e, "Unhandled exception trying to render component \"", getName(),
"\" to a string in context ", context.getRenderPage(), " -> ", context
.getDefinitionPage());
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw new StripesJspException(e);
}
}
|
diff --git a/org.mosaic.runner/src/main/java/org/mosaic/runner/logging/FrameworkEventsLoggerListener.java b/org.mosaic.runner/src/main/java/org/mosaic/runner/logging/FrameworkEventsLoggerListener.java
index becea5b5..452fef57 100644
--- a/org.mosaic.runner/src/main/java/org/mosaic/runner/logging/FrameworkEventsLoggerListener.java
+++ b/org.mosaic.runner/src/main/java/org/mosaic/runner/logging/FrameworkEventsLoggerListener.java
@@ -1,61 +1,61 @@
package org.mosaic.runner.logging;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.osgi.framework.startlevel.FrameworkStartLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author arik
*/
public class FrameworkEventsLoggerListener implements FrameworkListener {
private final Logger logger = LoggerFactory.getLogger( "org.mosaic.osgi.framework" );
@Override
public void frameworkEvent( FrameworkEvent event ) {
@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" )
Throwable throwable = event.getThrowable();
String throwableMsg = throwable != null ? throwable.getMessage() : "";
switch( event.getType() ) {
case FrameworkEvent.STARTED:
this.logger.info( "Started the OSGi Framework" );
break;
case FrameworkEvent.ERROR:
this.logger.error( "OSGi Framework error has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.PACKAGES_REFRESHED:
- this.logger.info( "Refreshed OSGi packages have been refreshed" );
+ this.logger.info( "Refreshed OSGi packages" );
break;
case FrameworkEvent.STARTLEVEL_CHANGED:
FrameworkStartLevel startLevel = event.getBundle().adapt( FrameworkStartLevel.class );
this.logger.info( "OSGi Framework start level has been changed to: {}", startLevel.getStartLevel() );
break;
case FrameworkEvent.WARNING:
this.logger.warn( "OSGi Framework warning has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.INFO:
this.logger.info( "OSGi Framework informational has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.STOPPED:
this.logger.info( "Stopped the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_UPDATE:
this.logger.info( "Restarting the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED:
this.logger.info( "Restarting the OSGi Framework due to boot class-path modification" );
break;
}
}
}
| true | true | public void frameworkEvent( FrameworkEvent event ) {
@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" )
Throwable throwable = event.getThrowable();
String throwableMsg = throwable != null ? throwable.getMessage() : "";
switch( event.getType() ) {
case FrameworkEvent.STARTED:
this.logger.info( "Started the OSGi Framework" );
break;
case FrameworkEvent.ERROR:
this.logger.error( "OSGi Framework error has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.PACKAGES_REFRESHED:
this.logger.info( "Refreshed OSGi packages have been refreshed" );
break;
case FrameworkEvent.STARTLEVEL_CHANGED:
FrameworkStartLevel startLevel = event.getBundle().adapt( FrameworkStartLevel.class );
this.logger.info( "OSGi Framework start level has been changed to: {}", startLevel.getStartLevel() );
break;
case FrameworkEvent.WARNING:
this.logger.warn( "OSGi Framework warning has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.INFO:
this.logger.info( "OSGi Framework informational has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.STOPPED:
this.logger.info( "Stopped the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_UPDATE:
this.logger.info( "Restarting the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED:
this.logger.info( "Restarting the OSGi Framework due to boot class-path modification" );
break;
}
}
| public void frameworkEvent( FrameworkEvent event ) {
@SuppressWarnings( "ThrowableResultOfMethodCallIgnored" )
Throwable throwable = event.getThrowable();
String throwableMsg = throwable != null ? throwable.getMessage() : "";
switch( event.getType() ) {
case FrameworkEvent.STARTED:
this.logger.info( "Started the OSGi Framework" );
break;
case FrameworkEvent.ERROR:
this.logger.error( "OSGi Framework error has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.PACKAGES_REFRESHED:
this.logger.info( "Refreshed OSGi packages" );
break;
case FrameworkEvent.STARTLEVEL_CHANGED:
FrameworkStartLevel startLevel = event.getBundle().adapt( FrameworkStartLevel.class );
this.logger.info( "OSGi Framework start level has been changed to: {}", startLevel.getStartLevel() );
break;
case FrameworkEvent.WARNING:
this.logger.warn( "OSGi Framework warning has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.INFO:
this.logger.info( "OSGi Framework informational has occurred: {}", throwableMsg, throwable );
break;
case FrameworkEvent.STOPPED:
this.logger.info( "Stopped the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_UPDATE:
this.logger.info( "Restarting the OSGi Framework" );
break;
case FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED:
this.logger.info( "Restarting the OSGi Framework due to boot class-path modification" );
break;
}
}
|
diff --git a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
index d719777f2..ecbe62d90 100644
--- a/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
+++ b/software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/DynamicEventAction.java
@@ -1,385 +1,385 @@
package edu.wustl.catissuecore.action;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.cab2b.common.util.Utility;
import edu.wustl.catissuecore.actionForm.DynamicEventForm;
import edu.wustl.catissuecore.bizlogic.CatissueDefaultBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.processingprocedure.Action;
import edu.wustl.catissuecore.domain.processingprocedure.ActionApplication;
import edu.wustl.catissuecore.domain.processingprocedure.DefaultAction;
import edu.wustl.catissuecore.processor.SPPEventProcessor;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.SpecimenEventsUtility;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.factory.AbstractFactoryConfig;
import edu.wustl.common.factory.IFactory;
import edu.wustl.common.util.global.CommonServiceLocator;
import edu.wustl.common.util.global.CommonUtilities;
public class DynamicEventAction extends BaseAction
{
/**
* Overrides the executeSecureAction method of SecureAction class.
* @param mapping
* object of ActionMapping
* @param form
* object of ActionForm
* @param request
* object of HttpServletRequest
* @param response : HttpServletResponse
* @throws Exception
* generic exception
* @return ActionForward : ActionForward
*/
@Override
protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
- + eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString();
+ + eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString()+"&showCalculateDefaultValue=false";
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
/**
* @param request
* @param dynamicEventForm
*/
private void resetFormParameters(HttpServletRequest request, DynamicEventForm dynamicEventForm)
{
if("edit".equals(request.getParameter(Constants.OPERATION)) && request.getSession().getAttribute(Constants.DYN_EVENT_FORM)!= null)
{
DynamicEventForm originalForm = (DynamicEventForm) request.getSession().getAttribute(Constants.DYN_EVENT_FORM);
dynamicEventForm.setContId(originalForm.getContId());
dynamicEventForm.setReasonDeviation(originalForm.getReasonDeviation());
dynamicEventForm.setRecordEntry(originalForm.getRecordEntry());
dynamicEventForm.setRecordIdentifier(originalForm.getRecordIdentifier());
dynamicEventForm.setUserId(originalForm.getUserId());
dynamicEventForm.setTimeInHours(originalForm.getTimeInHours());
dynamicEventForm.setTimeInMinutes(originalForm.getTimeInMinutes());
dynamicEventForm.setId(originalForm.getId());
}
}
/**
* @param request
* @param dynamicEventForm
*/
private void populateStaticAttributes(HttpServletRequest request,
final DynamicEventForm dynamicEventForm)
{
String sessionMapName = "formContextParameterMap"+ getFormContextFromRequest(request);
Map<String, Object> formContextParameterMap = (Map<String, Object>) request.getSession().getAttribute(sessionMapName);
if(formContextParameterMap !=null && Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR)))
{
setDateParameters(request, formContextParameterMap);
dynamicEventForm.setTimeInMinutes((String) formContextParameterMap.get("timeInMinutes"));
dynamicEventForm.setTimeInHours((String) formContextParameterMap.get("timeInHours"));
dynamicEventForm.setUserId(Long.valueOf((String)formContextParameterMap.get(Constants.USER_ID)));
dynamicEventForm.setDateOfEvent((String) formContextParameterMap.get(Constants.DATE_OF_EVENT));
dynamicEventForm.setReasonDeviation((String) formContextParameterMap.get(Constants.REASON_DEVIATION));
request.getSession().removeAttribute(sessionMapName);
request.getSession().removeAttribute(Constants.DYN_EVENT_FORM);
}
}
/**
* @param request
* @param formContextParameterMap
*/
private void setDateParameters(HttpServletRequest request,
Map<String, Object> formContextParameterMap)
{
if(formContextParameterMap.get(Constants.DATE_OF_EVENT)!= null)
{
String currentEventParametersDate = (String) formContextParameterMap.get(Constants.DATE_OF_EVENT);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute("dynamicEventParametersYear", AppUtility
.getYear(currentEventParametersDate));
request.setAttribute("dynamicEventParametersDay", AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("dynamicEventParametersMonth", AppUtility
.getMonth(currentEventParametersDate));
}
}
/**
* @param request
* @return
*/
private String getFormContextFromRequest(HttpServletRequest request)
{
String formContxtId = request.getParameter("formContextId");
if(formContxtId == null)
{
formContxtId = String.valueOf(request.getAttribute("formContextId"));
}
return formContxtId;
}
}
| true | true | protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString();
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
| protected ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
if (request.getParameter(Constants.REFRESH_EVENT_GRID) != null)
{
request.setAttribute(Constants.REFRESH_EVENT_GRID, request
.getParameter(Constants.REFRESH_EVENT_GRID));
}
//this.setCommonRequestParameters(request);
DynamicEventForm dynamicEventForm = (DynamicEventForm) form;
resetFormParameters(request, dynamicEventForm);
// if operation is add
if (dynamicEventForm.isAddOperation())
{
if (dynamicEventForm.getUserId() == 0)
{
final SessionDataBean sessionData = this.getSessionData(request);
if (sessionData != null && sessionData.getUserId() != null)
{
final long userId = sessionData.getUserId().longValue();
dynamicEventForm.setUserId(userId);
}
}
// set the current Date and Time for the event.
final Calendar cal = Calendar.getInstance();
if (dynamicEventForm.getDateOfEvent() == null)
{
dynamicEventForm.setDateOfEvent(CommonUtilities.parseDateToString(cal.getTime(),
CommonServiceLocator.getInstance().getDatePattern()));
}
if (dynamicEventForm.getTimeInHours() == null)
{
dynamicEventForm.setTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (dynamicEventForm.getTimeInMinutes() == null)
{
dynamicEventForm.setTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
else
{
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
if (specimenId == null)
{
request.setAttribute(Constants.SPECIMEN_ID, specimenId);
}
}
String reasonDeviation = "";
reasonDeviation = dynamicEventForm.getReasonDeviation();
if (reasonDeviation == null)
{
reasonDeviation = "";
}
String currentEventParametersDate = "";
currentEventParametersDate = dynamicEventForm.getDateOfEvent();
if (currentEventParametersDate == null)
{
currentEventParametersDate = "";
}
final Integer dynamicEventParametersYear = new Integer(AppUtility
.getYear(currentEventParametersDate));
final Integer dynamicEventParametersMonth = new Integer(AppUtility
.getMonth(currentEventParametersDate));
final Integer dynamicEventParametersDay = new Integer(AppUtility
.getDay(currentEventParametersDate));
request.setAttribute("minutesList", Constants.MINUTES_ARRAY);
// Sets the hourList attribute to be used in the Add/Edit
// FrozenEventParameters Page.
request.setAttribute("hourList", Constants.HOUR_ARRAY);
request.setAttribute("dynamicEventParametersYear", dynamicEventParametersYear);
request.setAttribute("dynamicEventParametersDay", dynamicEventParametersDay);
request.setAttribute("dynamicEventParametersMonth", dynamicEventParametersMonth);
request.setAttribute("formName", Constants.DYNAMIC_EVENT_ACTION);
request.setAttribute("addForJSP", Constants.ADD);
request.setAttribute("editForJSP", Constants.EDIT);
request.setAttribute("reasonDeviation", reasonDeviation);
request.setAttribute("userListforJSP", Constants.USERLIST);
request.setAttribute("currentEventParametersDate", currentEventParametersDate);
request.setAttribute(Constants.PAGE_OF, "pageOfDynamicEvent");
request.setAttribute(Constants.SPECIMEN_ID, request.getSession().getAttribute(
Constants.SPECIMEN_ID));
//request.setAttribute(Constants.SPECIMEN_ID, request.getAttribute(Constants.SPECIMEN_ID));
//request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
//request.setAttribute("changeAction", Constants.CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION);
final String operation = request.getParameter(Constants.OPERATION);
final IFactory factory = AbstractFactoryConfig.getInstance().getBizLogicFactory();
final UserBizLogic userBizLogic = (UserBizLogic) factory
.getBizLogic(Constants.USER_FORM_ID);
final Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
HashMap dynamicEventMap = (HashMap) request.getSession().getAttribute("dynamicEventMap");
String iframeURL="";
long recordIdentifier=0;
Long eventId=null;
if(dynamicEventForm.getOperation().equals(Constants.ADD))
{
String eventName = request.getParameter("eventName");
if(eventName == null)
{
eventName = (String)request.getSession().getAttribute("eventName");
}
request.getSession().setAttribute("eventName", eventName);
dynamicEventForm.setEventName(eventName);
eventId=(Long) dynamicEventMap.get(eventName);
if (Boolean.parseBoolean(request.getParameter("showDefaultValues")))
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<Action> actionList = defaultBizLogic.retrieve(Action.class.getName(),
Constants.ID, request.getParameter("formContextId"));
if (actionList != null && !actionList.isEmpty())
{
Action action = (Action) actionList.get(0);
if (action.getApplicationDefaultValue() != null)
{
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(action
.getApplicationDefaultValue().getId(), action.getContainerId());
}
}
}
else
{
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
List<DefaultAction> actionList = defaultBizLogic.retrieve(DefaultAction.class
.getName(), Constants.CONTAINER_ID, eventId);
DefaultAction action =null;
if (actionList != null && !actionList.isEmpty())
{
action = (DefaultAction) actionList.get(0);
}
else
{
action=new DefaultAction();
action.setContainerId(eventId);
defaultBizLogic.insert(action);
}
request.setAttribute("formContextId",action.getId());
}
if(eventName != null)
{
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if(eventId != null)
{
request.getSession().setAttribute("OverrideCaption", "_" + eventId.toString());
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=insertParentData&useApplicationStylesheet=true&showInDiv=false&overrideCSS=true&overrideScroll=true"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ eventId.toString() + "&OverrideCaption=" + "_" + eventId.toString()+"&showCalculateDefaultValue=false";
if (recordIdentifier != 0)
{
iframeURL = iframeURL + "&recordIdentifier=" + recordIdentifier;
}
}
}
else
{
String actionApplicationId = request.getParameter("id");
if(actionApplicationId ==null)
{
actionApplicationId = (String) request.getAttribute("id");
}
if(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))
&& request.getSession().getAttribute("dynamicEventsForm") != null)
{
dynamicEventForm = (DynamicEventForm) request.getSession().getAttribute("dynamicEventsForm");
actionApplicationId = String.valueOf(dynamicEventForm.getId());
}
recordIdentifier = SpecimenEventsUtility.getRecordIdentifier(dynamicEventForm
.getRecordEntry(), dynamicEventForm.getContId());
Long containerId = dynamicEventForm.getContId();
IBizLogic defaultBizLogic = new CatissueDefaultBizLogic();
String specimenId = (String) request.getAttribute(Constants.SPECIMEN_ID);
boolean isDefaultAction = true;
if(specimenId!=null && !"".equals(specimenId))
{
List<Specimen> specimentList = defaultBizLogic.retrieve(
Specimen.class.getName(), Constants.ID, specimenId);
if (specimentList != null && !specimentList.isEmpty())
{
Specimen specimen = (Specimen) specimentList.get(0);
if(specimen.getProcessingSPPApplication() != null)
{
for(ActionApplication actionApplication : new SPPEventProcessor().getFilteredActionApplication(specimen.getProcessingSPPApplication().getSppActionApplicationCollection()))
{
if(actionApplication.getId().toString().equals(actionApplicationId))
{
for(Action action : specimen.getSpecimenRequirement().getProcessingSPP().getActionCollection())
{
if(action.getContainerId().equals(containerId))
{
request.setAttribute("formContextId", action.getId());
break;
}
}
isDefaultAction = false;
break;
}
}
}
}
}
if(isDefaultAction)
{
List<DefaultAction> actionList = defaultBizLogic.retrieve(
DefaultAction.class.getName(), Constants.CONTAINER_ID, dynamicEventForm
.getContId());
if (actionList != null && !actionList.isEmpty())
{
DefaultAction action = (DefaultAction) actionList.get(0);
request.setAttribute("formContextId", action.getId());
}
}
dynamicEventForm.setRecordIdentifier(recordIdentifier);
iframeURL = "/catissuecore/LoadDataEntryFormAction.do?dataEntryOperation=edit&useApplicationStylesheet=true&showInDiv=false"+(Boolean.parseBoolean(request.getParameter(Constants.CONTAINS_ERROR))?"&containerId=":"&containerIdentifier=")
+ dynamicEventForm.getContId()
+ "&recordIdentifier="
+ recordIdentifier
+ "&OverrideCaption=" + "_" + dynamicEventForm.getContId();
List contList = AppUtility
.executeSQLQuery("select caption from dyextn_container where identifier="
+ dynamicEventForm.getContId());
String eventName = (String) ((List) contList.get(0)).get(0);
request.setAttribute("formDisplayName", Utility.getFormattedString(eventName));
}
if (request.getSession().getAttribute("specimenId") == null)
{
request.getSession().setAttribute("specimenId", request.getParameter("specimenId"));
}
request.setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("recordIdentifier", recordIdentifier);
request.getSession().setAttribute("containerId", dynamicEventForm.getContId());
request.getSession().setAttribute("mandatory_Message", "false");
String formContxtId = getFormContextFromRequest(request);
if(!"".equals(iframeURL))
{
iframeURL = iframeURL + "&FormContextIdentifier=" + formContxtId;
}
populateStaticAttributes(request, dynamicEventForm);
request.setAttribute("iframeURL", iframeURL);
return mapping.findForward((String) request.getAttribute(Constants.PAGE_OF));
}
|
diff --git a/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java b/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java
index fa6366b2f..f9e44b77d 100644
--- a/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java
+++ b/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java
@@ -1,87 +1,89 @@
//
// Copyright (c) 2011 Linkeos.
//
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
// You should have received a copy of the GNU General Public License along
// with Elveos.org. If not, see http://www.gnu.org/licenses/.
//
package com.bloatit.model.managers;
import java.util.ArrayList;
import java.util.List;
import com.bloatit.data.DaoHighlightFeature;
import com.bloatit.data.queries.DBRequests;
import com.bloatit.framework.utils.PageIterable;
import com.bloatit.model.HighlightFeature;
import com.bloatit.model.lists.HighlightFeatureList;
/**
* The Class HighlightFeatureManager is an utility class containing static
* methods for {@link HighlightFeature} loading etc.
*/
public final class HighlightFeatureManager {
/**
* Desactivated constructor on utility class.
*/
private HighlightFeatureManager() {
// Desactivate default ctor
}
/**
* Gets a {@link HighlightFeature} by its id.
*
* @param id the id
* @return the {@link HighlightFeature} or null if not found.
*/
public static HighlightFeature getById(final Integer id) {
return HighlightFeature.create(DBRequests.getById(DaoHighlightFeature.class, id));
}
/**
* Gets the all th {@link HighlightFeature}s.
*
* @return the {@link HighlightFeature} features.
*/
public static PageIterable<HighlightFeature> getAll() {
return new HighlightFeatureList(DBRequests.getAll(DaoHighlightFeature.class));
}
public static List<HighlightFeature> getPositionArray(int featureCount) {
final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll();
final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount);
for(int i = 0; i< featureCount; i++) {
hightlightFeatureArray.add(null);
}
for (final HighlightFeature highlightFeature : hightlightFeatureList) {
if(!highlightFeature.isActive()) {
continue;
}
final int position = highlightFeature.getPosition() - 1;
if (position < featureCount) {
if (hightlightFeatureArray.get(position) == null) {
hightlightFeatureArray.set(position, highlightFeature);
} else {
- if (!hightlightFeatureArray.get(position).getActivationDate().after(highlightFeature.getActivationDate())) {
+ if (highlightFeature.getActivationDate().after(hightlightFeatureArray.get(position).getActivationDate())) {
+ hightlightFeatureArray.set(position, highlightFeature);
+ } else if (highlightFeature.getActivationDate().equals(hightlightFeatureArray.get(position).getActivationDate()) && highlightFeature.getId() > hightlightFeatureArray.get(position).getId()) {
hightlightFeatureArray.set(position, highlightFeature);
}
}
}
}
return hightlightFeatureArray;
}
}
| true | true | public static List<HighlightFeature> getPositionArray(int featureCount) {
final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll();
final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount);
for(int i = 0; i< featureCount; i++) {
hightlightFeatureArray.add(null);
}
for (final HighlightFeature highlightFeature : hightlightFeatureList) {
if(!highlightFeature.isActive()) {
continue;
}
final int position = highlightFeature.getPosition() - 1;
if (position < featureCount) {
if (hightlightFeatureArray.get(position) == null) {
hightlightFeatureArray.set(position, highlightFeature);
} else {
if (!hightlightFeatureArray.get(position).getActivationDate().after(highlightFeature.getActivationDate())) {
hightlightFeatureArray.set(position, highlightFeature);
}
}
}
}
return hightlightFeatureArray;
}
| public static List<HighlightFeature> getPositionArray(int featureCount) {
final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll();
final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount);
for(int i = 0; i< featureCount; i++) {
hightlightFeatureArray.add(null);
}
for (final HighlightFeature highlightFeature : hightlightFeatureList) {
if(!highlightFeature.isActive()) {
continue;
}
final int position = highlightFeature.getPosition() - 1;
if (position < featureCount) {
if (hightlightFeatureArray.get(position) == null) {
hightlightFeatureArray.set(position, highlightFeature);
} else {
if (highlightFeature.getActivationDate().after(hightlightFeatureArray.get(position).getActivationDate())) {
hightlightFeatureArray.set(position, highlightFeature);
} else if (highlightFeature.getActivationDate().equals(hightlightFeatureArray.get(position).getActivationDate()) && highlightFeature.getId() > hightlightFeatureArray.get(position).getId()) {
hightlightFeatureArray.set(position, highlightFeature);
}
}
}
}
return hightlightFeatureArray;
}
|
diff --git a/src/com/philiptorchinsky/TimeAppe/MainActivity.java b/src/com/philiptorchinsky/TimeAppe/MainActivity.java
index 3372192..6a20aec 100644
--- a/src/com/philiptorchinsky/TimeAppe/MainActivity.java
+++ b/src/com/philiptorchinsky/TimeAppe/MainActivity.java
@@ -1,93 +1,93 @@
package com.philiptorchinsky.TimeAppe;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ListActivity {
/**
* Called when the activity is first created.
*/
static public boolean isTest = false;
private DBAdapter dh;
private Adapter notes;
public ArrayList<Item> list = new ArrayList<Item>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
dh.insert("TeamCity training", "inactive", 0,0);
dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
- int i = 2;
+ int i = 1;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Item item = (Item) getListAdapter().getItem(position);
String project = item.getProject();
String status = item.getStatus();
long secondsSpent = item.getSecondsSpent();
long lastActivated = item.getLastactivated();
if (status.equalsIgnoreCase("active")) {
status = "inactive";
item.setStatus(status);
long spentThisTime = System.currentTimeMillis() - lastActivated;
item.setSecondsSpent(secondsSpent + spentThisTime);
list.set((int)id,item);
dh.updateSpentTimeByProject(project,status,secondsSpent + spentThisTime);
// Toast.makeText(this, project + " selected. Now " + (secondsSpent + spentThisTime)/1000.0, Toast.LENGTH_LONG).show();
}
else {
status = "active";
item.setStatus(status);
lastActivated = System.currentTimeMillis();
item.setLastactivated(lastActivated);
list.set((int)id,item);
dh.updateActivatedByProject(project,status,lastActivated);
}
notes.notifyDataSetChanged();
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
dh.insert("TeamCity training", "inactive", 0,0);
dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
int i = 2;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dh = new DBAdapter (this);
dh.open();
// dh.destroy();
// dh.close();
//
// dh = new DBAdapter (this);
dh.insert("TeamCity training", "inactive", 0,0);
dh.insert("Android Study", "inactive", 0,0);
// dh.insert("FreelancersFeed", "inactive",0,0);
// GET ROWS
Cursor c = dh.getAll();
int i = 1;
c.moveToFirst();
if (!c.isAfterLast()) {
do {
String project = c.getString(1);
String status = c.getString(2);
long secondsSpent = c.getLong(3);
long lastactivated = c.getLong(4);
Item newitem = new Item(project, status, secondsSpent, lastactivated);
list.add(newitem);
} while (c.moveToNext());
}
notes = new Adapter (this,list);
setContentView(R.layout.main);
setListAdapter(notes);
}
|
diff --git a/zssapp/test/SS_060_Test.java b/zssapp/test/SS_060_Test.java
index 6c3a9ca..7747b97 100644
--- a/zssapp/test/SS_060_Test.java
+++ b/zssapp/test/SS_060_Test.java
@@ -1,28 +1,28 @@
import org.zkoss.ztl.JQuery;
public class SS_060_Test extends SSAbstractTestCase {
@Override
protected void executeTest() {
JQuery cell_B_8 = getSpecifiedCell(1, 7);
clickCell(cell_B_8);
clickCell(cell_B_8);
- click(jq("i.z-combobox-rounded-btn:eq(0)"));
- JQuery fontItem = jq("td.z-comboitem-text:eq(3)");
+ click(jq("$fontCtrlPanel $fontFamily:visible i.z-combobox-rounded-btn"));
+ JQuery fontItem = jq(".z-combobox-rounded-pp .timeFont:visible");
if (fontItem != null) {
click(fontItem);
}
cell_B_8 = getSpecifiedCell(1, 7);
String style = cell_B_8.css("font-family");
if (style != null) {
verifyTrue("Unexcepted result: " + style, "Times New Roman".equalsIgnoreCase(style));
} else {
verifyTrue("Cannot get style of specified cell!", false);
}
}
}
| true | true | protected void executeTest() {
JQuery cell_B_8 = getSpecifiedCell(1, 7);
clickCell(cell_B_8);
clickCell(cell_B_8);
click(jq("i.z-combobox-rounded-btn:eq(0)"));
JQuery fontItem = jq("td.z-comboitem-text:eq(3)");
if (fontItem != null) {
click(fontItem);
}
cell_B_8 = getSpecifiedCell(1, 7);
String style = cell_B_8.css("font-family");
if (style != null) {
verifyTrue("Unexcepted result: " + style, "Times New Roman".equalsIgnoreCase(style));
} else {
verifyTrue("Cannot get style of specified cell!", false);
}
}
| protected void executeTest() {
JQuery cell_B_8 = getSpecifiedCell(1, 7);
clickCell(cell_B_8);
clickCell(cell_B_8);
click(jq("$fontCtrlPanel $fontFamily:visible i.z-combobox-rounded-btn"));
JQuery fontItem = jq(".z-combobox-rounded-pp .timeFont:visible");
if (fontItem != null) {
click(fontItem);
}
cell_B_8 = getSpecifiedCell(1, 7);
String style = cell_B_8.css("font-family");
if (style != null) {
verifyTrue("Unexcepted result: " + style, "Times New Roman".equalsIgnoreCase(style));
} else {
verifyTrue("Cannot get style of specified cell!", false);
}
}
|
diff --git a/clients/java/src/test/java/com/thoughtworks/selenium/ApacheMyFacesSuggestTest.java b/clients/java/src/test/java/com/thoughtworks/selenium/ApacheMyFacesSuggestTest.java
index 2508257b..0c1dd1e9 100644
--- a/clients/java/src/test/java/com/thoughtworks/selenium/ApacheMyFacesSuggestTest.java
+++ b/clients/java/src/test/java/com/thoughtworks/selenium/ApacheMyFacesSuggestTest.java
@@ -1,70 +1,58 @@
package com.thoughtworks.selenium;
import junit.framework.*;
import org.openqa.selenium.server.*;
import org.openqa.selenium.server.browserlaunchers.*;
/**
* A test of the Apache MyFaces JSF AJAX auto-suggest sandbox application at www.irian.at.
*
*
* @author danielf
*
*/
public class ApacheMyFacesSuggestTest extends TestCase {
DefaultSelenium selenium;
protected void setUp() throws Exception {
}
public void testAJAXFirefox() throws Throwable {
selenium = new DefaultSelenium("localhost", SeleniumServer.DEFAULT_PORT, "*firefox", "http://www.irian.at");
selenium.start();
ajaxTester();
}
public void testAJAXIExplore() throws Throwable {
if (!WindowsUtils.thisIsWindows()) return;
selenium = new DefaultSelenium("localhost", SeleniumServer.DEFAULT_PORT, "*iexplore", "http://www.irian.at");
selenium.start();
ajaxTester();
}
public void ajaxTester() throws Throwable {
selenium.open("http://www.irian.at/myfaces-sandbox/inputSuggestAjax.jsf");
selenium.assertTextPresent("suggest");
String elementID = "_idJsp0:_idJsp3";
selenium.type(elementID, "foo");
// DGF On Mozilla a keyPress is needed, and types a letter.
// On IE6, a keyDown is needed, and no letter is typed. :-p
- // NS On firefox, keyPress needed, no letter typed.
+ // On firefox 1.0.6-1.5.0.1, keyPress needed, no letter typed;
+ // On firefox 1.5.0.2 (and higher), keyPress needed, letter typed
+ // That's due to Firefox bug 303713 https://bugzilla.mozilla.org/show_bug.cgi?id=303713
- boolean isIE = "true".equals(selenium.getEval("isIE"));
- boolean isFirefox = "true".equals(selenium.getEval("isFirefox"));
- boolean isNetscape = "true".equals(selenium.getEval("isNetscape"));
- String verificationText = null;
- if (isIE) {
- selenium.keyDown(elementID, Integer.toString('x'));
- } else {
- selenium.keyPress(elementID, Integer.toString('x'));
- }
- if (isNetscape) {
- verificationText = "foox1";
- } else if (isIE || isFirefox) {
- verificationText = "foo1";
- }
- else {
- fail("which browser is this?");
- }
+ String verificationText = "regexp:foox?1";
+ selenium.keyDown(elementID, Integer.toString('x'));
+ selenium.keyPress(elementID, Integer.toString('x'));
Thread.sleep(2000);
selenium.assertTextPresent(verificationText);
}
public void tearDown() {
if (selenium == null) return;
selenium.stop();
}
}
| false | true | public void ajaxTester() throws Throwable {
selenium.open("http://www.irian.at/myfaces-sandbox/inputSuggestAjax.jsf");
selenium.assertTextPresent("suggest");
String elementID = "_idJsp0:_idJsp3";
selenium.type(elementID, "foo");
// DGF On Mozilla a keyPress is needed, and types a letter.
// On IE6, a keyDown is needed, and no letter is typed. :-p
// NS On firefox, keyPress needed, no letter typed.
boolean isIE = "true".equals(selenium.getEval("isIE"));
boolean isFirefox = "true".equals(selenium.getEval("isFirefox"));
boolean isNetscape = "true".equals(selenium.getEval("isNetscape"));
String verificationText = null;
if (isIE) {
selenium.keyDown(elementID, Integer.toString('x'));
} else {
selenium.keyPress(elementID, Integer.toString('x'));
}
if (isNetscape) {
verificationText = "foox1";
} else if (isIE || isFirefox) {
verificationText = "foo1";
}
else {
fail("which browser is this?");
}
Thread.sleep(2000);
selenium.assertTextPresent(verificationText);
}
| public void ajaxTester() throws Throwable {
selenium.open("http://www.irian.at/myfaces-sandbox/inputSuggestAjax.jsf");
selenium.assertTextPresent("suggest");
String elementID = "_idJsp0:_idJsp3";
selenium.type(elementID, "foo");
// DGF On Mozilla a keyPress is needed, and types a letter.
// On IE6, a keyDown is needed, and no letter is typed. :-p
// On firefox 1.0.6-1.5.0.1, keyPress needed, no letter typed;
// On firefox 1.5.0.2 (and higher), keyPress needed, letter typed
// That's due to Firefox bug 303713 https://bugzilla.mozilla.org/show_bug.cgi?id=303713
String verificationText = "regexp:foox?1";
selenium.keyDown(elementID, Integer.toString('x'));
selenium.keyPress(elementID, Integer.toString('x'));
Thread.sleep(2000);
selenium.assertTextPresent(verificationText);
}
|
diff --git a/src/com/battlespace/main/OptimizerRunner.java b/src/com/battlespace/main/OptimizerRunner.java
index d9de9eb..4c7a18a 100644
--- a/src/com/battlespace/main/OptimizerRunner.java
+++ b/src/com/battlespace/main/OptimizerRunner.java
@@ -1,204 +1,204 @@
package com.battlespace.main;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.battlespace.domain.BasePlayerShipFactory;
import com.battlespace.domain.BoostedPlayerShipFactory;
import com.battlespace.domain.Booster;
import com.battlespace.domain.CommanderPower;
import com.battlespace.domain.EnemyShipDatabase;
import com.battlespace.domain.FileData;
import com.battlespace.domain.OptimizerRecord;
import com.battlespace.domain.OptimizerSettings;
import com.battlespace.domain.PlanetData;
import com.battlespace.domain.PlayerShip;
import com.battlespace.domain.SimulatorCollator;
import com.battlespace.domain.SimulatorContext;
import com.battlespace.domain.SimulatorParameters;
import com.battlespace.domain.SimulatorResults;
import com.battlespace.domain.optimizers.FitnessFunction;
import com.battlespace.service.CommanderPowerService;
import com.battlespace.service.DataLoaderService;
import com.battlespace.service.FormationService;
import com.battlespace.service.ObjectCreator;
import com.battlespace.service.Optimizer;
import com.battlespace.service.PlanetService;
import com.battlespace.service.PlayerShipDatabase;
import com.battlespace.service.PlayerSkillModifier;
import com.battlespace.service.RandomRoller;
import com.battlespace.service.Simulator;
import com.battlespace.strategy.AttackStrategy;
public class OptimizerRunner
{
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
FileData config = DataLoaderService.loadFile("conf/settings.txt");
// parameters
// param 1 is player formation,(commander),(luck),(skill)
//System.out.println(args[0]);
String[] playerArgs = args[0].split(",");
String playerFormation = playerArgs[0];
int commanderSkill = 0;
if(playerArgs.length > 1)
{
commanderSkill = Integer.valueOf(playerArgs[1]);
}
double commanderBoost = commanderSkill/Double.valueOf(config.get("skill_factor"));
int commanderLuck = 0;
if(playerArgs.length > 2)
{
commanderLuck = Integer.valueOf(playerArgs[2]);
}
double commanderCritical = commanderLuck/Double.valueOf(config.get("luck_factor"));
CommanderPower commanderPower = null;
if(playerArgs.length>3)
{
commanderPower = CommanderPowerService.get(playerArgs[3]);
}
// param 2 is enemy selection
// (planet)
// (planet level),(config)
// (formation),(ship,ship,ship...)
// i,(formation),(ship,ship,ship....)
boolean interception = false;
String[] enemyArgs = args[1].split(",");
String enemyFormation = null;
String enemyShips = null;
if(enemyArgs.length==1)
{
PlanetData pd = PlanetService.lookup(enemyArgs[0]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
}
else if(enemyArgs.length==2)
{
PlanetData pd = PlanetService.lookupByLayout(Integer.valueOf(enemyArgs[0]), enemyArgs[1]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
System.out.println("Planet code is " + pd.code);
}
else
{
int base = 0;
- if(args[0].startsWith("i"))
+ if(enemyArgs[0].startsWith("i"))
{
base++;
interception = true;
}
// formation, ship, ship, ship....
enemyFormation = enemyArgs[base];
StringBuffer sb = new StringBuffer();
for(int i=base+1;i<enemyArgs.length;i++)
{
if(i!=base+1) sb.append(",");
sb.append(enemyArgs[i]);
}
enemyShips = sb.toString();
}
String fitness="victory";
if(args.length==3)
{
fitness = args[2];
}
// init
AttackStrategy attackStrategy = (AttackStrategy)ObjectCreator.createObjectFromConfig("com.battlespace.strategy", config, "attackStrategy");
EnemyShipDatabase esd = EnemyShipDatabase.load();
OptimizerSettings settings = new OptimizerSettings();
List<String> availableShips = new LinkedList<String>();
FileData playerData = DataLoaderService.loadFile("conf/player_data.txt");
BoostedPlayerShipFactory bpsf = new BoostedPlayerShipFactory();
int militarySkill = playerData.getInt("military.skill", 0);
int unionArmor = playerData.getInt("union.armor", 0);
Set<String> keys = playerData.getKeys();
for(String key : keys)
{
// will eventually have to check for valid ship keys
if(!key.contains(".")) // all others contain a dot
{
// perfom boost calculations on this ship
PlayerShip psi = PlayerShipDatabase.lookup(key);
// get the ug as an array of int
int[] ug = new int[4];
String ugString = playerData.get(key);
for(int i=0;i<4;i++)
{
ug[i] = ugString.codePointAt(i) - '0';
}
psi = psi.applyUpgrades( ug, false); // allow sim to run even with missing files
Booster booster = new Booster(psi.size);
PlayerSkillModifier.upgrade(booster, militarySkill);
if(commanderPower!=null)
{
commanderPower.upgrade(booster);
}
booster.skillUpgrade(commanderBoost);
booster.add(new double[]{0,0,0, 0,0,0, 0,0, unionArmor*2.0,0, 0});
psi = psi.applyBooster(booster);
bpsf.register(key, psi);
// and add it to the list of ships the GA can use
availableShips.add(key);
}
}
settings.availableShips = availableShips;
settings.population = config.getInt("optimizer.population",0);
settings.mutations = config.getInt("optimizer.mutations",0);
settings.crossovers = config.getInt("optimizer.crossovers",0);
settings.iterations = config.getInt("optimizer.iterations",0);
settings.fitness = (FitnessFunction)ObjectCreator.createObjectFromConfig("com.battlespace.domain.optimizers", config, "optmode."+fitness);
settings.crossoverAttempts = config.getInt("optimizer.crossoverAttempts", 0);
settings.report = config.getInt("optimizer.report", 0);
settings.crossoverPopulation = config.getInt("optimizer.crossoverPopulation", 0);
settings.mutationPopulation = config.getInt("optimizer.mutationPopulation", 0);
settings.simulations = config.getInt("optimizer.simulations", 0);
// simple test of the simulator runner
SimulatorContext context = new SimulatorContext();
context.rng = new RandomRoller();
context.attackStrategy = attackStrategy;
context.playerFactory = new BasePlayerShipFactory(); // no upgrades, commander power etc
context.enemyFactory = esd;
context.playerCritChance = commanderCritical;
context.playerCritDamage = Double.valueOf(config.get("critical_multiplier"));
context.interception = interception;
if(commanderPower != null)
{
context.playerCritChance *= commanderPower.criticalMultiplier();
}
context.enemyCritChance = Double.valueOf(config.get("enemy_critical_percent"));
context.enemyCritDamage = Double.valueOf(config.get("critical_multiplier"));
SimulatorParameters params = new SimulatorParameters();
params.playerFormation = FormationService.get(playerFormation);
//params.playerShips = Arrays.asList(playerShips.split(","));
params.enemyFormation = FormationService.get(enemyFormation);
params.enemyShips = Arrays.asList(enemyShips.split(","));
OptimizerRecord out = Optimizer.optimize(context, params, settings);
System.out.println(out);
}
}
| true | true | public static void main(String[] args) throws Exception
{
FileData config = DataLoaderService.loadFile("conf/settings.txt");
// parameters
// param 1 is player formation,(commander),(luck),(skill)
//System.out.println(args[0]);
String[] playerArgs = args[0].split(",");
String playerFormation = playerArgs[0];
int commanderSkill = 0;
if(playerArgs.length > 1)
{
commanderSkill = Integer.valueOf(playerArgs[1]);
}
double commanderBoost = commanderSkill/Double.valueOf(config.get("skill_factor"));
int commanderLuck = 0;
if(playerArgs.length > 2)
{
commanderLuck = Integer.valueOf(playerArgs[2]);
}
double commanderCritical = commanderLuck/Double.valueOf(config.get("luck_factor"));
CommanderPower commanderPower = null;
if(playerArgs.length>3)
{
commanderPower = CommanderPowerService.get(playerArgs[3]);
}
// param 2 is enemy selection
// (planet)
// (planet level),(config)
// (formation),(ship,ship,ship...)
// i,(formation),(ship,ship,ship....)
boolean interception = false;
String[] enemyArgs = args[1].split(",");
String enemyFormation = null;
String enemyShips = null;
if(enemyArgs.length==1)
{
PlanetData pd = PlanetService.lookup(enemyArgs[0]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
}
else if(enemyArgs.length==2)
{
PlanetData pd = PlanetService.lookupByLayout(Integer.valueOf(enemyArgs[0]), enemyArgs[1]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
System.out.println("Planet code is " + pd.code);
}
else
{
int base = 0;
if(args[0].startsWith("i"))
{
base++;
interception = true;
}
// formation, ship, ship, ship....
enemyFormation = enemyArgs[base];
StringBuffer sb = new StringBuffer();
for(int i=base+1;i<enemyArgs.length;i++)
{
if(i!=base+1) sb.append(",");
sb.append(enemyArgs[i]);
}
enemyShips = sb.toString();
}
String fitness="victory";
if(args.length==3)
{
fitness = args[2];
}
// init
AttackStrategy attackStrategy = (AttackStrategy)ObjectCreator.createObjectFromConfig("com.battlespace.strategy", config, "attackStrategy");
EnemyShipDatabase esd = EnemyShipDatabase.load();
OptimizerSettings settings = new OptimizerSettings();
List<String> availableShips = new LinkedList<String>();
FileData playerData = DataLoaderService.loadFile("conf/player_data.txt");
BoostedPlayerShipFactory bpsf = new BoostedPlayerShipFactory();
int militarySkill = playerData.getInt("military.skill", 0);
int unionArmor = playerData.getInt("union.armor", 0);
Set<String> keys = playerData.getKeys();
for(String key : keys)
{
// will eventually have to check for valid ship keys
if(!key.contains(".")) // all others contain a dot
{
// perfom boost calculations on this ship
PlayerShip psi = PlayerShipDatabase.lookup(key);
// get the ug as an array of int
int[] ug = new int[4];
String ugString = playerData.get(key);
for(int i=0;i<4;i++)
{
ug[i] = ugString.codePointAt(i) - '0';
}
psi = psi.applyUpgrades( ug, false); // allow sim to run even with missing files
Booster booster = new Booster(psi.size);
PlayerSkillModifier.upgrade(booster, militarySkill);
if(commanderPower!=null)
{
commanderPower.upgrade(booster);
}
booster.skillUpgrade(commanderBoost);
booster.add(new double[]{0,0,0, 0,0,0, 0,0, unionArmor*2.0,0, 0});
psi = psi.applyBooster(booster);
bpsf.register(key, psi);
// and add it to the list of ships the GA can use
availableShips.add(key);
}
}
settings.availableShips = availableShips;
settings.population = config.getInt("optimizer.population",0);
settings.mutations = config.getInt("optimizer.mutations",0);
settings.crossovers = config.getInt("optimizer.crossovers",0);
settings.iterations = config.getInt("optimizer.iterations",0);
settings.fitness = (FitnessFunction)ObjectCreator.createObjectFromConfig("com.battlespace.domain.optimizers", config, "optmode."+fitness);
settings.crossoverAttempts = config.getInt("optimizer.crossoverAttempts", 0);
settings.report = config.getInt("optimizer.report", 0);
settings.crossoverPopulation = config.getInt("optimizer.crossoverPopulation", 0);
settings.mutationPopulation = config.getInt("optimizer.mutationPopulation", 0);
settings.simulations = config.getInt("optimizer.simulations", 0);
// simple test of the simulator runner
SimulatorContext context = new SimulatorContext();
context.rng = new RandomRoller();
context.attackStrategy = attackStrategy;
context.playerFactory = new BasePlayerShipFactory(); // no upgrades, commander power etc
context.enemyFactory = esd;
context.playerCritChance = commanderCritical;
context.playerCritDamage = Double.valueOf(config.get("critical_multiplier"));
context.interception = interception;
if(commanderPower != null)
{
context.playerCritChance *= commanderPower.criticalMultiplier();
}
context.enemyCritChance = Double.valueOf(config.get("enemy_critical_percent"));
context.enemyCritDamage = Double.valueOf(config.get("critical_multiplier"));
SimulatorParameters params = new SimulatorParameters();
params.playerFormation = FormationService.get(playerFormation);
//params.playerShips = Arrays.asList(playerShips.split(","));
params.enemyFormation = FormationService.get(enemyFormation);
params.enemyShips = Arrays.asList(enemyShips.split(","));
OptimizerRecord out = Optimizer.optimize(context, params, settings);
System.out.println(out);
}
| public static void main(String[] args) throws Exception
{
FileData config = DataLoaderService.loadFile("conf/settings.txt");
// parameters
// param 1 is player formation,(commander),(luck),(skill)
//System.out.println(args[0]);
String[] playerArgs = args[0].split(",");
String playerFormation = playerArgs[0];
int commanderSkill = 0;
if(playerArgs.length > 1)
{
commanderSkill = Integer.valueOf(playerArgs[1]);
}
double commanderBoost = commanderSkill/Double.valueOf(config.get("skill_factor"));
int commanderLuck = 0;
if(playerArgs.length > 2)
{
commanderLuck = Integer.valueOf(playerArgs[2]);
}
double commanderCritical = commanderLuck/Double.valueOf(config.get("luck_factor"));
CommanderPower commanderPower = null;
if(playerArgs.length>3)
{
commanderPower = CommanderPowerService.get(playerArgs[3]);
}
// param 2 is enemy selection
// (planet)
// (planet level),(config)
// (formation),(ship,ship,ship...)
// i,(formation),(ship,ship,ship....)
boolean interception = false;
String[] enemyArgs = args[1].split(",");
String enemyFormation = null;
String enemyShips = null;
if(enemyArgs.length==1)
{
PlanetData pd = PlanetService.lookup(enemyArgs[0]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
}
else if(enemyArgs.length==2)
{
PlanetData pd = PlanetService.lookupByLayout(Integer.valueOf(enemyArgs[0]), enemyArgs[1]);
enemyFormation = pd.formation;
enemyShips = pd.enemies;
System.out.println("Planet code is " + pd.code);
}
else
{
int base = 0;
if(enemyArgs[0].startsWith("i"))
{
base++;
interception = true;
}
// formation, ship, ship, ship....
enemyFormation = enemyArgs[base];
StringBuffer sb = new StringBuffer();
for(int i=base+1;i<enemyArgs.length;i++)
{
if(i!=base+1) sb.append(",");
sb.append(enemyArgs[i]);
}
enemyShips = sb.toString();
}
String fitness="victory";
if(args.length==3)
{
fitness = args[2];
}
// init
AttackStrategy attackStrategy = (AttackStrategy)ObjectCreator.createObjectFromConfig("com.battlespace.strategy", config, "attackStrategy");
EnemyShipDatabase esd = EnemyShipDatabase.load();
OptimizerSettings settings = new OptimizerSettings();
List<String> availableShips = new LinkedList<String>();
FileData playerData = DataLoaderService.loadFile("conf/player_data.txt");
BoostedPlayerShipFactory bpsf = new BoostedPlayerShipFactory();
int militarySkill = playerData.getInt("military.skill", 0);
int unionArmor = playerData.getInt("union.armor", 0);
Set<String> keys = playerData.getKeys();
for(String key : keys)
{
// will eventually have to check for valid ship keys
if(!key.contains(".")) // all others contain a dot
{
// perfom boost calculations on this ship
PlayerShip psi = PlayerShipDatabase.lookup(key);
// get the ug as an array of int
int[] ug = new int[4];
String ugString = playerData.get(key);
for(int i=0;i<4;i++)
{
ug[i] = ugString.codePointAt(i) - '0';
}
psi = psi.applyUpgrades( ug, false); // allow sim to run even with missing files
Booster booster = new Booster(psi.size);
PlayerSkillModifier.upgrade(booster, militarySkill);
if(commanderPower!=null)
{
commanderPower.upgrade(booster);
}
booster.skillUpgrade(commanderBoost);
booster.add(new double[]{0,0,0, 0,0,0, 0,0, unionArmor*2.0,0, 0});
psi = psi.applyBooster(booster);
bpsf.register(key, psi);
// and add it to the list of ships the GA can use
availableShips.add(key);
}
}
settings.availableShips = availableShips;
settings.population = config.getInt("optimizer.population",0);
settings.mutations = config.getInt("optimizer.mutations",0);
settings.crossovers = config.getInt("optimizer.crossovers",0);
settings.iterations = config.getInt("optimizer.iterations",0);
settings.fitness = (FitnessFunction)ObjectCreator.createObjectFromConfig("com.battlespace.domain.optimizers", config, "optmode."+fitness);
settings.crossoverAttempts = config.getInt("optimizer.crossoverAttempts", 0);
settings.report = config.getInt("optimizer.report", 0);
settings.crossoverPopulation = config.getInt("optimizer.crossoverPopulation", 0);
settings.mutationPopulation = config.getInt("optimizer.mutationPopulation", 0);
settings.simulations = config.getInt("optimizer.simulations", 0);
// simple test of the simulator runner
SimulatorContext context = new SimulatorContext();
context.rng = new RandomRoller();
context.attackStrategy = attackStrategy;
context.playerFactory = new BasePlayerShipFactory(); // no upgrades, commander power etc
context.enemyFactory = esd;
context.playerCritChance = commanderCritical;
context.playerCritDamage = Double.valueOf(config.get("critical_multiplier"));
context.interception = interception;
if(commanderPower != null)
{
context.playerCritChance *= commanderPower.criticalMultiplier();
}
context.enemyCritChance = Double.valueOf(config.get("enemy_critical_percent"));
context.enemyCritDamage = Double.valueOf(config.get("critical_multiplier"));
SimulatorParameters params = new SimulatorParameters();
params.playerFormation = FormationService.get(playerFormation);
//params.playerShips = Arrays.asList(playerShips.split(","));
params.enemyFormation = FormationService.get(enemyFormation);
params.enemyShips = Arrays.asList(enemyShips.split(","));
OptimizerRecord out = Optimizer.optimize(context, params, settings);
System.out.println(out);
}
|
diff --git a/sikuli-ide/src/main/java/org/sikuli/ide/ImageButton.java b/sikuli-ide/src/main/java/org/sikuli/ide/ImageButton.java
index d9085d49..2d203e9f 100644
--- a/sikuli-ide/src/main/java/org/sikuli/ide/ImageButton.java
+++ b/sikuli-ide/src/main/java/org/sikuli/ide/ImageButton.java
@@ -1,310 +1,313 @@
/*
* Copyright 2010-2011, Sikuli.org
* Released under the MIT License.
*
*/
package org.sikuli.ide;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.util.Locale;
import javax.swing.*;
import javax.swing.text.*;
import javax.imageio.*;
import org.sikuli.script.Location;
import org.sikuli.script.Debug;
class ImageButton extends JButton implements ActionListener, Serializable /*, MouseListener*/ {
static final int DEFAULT_NUM_MATCHES = 10;
static final float DEFAULT_SIMILARITY = 0.7f;
private String _imgFilename, _thumbFname;
private SikuliPane _pane;
private float _similarity;
private int _numMatches = DEFAULT_NUM_MATCHES;
private boolean _exact;
private Location _offset;
private int _imgW, _imgH;
private float _scale = 1f;
private PatternWindow pwin = null;
/*
public void mousePressed(java.awt.event.MouseEvent e) {}
public void mouseReleased(java.awt.event.MouseEvent e) {}
public void mouseClicked(java.awt.event.MouseEvent e) {}
public void mouseEntered(java.awt.event.MouseEvent e) {
}
public void mouseExited(java.awt.event.MouseEvent e) {
}
*/
public String getFilename(){
File img = new File(_imgFilename);
String oldBundle = img.getParent();
String newBundle = _pane.getSrcBundle();
Debug.log("ImageButton.getFilename: " + oldBundle + " " + newBundle);
if(oldBundle == newBundle)
return _imgFilename;
setFilename(newBundle + File.separatorChar + img.getName());
return _imgFilename;
}
public void setFilename(String newFilename){
_imgFilename = newFilename;
_thumbFname = createThumbnail(_imgFilename);
setIcon(new ImageIcon(_thumbFname));
setToolTipText( this.toString() );
}
public void setTargetOffset(Location offset){
Debug.log("setTargetOffset: " + offset);
_offset = offset;
setToolTipText( this.toString() );
}
public void setParameters(boolean exact, float similarity, int numMatches){
Debug.log(3, "setParameters: " + exact + "," + similarity + "," + numMatches);
_exact = exact;
if(similarity>=0) _similarity = similarity;
setToolTipText( this.toString() );
}
public BufferedImage createThumbnailImage(int maxHeight){
return createThumbnailImage(_imgFilename, maxHeight);
}
private BufferedImage createThumbnailImage(String imgFname, int maxHeight){
try{
BufferedImage img = ImageIO.read(new File(imgFname));
int w = img.getWidth(null), h = img.getHeight(null);
_imgW = w;
_imgH = h;
if(maxHeight >= h)
return img;
_scale = (float)maxHeight/h;
w *= _scale;
h *= _scale;
BufferedImage thumb = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = thumb.createGraphics();
g2d.drawImage(img, 0, 0, w, h, null);
g2d.dispose();
return thumb;
}
catch(IOException e){
Debug.error("Can't read file: " + e.getMessage());
return null;
}
}
private String createThumbnail(String imgFname, int maxHeight){
BufferedImage thumb = createThumbnailImage(imgFname, maxHeight);
return Utils.saveTmpImage(thumb);
}
private String createThumbnail(String imgFname){
final int max_h = UserPreferences.getInstance().getDefaultThumbHeight();
return createThumbnail(imgFname, max_h);
}
protected void init(SikuliPane pane){
_pane = pane;
_exact = false;
_similarity = DEFAULT_SIMILARITY;
_numMatches = DEFAULT_NUM_MATCHES;
setBorderPainted(true);
setCursor(new Cursor (Cursor.HAND_CURSOR));
addActionListener(this);
//addMouseListener(this);
setToolTipText( this.toString() );
}
protected ImageButton(SikuliPane pane){
init(pane);
}
public ImageButton(SikuliPane pane, String imgFilename){
init(pane);
setFilename(imgFilename);
}
private boolean useThumbnail(){
return !_imgFilename.equals(_thumbFname);
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
drawText(g2d);
if( useThumbnail() ){
g2d.setColor( new Color(0, 128, 128, 128) );
g2d.drawRoundRect(3, 3, getWidth()-7, getHeight()-7, 5, 5);
}
}
private static Font textFont = new Font("arial", Font.BOLD, 12);
private void drawText(Graphics2D g2d){
String strSim=null, strOffset=null;
if( _similarity != DEFAULT_SIMILARITY){
if(_similarity==1)
strSim = "1.0";
else{
strSim = String.format("%.2f", _similarity);
if(strSim.charAt(0) == '0')
strSim = strSim.substring(1);
}
}
if(_offset != null && (_offset.x!=0 || _offset.y !=0)){
strOffset = _offset.toString();
}
if(strOffset == null && strSim == null)
return;
final int fontH = g2d.getFontMetrics().getMaxAscent();
final int x = getWidth(), y = 0;
drawText(g2d, strSim, x, y);
if(_offset!=null)
drawCross(g2d);
}
private void drawCross(Graphics2D g2d){
int x,y;
final String cross = "+";
final int w = g2d.getFontMetrics().stringWidth(cross);
final int h = g2d.getFontMetrics().getMaxAscent();
if(_offset.x>_imgW/2) x = getWidth()-w;
else if(_offset.x<-_imgW/2) x = 0;
else x= (int)(getWidth()/2 + _offset.x * _scale - w/2 );
if(_offset.y>_imgH/2) y = getHeight()+h/2-3;
else if(_offset.y<-_imgH/2) y = h/2+2;
else y= (int)(getHeight()/2 + _offset.y * _scale + h/2);
g2d.setFont( textFont );
g2d.setColor( new Color(0, 0, 0, 180) );
g2d.drawString(cross, x+1, y+1);
g2d.setColor( new Color(255, 0, 0, 180) );
g2d.drawString(cross, x, y);
}
private void drawText(Graphics2D g2d, String str, int x, int y){
if(str==null)
return;
final int w = g2d.getFontMetrics().stringWidth(str);
final int fontH = g2d.getFontMetrics().getMaxAscent();
final int borderW = 2;
g2d.setFont( textFont );
g2d.setColor( new Color(0, 128, 0, 128) );
g2d.fillRoundRect(x-borderW*2-w, y, w+borderW*2, fontH+borderW*2, 3, 3);
g2d.setColor( Color.white );
g2d.drawString(str, x-w-3, y+fontH+1);
}
public void actionPerformed(ActionEvent e) {
Debug.log("open Pattern Settings");
pwin = new PatternWindow(this, _exact, _similarity, _numMatches);
pwin.setTargetOffset(_offset);
}
public Location getTargetOffset(){
return _offset;
}
public void setExact(boolean exact){
_exact = exact;
}
public void setSimilarity(float val){
if(val<0)
_similarity = 0;
else if(val>1)
_similarity = 1;
else
_similarity = val;
}
public static ImageButton createFromString(SikuliPane parentPane, String str){
if( !str.startsWith("Pattern") ){
if(str.charAt(0) == '\"' && str.charAt(str.length()-1) == '\"'){
String filename = str.substring(1, str.length()-1);
File f = parentPane.getFileInBundle(filename);
return new ImageButton(parentPane, f.getAbsolutePath());
}
return null;
}
ImageButton btn = new ImageButton(parentPane);
String[] tokens = str.split("\\)\\s*\\.?");
for(String tok : tokens){
//System.out.println("token: " + tok);
- if( tok.startsWith("exact") )
+ if( tok.startsWith("exact") ){
btn.setExact(true);
+ btn.setSimilarity(1.f);
+ }
else if( tok.startsWith("Pattern") ){
String filename = tok.substring(
tok.indexOf("\"")+1,tok.lastIndexOf("\""));
File f = parentPane.getFileInBundle(filename);
if( f != null && f.exists() ){
btn.setFilename(f.getAbsolutePath());
}
else
return null;
}
else if( tok.startsWith("similar") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
try{
btn.setSimilarity(Float.valueOf(strArg));
}
catch(NumberFormatException e){
return null;
}
}
else if( tok.startsWith("firstN") ){ // FIXME: replace with limit/max
String strArg = tok.substring(tok.lastIndexOf("(")+1);
btn._numMatches = Integer.valueOf(strArg);
}
else if( tok.startsWith("targetOffset") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
String[] args = strArg.split(",");
try{
Location offset = new Location(0,0);
offset.x = Integer.valueOf(args[0]);
offset.y = Integer.valueOf(args[1]);
btn.setTargetOffset(offset);
}
catch(NumberFormatException e){
return null;
}
}
}
+ btn.setToolTipText( btn.toString() );
return btn;
}
public String toString(){
if(_imgFilename == null)
return "null";
String img = new File(_imgFilename).getName();
String pat = "Pattern(\"" + img + "\")";
String ret = "";
if(_exact)
ret += ".exact()";
if(_similarity != DEFAULT_SIMILARITY && !_exact)
ret += String.format(Locale.ENGLISH, ".similar(%.2f)", _similarity);
if(_offset != null && (_offset.x!=0 || _offset.y!=0))
ret += ".targetOffset(" + _offset.x + "," + _offset.y +")";
if(!ret.equals(""))
ret = pat + ret;
else
ret = "\"" + img + "\"";
return ret;
}
}
| false | true | public static ImageButton createFromString(SikuliPane parentPane, String str){
if( !str.startsWith("Pattern") ){
if(str.charAt(0) == '\"' && str.charAt(str.length()-1) == '\"'){
String filename = str.substring(1, str.length()-1);
File f = parentPane.getFileInBundle(filename);
return new ImageButton(parentPane, f.getAbsolutePath());
}
return null;
}
ImageButton btn = new ImageButton(parentPane);
String[] tokens = str.split("\\)\\s*\\.?");
for(String tok : tokens){
//System.out.println("token: " + tok);
if( tok.startsWith("exact") )
btn.setExact(true);
else if( tok.startsWith("Pattern") ){
String filename = tok.substring(
tok.indexOf("\"")+1,tok.lastIndexOf("\""));
File f = parentPane.getFileInBundle(filename);
if( f != null && f.exists() ){
btn.setFilename(f.getAbsolutePath());
}
else
return null;
}
else if( tok.startsWith("similar") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
try{
btn.setSimilarity(Float.valueOf(strArg));
}
catch(NumberFormatException e){
return null;
}
}
else if( tok.startsWith("firstN") ){ // FIXME: replace with limit/max
String strArg = tok.substring(tok.lastIndexOf("(")+1);
btn._numMatches = Integer.valueOf(strArg);
}
else if( tok.startsWith("targetOffset") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
String[] args = strArg.split(",");
try{
Location offset = new Location(0,0);
offset.x = Integer.valueOf(args[0]);
offset.y = Integer.valueOf(args[1]);
btn.setTargetOffset(offset);
}
catch(NumberFormatException e){
return null;
}
}
}
return btn;
}
| public static ImageButton createFromString(SikuliPane parentPane, String str){
if( !str.startsWith("Pattern") ){
if(str.charAt(0) == '\"' && str.charAt(str.length()-1) == '\"'){
String filename = str.substring(1, str.length()-1);
File f = parentPane.getFileInBundle(filename);
return new ImageButton(parentPane, f.getAbsolutePath());
}
return null;
}
ImageButton btn = new ImageButton(parentPane);
String[] tokens = str.split("\\)\\s*\\.?");
for(String tok : tokens){
//System.out.println("token: " + tok);
if( tok.startsWith("exact") ){
btn.setExact(true);
btn.setSimilarity(1.f);
}
else if( tok.startsWith("Pattern") ){
String filename = tok.substring(
tok.indexOf("\"")+1,tok.lastIndexOf("\""));
File f = parentPane.getFileInBundle(filename);
if( f != null && f.exists() ){
btn.setFilename(f.getAbsolutePath());
}
else
return null;
}
else if( tok.startsWith("similar") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
try{
btn.setSimilarity(Float.valueOf(strArg));
}
catch(NumberFormatException e){
return null;
}
}
else if( tok.startsWith("firstN") ){ // FIXME: replace with limit/max
String strArg = tok.substring(tok.lastIndexOf("(")+1);
btn._numMatches = Integer.valueOf(strArg);
}
else if( tok.startsWith("targetOffset") ){
String strArg = tok.substring(tok.lastIndexOf("(")+1);
String[] args = strArg.split(",");
try{
Location offset = new Location(0,0);
offset.x = Integer.valueOf(args[0]);
offset.y = Integer.valueOf(args[1]);
btn.setTargetOffset(offset);
}
catch(NumberFormatException e){
return null;
}
}
}
btn.setToolTipText( btn.toString() );
return btn;
}
|
diff --git a/src/net/cyclestreets/SettingsActivity.java b/src/net/cyclestreets/SettingsActivity.java
index e41e975a..a62bb603 100644
--- a/src/net/cyclestreets/SettingsActivity.java
+++ b/src/net/cyclestreets/SettingsActivity.java
@@ -1,62 +1,64 @@
package net.cyclestreets;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setSummary(CycleStreetsPreferences.PREF_ROUTE_TYPE_KEY);
setSummary(CycleStreetsPreferences.PREF_UNITS_KEY);
setSummary(CycleStreetsPreferences.PREF_SPEED_KEY);
setSummary(CycleStreetsPreferences.PREF_MAPSTYLE_KEY);
setSummary(CycleStreetsPreferences.PREF_USERNAME_KEY);
setSummary(CycleStreetsPreferences.PREF_PASSWORD_KEY);
} // onCreate
@Override
protected void onResume()
{
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
} // onResume
@Override
protected void onPause()
{
super.onPause();
// stop listening while paused
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
} // onPause
public void onSharedPreferenceChanged(final SharedPreferences prefs, final String key)
{
setSummary(key);
} // onSharedPreferencesChanged
private void setSummary(final String key)
{
final Preference prefUI = findPreference(key);
if (prefUI instanceof ListPreference)
prefUI.setSummary(((ListPreference)prefUI).getEntry());
if (prefUI instanceof EditTextPreference)
{
String t = ((EditTextPreference)prefUI).getText();
- if((key.equals(CycleStreetsPreferences.PREF_PASSWORD_KEY)) && (t.length() != 0))
+ if((key.equals(CycleStreetsPreferences.PREF_PASSWORD_KEY)) &&
+ (t != null) &&
+ (t.length() != 0))
t = "********";
prefUI.setSummary(t);
}
} // setSummary
} // class SettingsActivity
| true | true | private void setSummary(final String key)
{
final Preference prefUI = findPreference(key);
if (prefUI instanceof ListPreference)
prefUI.setSummary(((ListPreference)prefUI).getEntry());
if (prefUI instanceof EditTextPreference)
{
String t = ((EditTextPreference)prefUI).getText();
if((key.equals(CycleStreetsPreferences.PREF_PASSWORD_KEY)) && (t.length() != 0))
t = "********";
prefUI.setSummary(t);
}
} // setSummary
| private void setSummary(final String key)
{
final Preference prefUI = findPreference(key);
if (prefUI instanceof ListPreference)
prefUI.setSummary(((ListPreference)prefUI).getEntry());
if (prefUI instanceof EditTextPreference)
{
String t = ((EditTextPreference)prefUI).getText();
if((key.equals(CycleStreetsPreferences.PREF_PASSWORD_KEY)) &&
(t != null) &&
(t.length() != 0))
t = "********";
prefUI.setSummary(t);
}
} // setSummary
|
diff --git a/plugins/eu.udig.omsbox/src/eu/udig/omsbox/core/OmsScriptExecutor.java b/plugins/eu.udig.omsbox/src/eu/udig/omsbox/core/OmsScriptExecutor.java
index 02f47b58c..738f5c4f0 100644
--- a/plugins/eu.udig.omsbox/src/eu/udig/omsbox/core/OmsScriptExecutor.java
+++ b/plugins/eu.udig.omsbox/src/eu/udig/omsbox/core/OmsScriptExecutor.java
@@ -1,325 +1,324 @@
/*
* JGrass - Free Open Source Java GIS http://www.jgrass.org
* (C) HydroloGIS - www.hydrologis.com
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the HydroloGIS BSD
* License v1.0 (http://udig.refractions.net/files/hsd3-v10.html).
*/
package eu.udig.omsbox.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import oms3.CLI;
import org.eclipse.core.runtime.Platform;
import org.joda.time.DateTime;
import eu.udig.omsbox.OmsBoxPlugin;
import eu.udig.omsbox.utils.OmsBoxConstants;
/**
* Executor of OMS scripts.
*
* @author Andrea Antonello (www.hydrologis.com)
*/
@SuppressWarnings("nls")
public class OmsScriptExecutor {
private static final String[] JAVA_EXES = {"jre/bin/java.exe", "jre/bin/java"};
private String classPath;
private boolean isRunning = false;
List<IProcessListener> listeners = new ArrayList<IProcessListener>();
private String javaFile;
public OmsScriptExecutor() throws Exception {
/*
* get java exec
*/
// search for the java exec to use
// try one. The udig jre, which has all we need
URL url = Platform.getInstallLocation().getURL();
String path = url.getPath();
File installLocation = new File(path);
javaFile = null;
for( String java : JAVA_EXES ) {
File tmpJavaFile = new File(installLocation, java);
if (tmpJavaFile.exists()) {
javaFile = tmpJavaFile.getAbsolutePath();
break;
}
}
// else try the java home
if (javaFile == null) {
String jreDirectory = System.getProperty("java.home");
for( String java : JAVA_EXES ) {
File tmpJavaFile = new File(jreDirectory, java);
if (tmpJavaFile.exists()) {
javaFile = tmpJavaFile.getAbsolutePath();
break;
}
}
}
// else hope for one in the path
if (javaFile == null) {
javaFile = "java";
}
/*
* get libraries
*/
String classpathJars = OmsBoxPlugin.getDefault().getClasspathJars();
classPath = classpathJars;
}
/**
* Execute an OMS script.
*
* @param script the script file or the script string.
* @param internalStream
* @param errorStream
* @param loggerLevelGui the log level as presented in the GUI, can be OFF|ON. This is not the OMS logger level, which
* in stead has to be picked from the {@link OmsBoxConstants#LOGLEVELS_MAP}.
* @param ramLevel the heap size to use in megabytes.
* @return the process.
* @throws Exception
*/
public Process exec( String script, final PrintStream internalStream, final PrintStream errorStream, String loggerLevelGui,
String ramLevel ) throws Exception {
if (loggerLevelGui == null)
loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF;
File scriptFile = new File(script);
if (!scriptFile.exists()) {
// if the file doesn't exist, it is a script, let's put it into a file
scriptFile = File.createTempFile("omsbox_script_", ".oms");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(scriptFile));
bw.write(script);
} finally {
bw.close();
}
} else {
// it is a script in a file, read it to log it
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(scriptFile));
String line = null;
while( (line = br.readLine()) != null ) {
sb.append(line).append("\n");
}
} finally {
br.close();
}
script = sb.toString();
}
// tmp folder
String tempdir = System.getProperty("java.io.tmpdir");
File omsTmp = new File(tempdir + File.separator + "oms");
if (!omsTmp.exists())
omsTmp.mkdirs();
List<String> arguments = new ArrayList<String>();
arguments.add(javaFile);
// ram usage
String ramExpr = "-Xmx" + ramLevel + "m";
arguments.add(ramExpr);
// modules jars
List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars();
StringBuilder sb = new StringBuilder();
for( String moduleJar : modulesJars ) {
sb.append(File.pathSeparator).append(moduleJar);
}
String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, "");
String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\"";
arguments.add(resourcesFlag);
// grass gisbase
String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference();
if (grassGisbase != null && grassGisbase.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase);
}
String grassShell = OmsBoxPlugin.getDefault().getShellPreference();
if (grassShell != null && grassShell.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell);
}
- String safeClassPath = "\"" + classPath + "\"";
// all the arguments
arguments.add("-cp");
- arguments.add(safeClassPath);
+ arguments.add(classPath);
arguments.add(CLI.class.getCanonicalName());
arguments.add("-r");
arguments.add(scriptFile.getAbsolutePath());
String[] args = arguments.toArray(new String[0]);
// {javaFile, ramExpr, resourcesFlag, "-cp", classPath,
// CLI.class.getCanonicalName(), "-r",
// scriptFile.getAbsolutePath()};
ProcessBuilder processBuilder = new ProcessBuilder(args);
// work in home
String homeDir = System.getProperty("java.home");
processBuilder.directory(new File(homeDir));
final Process process = processBuilder.start();
internalStream.println("Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
internalStream.println("");
// command launched
if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) {
internalStream.println("------------------------------>8----------------------------");
internalStream.println("Launching command: ");
internalStream.println("------------------");
List<String> command = processBuilder.command();
int i = 0;
for( String arg : command ) {
if (i++ != 0) {
if (!arg.startsWith("-")) {
internalStream.print("\t\t");
} else {
internalStream.print("\t");
}
}
internalStream.print(arg);
internalStream.print("\n");
}
internalStream.println("");
internalStream.println("(Put it all on a single line to execute it from command line)");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// script run
internalStream.println("Script run: ");
internalStream.println("-----------");
internalStream.println(script);
internalStream.println("");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// environment used
internalStream.println("Environment used: ");
internalStream.println("-----------------");
Map<String, String> environment = processBuilder.environment();
Set<Entry<String, String>> entrySet = environment.entrySet();
for( Entry<String, String> entry : entrySet ) {
internalStream.print(entry.getKey());
internalStream.print(" =\t");
internalStream.println(entry.getValue());
}
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
}
internalStream.println("");
isRunning = true;
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
internalStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
isRunning = false;
updateListeners();
}
internalStream.println("");
internalStream.println("");
internalStream.println("Process finished: "
+ new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
};
}.start();
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
/*
* remove of ugly recurring geotools warnings. Not nice, but
* at least users do not get confused.
*/
if (ConsoleMessageFilter.doRemove(line)) {
continue;
}
errorStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
return process;
}
public boolean isRunning() {
return isRunning;
}
public void addProcessListener( IProcessListener listener ) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
public void removeProcessListener( IProcessListener listener ) {
if (listeners.contains(listener)) {
listeners.remove(listener);
}
}
private void updateListeners() {
for( IProcessListener listener : listeners ) {
listener.onProcessStopped();
}
}
}
| false | true | public Process exec( String script, final PrintStream internalStream, final PrintStream errorStream, String loggerLevelGui,
String ramLevel ) throws Exception {
if (loggerLevelGui == null)
loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF;
File scriptFile = new File(script);
if (!scriptFile.exists()) {
// if the file doesn't exist, it is a script, let's put it into a file
scriptFile = File.createTempFile("omsbox_script_", ".oms");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(scriptFile));
bw.write(script);
} finally {
bw.close();
}
} else {
// it is a script in a file, read it to log it
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(scriptFile));
String line = null;
while( (line = br.readLine()) != null ) {
sb.append(line).append("\n");
}
} finally {
br.close();
}
script = sb.toString();
}
// tmp folder
String tempdir = System.getProperty("java.io.tmpdir");
File omsTmp = new File(tempdir + File.separator + "oms");
if (!omsTmp.exists())
omsTmp.mkdirs();
List<String> arguments = new ArrayList<String>();
arguments.add(javaFile);
// ram usage
String ramExpr = "-Xmx" + ramLevel + "m";
arguments.add(ramExpr);
// modules jars
List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars();
StringBuilder sb = new StringBuilder();
for( String moduleJar : modulesJars ) {
sb.append(File.pathSeparator).append(moduleJar);
}
String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, "");
String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\"";
arguments.add(resourcesFlag);
// grass gisbase
String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference();
if (grassGisbase != null && grassGisbase.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase);
}
String grassShell = OmsBoxPlugin.getDefault().getShellPreference();
if (grassShell != null && grassShell.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell);
}
String safeClassPath = "\"" + classPath + "\"";
// all the arguments
arguments.add("-cp");
arguments.add(safeClassPath);
arguments.add(CLI.class.getCanonicalName());
arguments.add("-r");
arguments.add(scriptFile.getAbsolutePath());
String[] args = arguments.toArray(new String[0]);
// {javaFile, ramExpr, resourcesFlag, "-cp", classPath,
// CLI.class.getCanonicalName(), "-r",
// scriptFile.getAbsolutePath()};
ProcessBuilder processBuilder = new ProcessBuilder(args);
// work in home
String homeDir = System.getProperty("java.home");
processBuilder.directory(new File(homeDir));
final Process process = processBuilder.start();
internalStream.println("Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
internalStream.println("");
// command launched
if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) {
internalStream.println("------------------------------>8----------------------------");
internalStream.println("Launching command: ");
internalStream.println("------------------");
List<String> command = processBuilder.command();
int i = 0;
for( String arg : command ) {
if (i++ != 0) {
if (!arg.startsWith("-")) {
internalStream.print("\t\t");
} else {
internalStream.print("\t");
}
}
internalStream.print(arg);
internalStream.print("\n");
}
internalStream.println("");
internalStream.println("(Put it all on a single line to execute it from command line)");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// script run
internalStream.println("Script run: ");
internalStream.println("-----------");
internalStream.println(script);
internalStream.println("");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// environment used
internalStream.println("Environment used: ");
internalStream.println("-----------------");
Map<String, String> environment = processBuilder.environment();
Set<Entry<String, String>> entrySet = environment.entrySet();
for( Entry<String, String> entry : entrySet ) {
internalStream.print(entry.getKey());
internalStream.print(" =\t");
internalStream.println(entry.getValue());
}
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
}
internalStream.println("");
isRunning = true;
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
internalStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
isRunning = false;
updateListeners();
}
internalStream.println("");
internalStream.println("");
internalStream.println("Process finished: "
+ new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
};
}.start();
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
/*
* remove of ugly recurring geotools warnings. Not nice, but
* at least users do not get confused.
*/
if (ConsoleMessageFilter.doRemove(line)) {
continue;
}
errorStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
return process;
}
| public Process exec( String script, final PrintStream internalStream, final PrintStream errorStream, String loggerLevelGui,
String ramLevel ) throws Exception {
if (loggerLevelGui == null)
loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF;
File scriptFile = new File(script);
if (!scriptFile.exists()) {
// if the file doesn't exist, it is a script, let's put it into a file
scriptFile = File.createTempFile("omsbox_script_", ".oms");
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(scriptFile));
bw.write(script);
} finally {
bw.close();
}
} else {
// it is a script in a file, read it to log it
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(scriptFile));
String line = null;
while( (line = br.readLine()) != null ) {
sb.append(line).append("\n");
}
} finally {
br.close();
}
script = sb.toString();
}
// tmp folder
String tempdir = System.getProperty("java.io.tmpdir");
File omsTmp = new File(tempdir + File.separator + "oms");
if (!omsTmp.exists())
omsTmp.mkdirs();
List<String> arguments = new ArrayList<String>();
arguments.add(javaFile);
// ram usage
String ramExpr = "-Xmx" + ramLevel + "m";
arguments.add(ramExpr);
// modules jars
List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars();
StringBuilder sb = new StringBuilder();
for( String moduleJar : modulesJars ) {
sb.append(File.pathSeparator).append(moduleJar);
}
String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, "");
String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\"";
arguments.add(resourcesFlag);
// grass gisbase
String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference();
if (grassGisbase != null && grassGisbase.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase);
}
String grassShell = OmsBoxPlugin.getDefault().getShellPreference();
if (grassShell != null && grassShell.length() > 0) {
arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell);
}
// all the arguments
arguments.add("-cp");
arguments.add(classPath);
arguments.add(CLI.class.getCanonicalName());
arguments.add("-r");
arguments.add(scriptFile.getAbsolutePath());
String[] args = arguments.toArray(new String[0]);
// {javaFile, ramExpr, resourcesFlag, "-cp", classPath,
// CLI.class.getCanonicalName(), "-r",
// scriptFile.getAbsolutePath()};
ProcessBuilder processBuilder = new ProcessBuilder(args);
// work in home
String homeDir = System.getProperty("java.home");
processBuilder.directory(new File(homeDir));
final Process process = processBuilder.start();
internalStream.println("Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
internalStream.println("");
// command launched
if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) {
internalStream.println("------------------------------>8----------------------------");
internalStream.println("Launching command: ");
internalStream.println("------------------");
List<String> command = processBuilder.command();
int i = 0;
for( String arg : command ) {
if (i++ != 0) {
if (!arg.startsWith("-")) {
internalStream.print("\t\t");
} else {
internalStream.print("\t");
}
}
internalStream.print(arg);
internalStream.print("\n");
}
internalStream.println("");
internalStream.println("(Put it all on a single line to execute it from command line)");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// script run
internalStream.println("Script run: ");
internalStream.println("-----------");
internalStream.println(script);
internalStream.println("");
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
// environment used
internalStream.println("Environment used: ");
internalStream.println("-----------------");
Map<String, String> environment = processBuilder.environment();
Set<Entry<String, String>> entrySet = environment.entrySet();
for( Entry<String, String> entry : entrySet ) {
internalStream.print(entry.getKey());
internalStream.print(" =\t");
internalStream.println(entry.getValue());
}
internalStream.println("------------------------------>8----------------------------");
internalStream.println("");
}
internalStream.println("");
isRunning = true;
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
internalStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
isRunning = false;
updateListeners();
}
internalStream.println("");
internalStream.println("");
internalStream.println("Process finished: "
+ new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
};
}.start();
new Thread(){
public void run() {
BufferedReader br = null;
try {
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line;
while( (line = br.readLine()) != null ) {
/*
* remove of ugly recurring geotools warnings. Not nice, but
* at least users do not get confused.
*/
if (ConsoleMessageFilter.doRemove(line)) {
continue;
}
errorStream.println(line);
}
} catch (Exception e) {
e.printStackTrace();
errorStream.println(e.getLocalizedMessage());
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
return process;
}
|
diff --git a/kernel/src/main/java/com/qspin/qtaste/testsuite/TestSuite.java b/kernel/src/main/java/com/qspin/qtaste/testsuite/TestSuite.java
index c6a4cb43..87ea534c 100644
--- a/kernel/src/main/java/com/qspin/qtaste/testsuite/TestSuite.java
+++ b/kernel/src/main/java/com/qspin/qtaste/testsuite/TestSuite.java
@@ -1,241 +1,242 @@
/*
Copyright 2007-2009 QSpin - www.qspin.be
This file is part of QTaste framework.
QTaste is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QTaste is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with QTaste. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TestSuite.java
*
* Created on 11 octobre 2007, 15:43
*/
package com.qspin.qtaste.testsuite;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import com.qspin.qtaste.kernel.engine.TestEngine;
import com.qspin.qtaste.reporter.testresults.TestResult;
import com.qspin.qtaste.reporter.testresults.TestResultsReportManager;
import com.qspin.qtaste.util.Log4jLoggerFactory;
/**
*
* @author lvboque
*/
public abstract class TestSuite implements TestReportListener {
private static Logger logger = Log4jLoggerFactory.getLogger(TestSuite.class);
protected String name;
protected int numberLoops = 1;
protected boolean loopsInHours = false;
private Date startExecutionDate;
private Date stopExecutionDate;
private int nbTestsToExecute = 0;
private int nbTestsExecuted = 0;
private int nbTestsPassed = 0;
private int nbTestsFailed = 0;
private int nbTestsNotAvailable = 0;
private int nbTestsRetries = 0;
private boolean abortedByUser = false;
private List<TestReportListener> testReportListeners = new LinkedList<TestReportListener>();
/** Creates a new instance of TestSuite */
public TestSuite(String name) {
this.name = name;
}
/**
* Computes and returns the number of tests to execute.
* @return number of tests to execute or -1 if unknown
*/
public abstract int computeNumberTestsToExecute();
/**
* Executes the test suite once in specified debug mode.
*
* @param debug true if in debug mode, false otherwise
* @return true if execution successful, false otherwise (aborted)
*/
public abstract boolean executeOnce(boolean debug);
/** Executes a test suite, the number of times specified by numberLoops/loopsInHours.
*
* @param debug true to execute in debug mode, false otherwise
* @param initializeTestEngine true to initialize/terminate the test engine, false otherwise
* @return true if execution successful, false otherwise (aborted)
*/
public boolean execute(boolean debug, boolean initializeTestEngine) {
boolean executionSuccess = true;
nbTestsToExecute = computeNumberTestsToExecute();
startExecutionDate = new Date();
reportTestSuiteStarted();
if (nbTestsToExecute != 0) {
if (!initializeTestEngine || TestEngine.initialize()) {
if (numberLoops != 1 || loopsInHours) {
boolean continueExecution = true;
int currentExecution = 1;
long startTime_ms = System.currentTimeMillis();
do {
logger.info("Execution " + currentExecution + (numberLoops != -1 && !loopsInHours ? " of " + numberLoops : "") + " of test suite " + getName());
if (!executeOnce(debug)) {
executionSuccess = false;
break;
}
if (loopsInHours) {
long elapsedTime_ms = System.currentTimeMillis() - startTime_ms;
long elapsedTime_h = elapsedTime_ms / 1000 / 3600;
continueExecution = elapsedTime_h < numberLoops;
} else {
continueExecution = numberLoops == -1 || currentExecution < numberLoops;
}
currentExecution++;
} while (continueExecution);
} else {
executionSuccess = executeOnce(debug);
}
} else {
executionSuccess = false;
}
this.abortedByUser = TestEngine.isStartStopSUTCancelled;
if (initializeTestEngine) {
TestEngine.terminate();
}
} else {
logger.warn("Test suite " + getName() + " doesn't contain any test to execute");
+ executionSuccess = false;
}
stopExecutionDate = new Date();
reportTestSuiteStopped();
return executionSuccess;
}
public abstract List<TestScript> getTestScripts();
public void reportTestSuiteStarted() {
TestResultsReportManager.getInstance().refresh();
for (TestReportListener testReportListener: testReportListeners) {
testReportListener.reportTestSuiteStarted();
}
}
public void reportTestSuiteStopped() {
TestResultsReportManager.getInstance().refresh();
for (TestReportListener testReportListener: testReportListeners) {
testReportListener.reportTestSuiteStopped();
}
}
public boolean isAbortedByUser() {
return abortedByUser;
}
public void setAbortedByUser(boolean value) {
abortedByUser = value;
}
/**
* @param numberLoops number of executions, number of hours of executions,
* or -1 for infinite number of executions
* @param loopsInHours if true, numberLoops is the number of hours of executions
* otherwise numberLoops is the number of executions
*/
public void setExecutionLoops(int numberLoops, boolean loopsInHours) {
this.numberLoops = numberLoops;
this.loopsInHours = loopsInHours;
}
public String getName() {
return name;
}
public Date getStartExecutionDate() {
return startExecutionDate;
}
public Date getStopExecutionDate() {
return stopExecutionDate;
}
public int getNbTestsToExecute() {
return nbTestsToExecute;
}
public void setNbTestsToExecute(int nbTestsToExecute) {
this.nbTestsToExecute = nbTestsToExecute;
}
public int getNbTestsExecuted() {
return nbTestsExecuted;
}
public void reportTestResult(TestResult.Status status) {
nbTestsExecuted++;
switch (status) {
case SUCCESS:
nbTestsPassed++;
break;
case FAIL:
nbTestsFailed++;
break;
case NOT_AVAILABLE:
nbTestsNotAvailable++;
break;
default:
logger.error("Invalid status: " + status);
}
for (TestReportListener testReportListener: testReportListeners) {
testReportListener.reportTestResult(status);
}
}
public void reportTestRetry() {
nbTestsRetries++;
for (TestReportListener testResultListener: testReportListeners) {
testResultListener.reportTestRetry();
}
}
public int getNbTestsPassed() {
return nbTestsPassed;
}
public int getNbTestsFailed() {
return nbTestsFailed;
}
public int getNbTestsNotAvailable() {
return nbTestsNotAvailable;
}
public int getNbTestsRetries() {
return nbTestsRetries;
}
public void addTestReportListener(TestReportListener listener) {
testReportListeners.add(listener);
}
public void removeTestReportListener(TestReportListener listener) {
testReportListeners.remove(listener);
}
}
| true | true | public boolean execute(boolean debug, boolean initializeTestEngine) {
boolean executionSuccess = true;
nbTestsToExecute = computeNumberTestsToExecute();
startExecutionDate = new Date();
reportTestSuiteStarted();
if (nbTestsToExecute != 0) {
if (!initializeTestEngine || TestEngine.initialize()) {
if (numberLoops != 1 || loopsInHours) {
boolean continueExecution = true;
int currentExecution = 1;
long startTime_ms = System.currentTimeMillis();
do {
logger.info("Execution " + currentExecution + (numberLoops != -1 && !loopsInHours ? " of " + numberLoops : "") + " of test suite " + getName());
if (!executeOnce(debug)) {
executionSuccess = false;
break;
}
if (loopsInHours) {
long elapsedTime_ms = System.currentTimeMillis() - startTime_ms;
long elapsedTime_h = elapsedTime_ms / 1000 / 3600;
continueExecution = elapsedTime_h < numberLoops;
} else {
continueExecution = numberLoops == -1 || currentExecution < numberLoops;
}
currentExecution++;
} while (continueExecution);
} else {
executionSuccess = executeOnce(debug);
}
} else {
executionSuccess = false;
}
this.abortedByUser = TestEngine.isStartStopSUTCancelled;
if (initializeTestEngine) {
TestEngine.terminate();
}
} else {
logger.warn("Test suite " + getName() + " doesn't contain any test to execute");
}
stopExecutionDate = new Date();
reportTestSuiteStopped();
return executionSuccess;
}
| public boolean execute(boolean debug, boolean initializeTestEngine) {
boolean executionSuccess = true;
nbTestsToExecute = computeNumberTestsToExecute();
startExecutionDate = new Date();
reportTestSuiteStarted();
if (nbTestsToExecute != 0) {
if (!initializeTestEngine || TestEngine.initialize()) {
if (numberLoops != 1 || loopsInHours) {
boolean continueExecution = true;
int currentExecution = 1;
long startTime_ms = System.currentTimeMillis();
do {
logger.info("Execution " + currentExecution + (numberLoops != -1 && !loopsInHours ? " of " + numberLoops : "") + " of test suite " + getName());
if (!executeOnce(debug)) {
executionSuccess = false;
break;
}
if (loopsInHours) {
long elapsedTime_ms = System.currentTimeMillis() - startTime_ms;
long elapsedTime_h = elapsedTime_ms / 1000 / 3600;
continueExecution = elapsedTime_h < numberLoops;
} else {
continueExecution = numberLoops == -1 || currentExecution < numberLoops;
}
currentExecution++;
} while (continueExecution);
} else {
executionSuccess = executeOnce(debug);
}
} else {
executionSuccess = false;
}
this.abortedByUser = TestEngine.isStartStopSUTCancelled;
if (initializeTestEngine) {
TestEngine.terminate();
}
} else {
logger.warn("Test suite " + getName() + " doesn't contain any test to execute");
executionSuccess = false;
}
stopExecutionDate = new Date();
reportTestSuiteStopped();
return executionSuccess;
}
|
diff --git a/src/main/java/com/vdweem/webspotify/action/ImageAction.java b/src/main/java/com/vdweem/webspotify/action/ImageAction.java
index 93841e0..5c2769c 100644
--- a/src/main/java/com/vdweem/webspotify/action/ImageAction.java
+++ b/src/main/java/com/vdweem/webspotify/action/ImageAction.java
@@ -1,64 +1,64 @@
package com.vdweem.webspotify.action;
import jahspotify.media.Artist;
import jahspotify.media.Image;
import jahspotify.media.Link;
import jahspotify.services.JahSpotifyService;
import jahspotify.services.MediaHelper;
import java.util.List;
import com.opensymphony.xwork2.Result;
import com.vdweem.webspotify.result.ImageResult;
/**
* Show an image. If no image is found then show the corresponding placeholder.
* @author Niels
*/
public class ImageAction {
private String id;
public Result execute() {
Link link = Link.create(id);
String img = null;
switch (link.getType()) {
case ALBUM:
img = "noAlbum.png";
link = JahSpotifyService.getInstance().getJahSpotify().readAlbum(link).getCover();
break;
case ARTIST:
img = "noArtist.png";
Artist artist = JahSpotifyService.getInstance().getJahSpotify().readArtist(link, true);
if (!MediaHelper.waitFor(artist, 2)) break;
List<Link> links = artist.getPortraits();
if (links.size() > 0) link = links.get(0);
else link = null;
break;
case TRACK:
link = Link.create(JahSpotifyService.getInstance().getJahSpotify().readTrack(link).getCover());
break;
case IMAGE:
break;
default:
throw new IllegalArgumentException("Images should be created from an artist, album, track or image link.");
}
if (link != null) {
Image image = JahSpotifyService.getInstance().getJahSpotify().readImage(link);
if (image == null) return null;
if (MediaHelper.waitFor(image, 2)) {
return new ImageResult(image.getBytes());
}
}
- return new ImageResult("images/" + img);
+ return new ImageResult(img);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| true | true | public Result execute() {
Link link = Link.create(id);
String img = null;
switch (link.getType()) {
case ALBUM:
img = "noAlbum.png";
link = JahSpotifyService.getInstance().getJahSpotify().readAlbum(link).getCover();
break;
case ARTIST:
img = "noArtist.png";
Artist artist = JahSpotifyService.getInstance().getJahSpotify().readArtist(link, true);
if (!MediaHelper.waitFor(artist, 2)) break;
List<Link> links = artist.getPortraits();
if (links.size() > 0) link = links.get(0);
else link = null;
break;
case TRACK:
link = Link.create(JahSpotifyService.getInstance().getJahSpotify().readTrack(link).getCover());
break;
case IMAGE:
break;
default:
throw new IllegalArgumentException("Images should be created from an artist, album, track or image link.");
}
if (link != null) {
Image image = JahSpotifyService.getInstance().getJahSpotify().readImage(link);
if (image == null) return null;
if (MediaHelper.waitFor(image, 2)) {
return new ImageResult(image.getBytes());
}
}
return new ImageResult("images/" + img);
}
| public Result execute() {
Link link = Link.create(id);
String img = null;
switch (link.getType()) {
case ALBUM:
img = "noAlbum.png";
link = JahSpotifyService.getInstance().getJahSpotify().readAlbum(link).getCover();
break;
case ARTIST:
img = "noArtist.png";
Artist artist = JahSpotifyService.getInstance().getJahSpotify().readArtist(link, true);
if (!MediaHelper.waitFor(artist, 2)) break;
List<Link> links = artist.getPortraits();
if (links.size() > 0) link = links.get(0);
else link = null;
break;
case TRACK:
link = Link.create(JahSpotifyService.getInstance().getJahSpotify().readTrack(link).getCover());
break;
case IMAGE:
break;
default:
throw new IllegalArgumentException("Images should be created from an artist, album, track or image link.");
}
if (link != null) {
Image image = JahSpotifyService.getInstance().getJahSpotify().readImage(link);
if (image == null) return null;
if (MediaHelper.waitFor(image, 2)) {
return new ImageResult(image.getBytes());
}
}
return new ImageResult(img);
}
|
diff --git a/src/testapp/interactive/java/nextapp/echo2/testapp/interactive/testscreen/TableTest.java b/src/testapp/interactive/java/nextapp/echo2/testapp/interactive/testscreen/TableTest.java
index 3a9e6c51..e51e76e0 100644
--- a/src/testapp/interactive/java/nextapp/echo2/testapp/interactive/testscreen/TableTest.java
+++ b/src/testapp/interactive/java/nextapp/echo2/testapp/interactive/testscreen/TableTest.java
@@ -1,401 +1,408 @@
/*
* This file is part of the Echo Web Application Framework (hereinafter "Echo").
* Copyright (C) 2002-2005 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package nextapp.echo2.testapp.interactive.testscreen;
import nextapp.echo2.app.Border;
import nextapp.echo2.app.Color;
import nextapp.echo2.app.Column;
import nextapp.echo2.app.Extent;
import nextapp.echo2.app.Insets;
import nextapp.echo2.app.Label;
import nextapp.echo2.app.SplitPane;
import nextapp.echo2.app.Table;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.app.event.ChangeEvent;
import nextapp.echo2.app.event.ChangeListener;
import nextapp.echo2.app.layout.SplitPaneLayoutData;
import nextapp.echo2.app.list.ListSelectionModel;
import nextapp.echo2.app.table.AbstractTableModel;
import nextapp.echo2.app.table.DefaultTableModel;
import nextapp.echo2.app.table.TableColumnModel;
import nextapp.echo2.testapp.interactive.ButtonColumn;
import nextapp.echo2.testapp.interactive.InteractiveApp;
import nextapp.echo2.testapp.interactive.StyleUtil;
import nextapp.echo2.testapp.interactive.Styles;
/**
* A test for <code>Tables</code>s.
*/
public class TableTest extends SplitPane {
private Table testTable;
private class MultiplicationTableModel extends AbstractTableModel {
/**
* @see nextapp.echo2.app.table.TableModel#getColumnCount()
*/
public int getColumnCount() {
return 12;
}
/**
* @see nextapp.echo2.app.table.TableModel#getRowCount()
*/
public int getRowCount() {
return 12;
}
/**
* @see nextapp.echo2.app.table.TableModel#getValueAt(int, int)
*/
public Object getValueAt(int column, int row) {
return new Integer((column + 1) * (row + 1));
}
}
/**
* Writes <code>ActionEvent</code>s to console.
*/
private ActionListener actionListener = new ActionListener() {
/**
* @see nextapp.echo2.app.event.ActionListener#actionPerformed(nextapp.echo2.app.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
((InteractiveApp) getApplicationInstance()).consoleWrite(e.toString());
}
};
/**
* Writes <code>ChangeEvent</code>s to console.
*/
private ChangeListener changeListener = new ChangeListener() {
/**
* @see nextapp.echo2.app.event.ChangeListener#stateChanged(nextapp.echo2.app.event.ChangeEvent)
*/
public void stateChanged(ChangeEvent e) {
((InteractiveApp) getApplicationInstance()).consoleWrite(e.toString());
}
};
public TableTest() {
super(SplitPane.ORIENTATION_HORIZONTAL, new Extent(250, Extent.PX));
setStyleName("defaultResizable");
Column groupContainerColumn = new Column();
groupContainerColumn.setCellSpacing(new Extent(5));
groupContainerColumn.setStyleName(Styles.TEST_CONTROLS_COLUMN_STYLE_NAME);
add(groupContainerColumn);
Column testColumn = new Column();
SplitPaneLayoutData splitPaneLayoutData = new SplitPaneLayoutData();
splitPaneLayoutData.setInsets(new Insets(10, 5));
testColumn.setLayoutData(splitPaneLayoutData);
add(testColumn);
ButtonColumn controlsColumn;
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("TableModel"));
controlsColumn.addButton("Multiplication Model", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new MultiplicationTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Empty)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new DefaultTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Employees)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model = new DefaultTableModel();
model.setColumnCount(3);
model.insertRow(0, new String[]{"Bob Johnson", "[email protected]", "949.555.1234"});
model.insertRow(0, new String[]{"Laura Smith", "[email protected]", "217.555.9343"});
model.insertRow(0, new String[]{"Jenny Roberts", "[email protected]", "630.555.1987"});
model.insertRow(0, new String[]{"Thomas Albertson", "[email protected]", "619.555.1233"});
model.insertRow(0, new String[]{"Albert Thomas", "[email protected]", "408.555.3232"});
model.insertRow(0, new String[]{"Sheila Simmons", "[email protected]", "212.555.8700"});
model.insertRow(0, new String[]{"Mark Atkinson", "[email protected]", "213.555.9456"});
model.insertRow(0, new String[]{"Linda Jefferson", "[email protected]", "949.555.8925"});
model.insertRow(0, new String[]{"Yvonne Adams", "[email protected]", "714.555.8543"});
testTable.setModel(model);
}
});
testTable = new Table();
testTable.setBorder(new Border(new Extent(1), Color.BLUE, Border.STYLE_SOLID));
testColumn.add(testTable);
controlsColumn.add(new Label("Appearance"));
controlsColumn.addButton("Change Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Border (All Attributes)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.randomBorder());
}
});
controlsColumn.addButton("Change Border Color", new ActionListener() {
public void actionPerformed(ActionEvent e) {
Border border = testTable.getBorder();
testTable.setBorder(new Border(border.getSize(), StyleUtil.randomColor(), border.getStyle()));
}
});
controlsColumn.addButton("Change Border Size", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderSize(testTable.getBorder()));
}
});
controlsColumn.addButton("Change Border Style", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderStyle(testTable.getBorder()));
}
});
controlsColumn.addButton("Set Insets 0px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(0));
}
});
controlsColumn.addButton("Set Insets 2px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(2));
}
});
controlsColumn.addButton("Set Insets 10/5px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 5));
}
});
controlsColumn.addButton("Set Insets 10/20/30/40px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 20, 30, 40));
}
});
controlsColumn.addButton("Set Width = null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(null);
}
});
controlsColumn.addButton("Set Width = 500px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(500));
}
});
controlsColumn.addButton("Set Width = 100%", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(100, Extent.PERCENT));
}
});
controlsColumn.addButton("Set ColumnWidths Equal", new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableColumnModel columnModel = testTable.getColumnModel();
int columnCount = columnModel.getColumnCount();
- Extent width = new Extent(100 / columnCount, Extent.PERCENT);
- for (int i = 0; i < columnCount; ++i) {
- columnModel.getColumn(i).setWidth(width);
+ if (columnCount > 0) {
+ Extent width = new Extent(100 / columnCount, Extent.PERCENT);
+ for (int i = 0; i < columnCount; ++i) {
+ columnModel.getColumn(i).setWidth(width);
+ }
}
}
});
+ controlsColumn.addButton("Toggle Header Visible", new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ testTable.setHeaderVisible(!testTable.isHeaderVisible());
+ }
+ });
// Rollover Effect Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Rollover Effects"));
controlsColumn.addButton("Enable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(true);
}
});
controlsColumn.addButton("Disable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(false);
}
});
controlsColumn.addButton("Set Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(null);
}
});
controlsColumn.addButton("Set Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(null);
}
});
controlsColumn.addButton("Set Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(null);
}
});
controlsColumn.addButton("Set Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(Styles.BG_SHADOW_LIGHT_BLUE);
}
});
controlsColumn.addButton("Clear Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(null);
}
});
// Selection Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Selection"));
controlsColumn.addButton("Enable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(true);
}
});
controlsColumn.addButton("Disable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(false);
}
});
controlsColumn.addButton("Set SelectionMode = Single", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
});
controlsColumn.addButton("Set SelectionMode = Multiple", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_SELECTION);
}
});
controlsColumn.addButton("Set Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(null);
}
});
controlsColumn.addButton("Set Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(null);
}
});
controlsColumn.addButton("Set Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(null);
}
});
controlsColumn.addButton("Set Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(Styles.BUTTON_PRESSED_BACKGROUND_IMAGE);
}
});
controlsColumn.addButton("Clear Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(null);
}
});
// Listener Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Listeners"));
controlsColumn.addButton("Add ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.addActionListener(actionListener);
}
});
controlsColumn.addButton("Remove ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.removeActionListener(actionListener);
}
});
controlsColumn.addButton("Add ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().addChangeListener(changeListener);
}
});
controlsColumn.addButton("Remove ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().removeChangeListener(changeListener);
}
});
}
}
| false | true | public TableTest() {
super(SplitPane.ORIENTATION_HORIZONTAL, new Extent(250, Extent.PX));
setStyleName("defaultResizable");
Column groupContainerColumn = new Column();
groupContainerColumn.setCellSpacing(new Extent(5));
groupContainerColumn.setStyleName(Styles.TEST_CONTROLS_COLUMN_STYLE_NAME);
add(groupContainerColumn);
Column testColumn = new Column();
SplitPaneLayoutData splitPaneLayoutData = new SplitPaneLayoutData();
splitPaneLayoutData.setInsets(new Insets(10, 5));
testColumn.setLayoutData(splitPaneLayoutData);
add(testColumn);
ButtonColumn controlsColumn;
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("TableModel"));
controlsColumn.addButton("Multiplication Model", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new MultiplicationTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Empty)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new DefaultTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Employees)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model = new DefaultTableModel();
model.setColumnCount(3);
model.insertRow(0, new String[]{"Bob Johnson", "[email protected]", "949.555.1234"});
model.insertRow(0, new String[]{"Laura Smith", "[email protected]", "217.555.9343"});
model.insertRow(0, new String[]{"Jenny Roberts", "[email protected]", "630.555.1987"});
model.insertRow(0, new String[]{"Thomas Albertson", "[email protected]", "619.555.1233"});
model.insertRow(0, new String[]{"Albert Thomas", "[email protected]", "408.555.3232"});
model.insertRow(0, new String[]{"Sheila Simmons", "[email protected]", "212.555.8700"});
model.insertRow(0, new String[]{"Mark Atkinson", "[email protected]", "213.555.9456"});
model.insertRow(0, new String[]{"Linda Jefferson", "[email protected]", "949.555.8925"});
model.insertRow(0, new String[]{"Yvonne Adams", "[email protected]", "714.555.8543"});
testTable.setModel(model);
}
});
testTable = new Table();
testTable.setBorder(new Border(new Extent(1), Color.BLUE, Border.STYLE_SOLID));
testColumn.add(testTable);
controlsColumn.add(new Label("Appearance"));
controlsColumn.addButton("Change Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Border (All Attributes)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.randomBorder());
}
});
controlsColumn.addButton("Change Border Color", new ActionListener() {
public void actionPerformed(ActionEvent e) {
Border border = testTable.getBorder();
testTable.setBorder(new Border(border.getSize(), StyleUtil.randomColor(), border.getStyle()));
}
});
controlsColumn.addButton("Change Border Size", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderSize(testTable.getBorder()));
}
});
controlsColumn.addButton("Change Border Style", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderStyle(testTable.getBorder()));
}
});
controlsColumn.addButton("Set Insets 0px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(0));
}
});
controlsColumn.addButton("Set Insets 2px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(2));
}
});
controlsColumn.addButton("Set Insets 10/5px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 5));
}
});
controlsColumn.addButton("Set Insets 10/20/30/40px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 20, 30, 40));
}
});
controlsColumn.addButton("Set Width = null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(null);
}
});
controlsColumn.addButton("Set Width = 500px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(500));
}
});
controlsColumn.addButton("Set Width = 100%", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(100, Extent.PERCENT));
}
});
controlsColumn.addButton("Set ColumnWidths Equal", new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableColumnModel columnModel = testTable.getColumnModel();
int columnCount = columnModel.getColumnCount();
Extent width = new Extent(100 / columnCount, Extent.PERCENT);
for (int i = 0; i < columnCount; ++i) {
columnModel.getColumn(i).setWidth(width);
}
}
});
// Rollover Effect Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Rollover Effects"));
controlsColumn.addButton("Enable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(true);
}
});
controlsColumn.addButton("Disable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(false);
}
});
controlsColumn.addButton("Set Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(null);
}
});
controlsColumn.addButton("Set Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(null);
}
});
controlsColumn.addButton("Set Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(null);
}
});
controlsColumn.addButton("Set Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(Styles.BG_SHADOW_LIGHT_BLUE);
}
});
controlsColumn.addButton("Clear Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(null);
}
});
// Selection Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Selection"));
controlsColumn.addButton("Enable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(true);
}
});
controlsColumn.addButton("Disable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(false);
}
});
controlsColumn.addButton("Set SelectionMode = Single", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
});
controlsColumn.addButton("Set SelectionMode = Multiple", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_SELECTION);
}
});
controlsColumn.addButton("Set Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(null);
}
});
controlsColumn.addButton("Set Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(null);
}
});
controlsColumn.addButton("Set Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(null);
}
});
controlsColumn.addButton("Set Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(Styles.BUTTON_PRESSED_BACKGROUND_IMAGE);
}
});
controlsColumn.addButton("Clear Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(null);
}
});
// Listener Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Listeners"));
controlsColumn.addButton("Add ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.addActionListener(actionListener);
}
});
controlsColumn.addButton("Remove ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.removeActionListener(actionListener);
}
});
controlsColumn.addButton("Add ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().addChangeListener(changeListener);
}
});
controlsColumn.addButton("Remove ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().removeChangeListener(changeListener);
}
});
}
| public TableTest() {
super(SplitPane.ORIENTATION_HORIZONTAL, new Extent(250, Extent.PX));
setStyleName("defaultResizable");
Column groupContainerColumn = new Column();
groupContainerColumn.setCellSpacing(new Extent(5));
groupContainerColumn.setStyleName(Styles.TEST_CONTROLS_COLUMN_STYLE_NAME);
add(groupContainerColumn);
Column testColumn = new Column();
SplitPaneLayoutData splitPaneLayoutData = new SplitPaneLayoutData();
splitPaneLayoutData.setInsets(new Insets(10, 5));
testColumn.setLayoutData(splitPaneLayoutData);
add(testColumn);
ButtonColumn controlsColumn;
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("TableModel"));
controlsColumn.addButton("Multiplication Model", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new MultiplicationTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Empty)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setModel(new DefaultTableModel());
}
});
controlsColumn.addButton("DefaultTableModel (Employees)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model = new DefaultTableModel();
model.setColumnCount(3);
model.insertRow(0, new String[]{"Bob Johnson", "[email protected]", "949.555.1234"});
model.insertRow(0, new String[]{"Laura Smith", "[email protected]", "217.555.9343"});
model.insertRow(0, new String[]{"Jenny Roberts", "[email protected]", "630.555.1987"});
model.insertRow(0, new String[]{"Thomas Albertson", "[email protected]", "619.555.1233"});
model.insertRow(0, new String[]{"Albert Thomas", "[email protected]", "408.555.3232"});
model.insertRow(0, new String[]{"Sheila Simmons", "[email protected]", "212.555.8700"});
model.insertRow(0, new String[]{"Mark Atkinson", "[email protected]", "213.555.9456"});
model.insertRow(0, new String[]{"Linda Jefferson", "[email protected]", "949.555.8925"});
model.insertRow(0, new String[]{"Yvonne Adams", "[email protected]", "714.555.8543"});
testTable.setModel(model);
}
});
testTable = new Table();
testTable.setBorder(new Border(new Extent(1), Color.BLUE, Border.STYLE_SOLID));
testColumn.add(testTable);
controlsColumn.add(new Label("Appearance"));
controlsColumn.addButton("Change Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Change Border (All Attributes)", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.randomBorder());
}
});
controlsColumn.addButton("Change Border Color", new ActionListener() {
public void actionPerformed(ActionEvent e) {
Border border = testTable.getBorder();
testTable.setBorder(new Border(border.getSize(), StyleUtil.randomColor(), border.getStyle()));
}
});
controlsColumn.addButton("Change Border Size", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderSize(testTable.getBorder()));
}
});
controlsColumn.addButton("Change Border Style", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setBorder(StyleUtil.nextBorderStyle(testTable.getBorder()));
}
});
controlsColumn.addButton("Set Insets 0px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(0));
}
});
controlsColumn.addButton("Set Insets 2px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(2));
}
});
controlsColumn.addButton("Set Insets 10/5px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 5));
}
});
controlsColumn.addButton("Set Insets 10/20/30/40px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setInsets(new Insets(10, 20, 30, 40));
}
});
controlsColumn.addButton("Set Width = null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(null);
}
});
controlsColumn.addButton("Set Width = 500px", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(500));
}
});
controlsColumn.addButton("Set Width = 100%", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setWidth(new Extent(100, Extent.PERCENT));
}
});
controlsColumn.addButton("Set ColumnWidths Equal", new ActionListener() {
public void actionPerformed(ActionEvent e) {
TableColumnModel columnModel = testTable.getColumnModel();
int columnCount = columnModel.getColumnCount();
if (columnCount > 0) {
Extent width = new Extent(100 / columnCount, Extent.PERCENT);
for (int i = 0; i < columnCount; ++i) {
columnModel.getColumn(i).setWidth(width);
}
}
}
});
controlsColumn.addButton("Toggle Header Visible", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setHeaderVisible(!testTable.isHeaderVisible());
}
});
// Rollover Effect Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Rollover Effects"));
controlsColumn.addButton("Enable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(true);
}
});
controlsColumn.addButton("Disable Rollover Effects", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverEnabled(false);
}
});
controlsColumn.addButton("Set Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverForeground(null);
}
});
controlsColumn.addButton("Set Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Rollover Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackground(null);
}
});
controlsColumn.addButton("Set Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Rollover Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverFont(null);
}
});
controlsColumn.addButton("Set Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(Styles.BG_SHADOW_LIGHT_BLUE);
}
});
controlsColumn.addButton("Clear Rollover Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setRolloverBackgroundImage(null);
}
});
// Selection Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Selection"));
controlsColumn.addButton("Enable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(true);
}
});
controlsColumn.addButton("Disable Selection", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionEnabled(false);
}
});
controlsColumn.addButton("Set SelectionMode = Single", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
});
controlsColumn.addButton("Set SelectionMode = Multiple", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_SELECTION);
}
});
controlsColumn.addButton("Set Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Foreground", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionForeground(null);
}
});
controlsColumn.addButton("Set Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(StyleUtil.randomColor());
}
});
controlsColumn.addButton("Clear Selection Background", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackground(null);
}
});
controlsColumn.addButton("Set Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(StyleUtil.randomFont());
}
});
controlsColumn.addButton("Clear Selection Font", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionFont(null);
}
});
controlsColumn.addButton("Set Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(Styles.BUTTON_PRESSED_BACKGROUND_IMAGE);
}
});
controlsColumn.addButton("Clear Selection Background Image", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.setSelectionBackgroundImage(null);
}
});
// Listener Settings
controlsColumn = new ButtonColumn();
groupContainerColumn.add(controlsColumn);
controlsColumn.add(new Label("Listeners"));
controlsColumn.addButton("Add ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.addActionListener(actionListener);
}
});
controlsColumn.addButton("Remove ActionListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.removeActionListener(actionListener);
}
});
controlsColumn.addButton("Add ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().addChangeListener(changeListener);
}
});
controlsColumn.addButton("Remove ChangeListener", new ActionListener() {
public void actionPerformed(ActionEvent e) {
testTable.getSelectionModel().removeChangeListener(changeListener);
}
});
}
|
diff --git a/src/com/sohail/online_quizzing_app/tests/TestDeserialize.java b/src/com/sohail/online_quizzing_app/tests/TestDeserialize.java
index 5950e0a..7a49a8d 100644
--- a/src/com/sohail/online_quizzing_app/tests/TestDeserialize.java
+++ b/src/com/sohail/online_quizzing_app/tests/TestDeserialize.java
@@ -1,62 +1,63 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sohail.online_quizzing_app.tests;
import com.sohail.online_quizzing_app.model.pojo.OptionStructure;
import com.sohail.online_quizzing_app.model.pojo.QuestionStructure;
import com.sohail.online_quizzing_app.model.pojo.QuizStructure;
import java.io.File;
import java.util.ArrayList;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
/**
*
* @author SOHAIL
*/
public class TestDeserialize {
public static void main(String[] args) {
Serializer serializer = new Persister();
File source = new File("D:/Quiz.xml");
QuizStructure quiz = null;
try {
quiz = serializer.read(QuizStructure.class, source);
} catch (Exception ex) {
ex.printStackTrace();
}
ArrayList<QuestionStructure> questions = quiz.getQuestions();
- ArrayList<OptionStructure> options = quiz.getOptionList();
System.out.println("Quiz Details:");
System.out.println("Quiz Subject: " + quiz.getSubject());
System.out.println("Quiz Topic: " + quiz.getTopic());
System.out.println("Quiz Description: " + quiz.getDescription());
System.out.println("Quiz Time Limit: " + quiz.getTimeLimit());
System.out.println("Quiz Submission Date: " + quiz.getSubmission_date());
System.out.println("Quiz Due Date: " + quiz.getDue_date());
System.out.println("Quiz Total Questions in Quiz: " + quiz.getTotal_questions_in_quiz());
System.out.println("Quiz Total Questions To Solve: " + quiz.getTotal_questions_to_solve());
System.out.println("---------------------------------------------------");
for (QuestionStructure questionStructure : questions) {
System.out.println("Question: " + questionStructure.getQuestion());
System.out.println("Question Image: " + questionStructure.getQuestionImage());
System.out.println("Question Difficulty: " + questionStructure.getDifficulty());
System.out.println("Question UUID: " + questionStructure.getUuid());
System.out.println("Quiz UUID: " + questionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
+ //Iterate over each options of the question
+ ArrayList<OptionStructure> options = quiz.getOptionList();
for (OptionStructure optionStructure : options) {
System.out.println("Option: " + optionStructure.getOption());
System.out.println("Option Image: " + optionStructure.getOptionImage());
System.out.println("Option IsCorrectAns: " + optionStructure.isCorrectAns());
System.out.println("Option UUID: " + optionStructure.getUuid());
System.out.println("Question UUID: " + optionStructure.getUuid_question());
System.out.println("Quiz UUID: " + optionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
}
}
}
}
| false | true | public static void main(String[] args) {
Serializer serializer = new Persister();
File source = new File("D:/Quiz.xml");
QuizStructure quiz = null;
try {
quiz = serializer.read(QuizStructure.class, source);
} catch (Exception ex) {
ex.printStackTrace();
}
ArrayList<QuestionStructure> questions = quiz.getQuestions();
ArrayList<OptionStructure> options = quiz.getOptionList();
System.out.println("Quiz Details:");
System.out.println("Quiz Subject: " + quiz.getSubject());
System.out.println("Quiz Topic: " + quiz.getTopic());
System.out.println("Quiz Description: " + quiz.getDescription());
System.out.println("Quiz Time Limit: " + quiz.getTimeLimit());
System.out.println("Quiz Submission Date: " + quiz.getSubmission_date());
System.out.println("Quiz Due Date: " + quiz.getDue_date());
System.out.println("Quiz Total Questions in Quiz: " + quiz.getTotal_questions_in_quiz());
System.out.println("Quiz Total Questions To Solve: " + quiz.getTotal_questions_to_solve());
System.out.println("---------------------------------------------------");
for (QuestionStructure questionStructure : questions) {
System.out.println("Question: " + questionStructure.getQuestion());
System.out.println("Question Image: " + questionStructure.getQuestionImage());
System.out.println("Question Difficulty: " + questionStructure.getDifficulty());
System.out.println("Question UUID: " + questionStructure.getUuid());
System.out.println("Quiz UUID: " + questionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
for (OptionStructure optionStructure : options) {
System.out.println("Option: " + optionStructure.getOption());
System.out.println("Option Image: " + optionStructure.getOptionImage());
System.out.println("Option IsCorrectAns: " + optionStructure.isCorrectAns());
System.out.println("Option UUID: " + optionStructure.getUuid());
System.out.println("Question UUID: " + optionStructure.getUuid_question());
System.out.println("Quiz UUID: " + optionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
}
}
}
| public static void main(String[] args) {
Serializer serializer = new Persister();
File source = new File("D:/Quiz.xml");
QuizStructure quiz = null;
try {
quiz = serializer.read(QuizStructure.class, source);
} catch (Exception ex) {
ex.printStackTrace();
}
ArrayList<QuestionStructure> questions = quiz.getQuestions();
System.out.println("Quiz Details:");
System.out.println("Quiz Subject: " + quiz.getSubject());
System.out.println("Quiz Topic: " + quiz.getTopic());
System.out.println("Quiz Description: " + quiz.getDescription());
System.out.println("Quiz Time Limit: " + quiz.getTimeLimit());
System.out.println("Quiz Submission Date: " + quiz.getSubmission_date());
System.out.println("Quiz Due Date: " + quiz.getDue_date());
System.out.println("Quiz Total Questions in Quiz: " + quiz.getTotal_questions_in_quiz());
System.out.println("Quiz Total Questions To Solve: " + quiz.getTotal_questions_to_solve());
System.out.println("---------------------------------------------------");
for (QuestionStructure questionStructure : questions) {
System.out.println("Question: " + questionStructure.getQuestion());
System.out.println("Question Image: " + questionStructure.getQuestionImage());
System.out.println("Question Difficulty: " + questionStructure.getDifficulty());
System.out.println("Question UUID: " + questionStructure.getUuid());
System.out.println("Quiz UUID: " + questionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
//Iterate over each options of the question
ArrayList<OptionStructure> options = quiz.getOptionList();
for (OptionStructure optionStructure : options) {
System.out.println("Option: " + optionStructure.getOption());
System.out.println("Option Image: " + optionStructure.getOptionImage());
System.out.println("Option IsCorrectAns: " + optionStructure.isCorrectAns());
System.out.println("Option UUID: " + optionStructure.getUuid());
System.out.println("Question UUID: " + optionStructure.getUuid_question());
System.out.println("Quiz UUID: " + optionStructure.getUuid_quiz());
System.out.println("---------------------------------------------------");
}
}
}
|
diff --git a/src/be/ibridge/kettle/core/LocalVariables.java b/src/be/ibridge/kettle/core/LocalVariables.java
index bdd126f5..b443bc8f 100644
--- a/src/be/ibridge/kettle/core/LocalVariables.java
+++ b/src/be/ibridge/kettle/core/LocalVariables.java
@@ -1,177 +1,177 @@
package be.ibridge.kettle.core;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* This class is a container for "Local" enrvironment variables.
* This is a singleton. We are going to launch jobs using a customer classloader.
* This will make the variables inside it local.
*
* @author Matt
*/
public class LocalVariables
{
ThreadLocal local;
private static LocalVariables localVariables;
private Map map;
/**
* Create a new KettleVariables variable map in the local variables map for the specified thread.
* @param localThread The local thread to attach to
* @param parentThread The parent thread, null if there is no parent thread. The initial value of the variables will be taken from the variables that are attached to this thread.
* @param sameNamespace true if you want to use the same namespace as the parent (if any) or false if you want to use a new namespace, create a new KettleVariables object.
*/
public KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace)
{
if (parentThread!=null && parentThread.equals(localThread))
{
throw new RuntimeException("local thread can't be the same as the parent thread!");
}
// System.out.println("---> Create new KettleVariables for thread ["+localThread+"]");
// See if the thread already has an entry in the map
//
KettleVariables vars = new KettleVariables(localThread, parentThread);
// Copy the initial values from the parent thread if it is specified
if (parentThread!=null)
{
KettleVariables initialValue = getKettleVariables(parentThread);
if (initialValue!=null)
{
if (sameNamespace)
{
vars = new KettleVariables(localThread, parentThread);
vars.setProperties(initialValue.getProperties());
}
else
{
vars.putAll(initialValue.getProperties());
}
}
else
{
throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]");
}
}
// Before we add this, for debugging, just see if we're not overwriting anything.
// Overwriting is a big No-No
KettleVariables checkVars = (KettleVariables) map.get(localThread);
if (checkVars!=null)
{
- throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]");
+ // throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]");
}
// LogWriter.getInstance().logBasic("LocalVariables!", "---> Store new KettleVariables in key ["+localThread+"], vars.local ["+vars.getLocalThread()+"], vars.parent ["+vars.getParentThread()+"]");
// Put this one in the map, attached to the local thread
map.put(localThread, vars);
return vars;
}
public LocalVariables()
{
map = new Hashtable();
}
public static final LocalVariables getInstance()
{
if (localVariables==null) // Not the first time we call this, see if we have properties for this thread
{
// System.out.println("Init of new local variables object");
localVariables = new LocalVariables();
}
return localVariables;
}
public Map getMap()
{
return map;
}
public static final KettleVariables getKettleVariables()
{
return getInstance().getVariables(Thread.currentThread().toString());
}
public static final KettleVariables getKettleVariables(String thread)
{
return getInstance().getVariables(thread);
}
/**
* Find the KettleVariables in the map, attached to the specified Thread.
* This is not singleton stuff, we return null in case we don't have anything attached to the current thread.
* That makes it easier to find the "missing links"
* @param localThread The thread to look for
* @return The KettleVariables attached to the specified thread.
*/
private KettleVariables getVariables(String localThread)
{
KettleVariables kettleVariables = (KettleVariables) map.get(localThread);
return kettleVariables;
}
public void removeKettleVariables(String thread)
{
removeKettleVariables(thread, 1);
}
/**
* Remove all KettleVariables objects in the map, including the one for this thread, but also the ones with this thread as parent, etc.
* @param thread the grand-parent thread to look for to remove
*/
private void removeKettleVariables(String thread, int level)
{
LogWriter log = LogWriter.getInstance();
List children = getKettleVariablesWithParent(thread);
for (int i=0;i<children.size();i++)
{
String child = (String)children.get(i);
removeKettleVariables(child, level+1);
}
// See if it was in there in the first place...
if (map.get(thread)==null)
{
// We should not ever arrive here...
log.logError("LocalVariables!!!!!!!", "The variables you are trying to remove, do not exist for thread ["+thread+"]");
log.logError("LocalVariables!!!!!!!", "Please report this error to the Kettle developers.");
}
else
{
map.remove(thread);
}
}
private List getKettleVariablesWithParent(String parentThread)
{
List children = new ArrayList();
List values = new ArrayList(map.values());
for (int i=0;i<values.size();i++)
{
KettleVariables kv = (KettleVariables)values.get(i);
if (kv.getParentThread()!=null && kv.getParentThread().equals(parentThread))
{
if (kv.getLocalThread().equals(parentThread))
{
System.out.println("---> !!!! This should not happen! Thread ["+parentThread+"] is linked to itself!");
}
else
{
children.add(kv.getLocalThread());
}
}
}
return children;
}
}
| true | true | public KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace)
{
if (parentThread!=null && parentThread.equals(localThread))
{
throw new RuntimeException("local thread can't be the same as the parent thread!");
}
// System.out.println("---> Create new KettleVariables for thread ["+localThread+"]");
// See if the thread already has an entry in the map
//
KettleVariables vars = new KettleVariables(localThread, parentThread);
// Copy the initial values from the parent thread if it is specified
if (parentThread!=null)
{
KettleVariables initialValue = getKettleVariables(parentThread);
if (initialValue!=null)
{
if (sameNamespace)
{
vars = new KettleVariables(localThread, parentThread);
vars.setProperties(initialValue.getProperties());
}
else
{
vars.putAll(initialValue.getProperties());
}
}
else
{
throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]");
}
}
// Before we add this, for debugging, just see if we're not overwriting anything.
// Overwriting is a big No-No
KettleVariables checkVars = (KettleVariables) map.get(localThread);
if (checkVars!=null)
{
throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]");
}
// LogWriter.getInstance().logBasic("LocalVariables!", "---> Store new KettleVariables in key ["+localThread+"], vars.local ["+vars.getLocalThread()+"], vars.parent ["+vars.getParentThread()+"]");
// Put this one in the map, attached to the local thread
map.put(localThread, vars);
return vars;
}
| public KettleVariables createKettleVariables(String localThread, String parentThread, boolean sameNamespace)
{
if (parentThread!=null && parentThread.equals(localThread))
{
throw new RuntimeException("local thread can't be the same as the parent thread!");
}
// System.out.println("---> Create new KettleVariables for thread ["+localThread+"]");
// See if the thread already has an entry in the map
//
KettleVariables vars = new KettleVariables(localThread, parentThread);
// Copy the initial values from the parent thread if it is specified
if (parentThread!=null)
{
KettleVariables initialValue = getKettleVariables(parentThread);
if (initialValue!=null)
{
if (sameNamespace)
{
vars = new KettleVariables(localThread, parentThread);
vars.setProperties(initialValue.getProperties());
}
else
{
vars.putAll(initialValue.getProperties());
}
}
else
{
throw new RuntimeException("No parent Kettle Variables found for thread ["+parentThread+"], local thread is ["+localThread+"]");
}
}
// Before we add this, for debugging, just see if we're not overwriting anything.
// Overwriting is a big No-No
KettleVariables checkVars = (KettleVariables) map.get(localThread);
if (checkVars!=null)
{
// throw new RuntimeException("There are already variables in the local variables map for ["+localThread+"]");
}
// LogWriter.getInstance().logBasic("LocalVariables!", "---> Store new KettleVariables in key ["+localThread+"], vars.local ["+vars.getLocalThread()+"], vars.parent ["+vars.getParentThread()+"]");
// Put this one in the map, attached to the local thread
map.put(localThread, vars);
return vars;
}
|
diff --git a/common/src/main/java/dk/statsbiblioteket/doms/transformers/common/checksums/ChecksumParser.java b/common/src/main/java/dk/statsbiblioteket/doms/transformers/common/checksums/ChecksumParser.java
index e23e07a..d08f7ff 100644
--- a/common/src/main/java/dk/statsbiblioteket/doms/transformers/common/checksums/ChecksumParser.java
+++ b/common/src/main/java/dk/statsbiblioteket/doms/transformers/common/checksums/ChecksumParser.java
@@ -1,45 +1,45 @@
package dk.statsbiblioteket.doms.transformers.common.checksums;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipInputStream;
/**
* Created by IntelliJ IDEA.
* User: abr
* Date: 7/18/12
* Time: 3:24 PM
* To change this template use File | Settings | File Templates.
*/
public class ChecksumParser {
private Map<String,String> nameChecksumsMap = new HashMap<String, String>();
public ChecksumParser(InputStream checksumsZipStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(checksumsZipStream);
- // This probably only works when the zip-file only contain
+ // This probably only works when the zip-file contains exacly one (1) file
zipInputStream.getNextEntry();
BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
String line;
while ((line = reader.readLine()) != null){
String[] splits = line.split(" ");
String name = splits[1].trim();
String checksum = splits[0].trim();
if (name.endsWith(".log")){
continue;
}
nameChecksumsMap.put(name, checksum);
}
System.out.println(nameChecksumsMap.size());
}
public Map<String, String> getNameChecksumsMap() {
return Collections.unmodifiableMap(nameChecksumsMap);
}
}
| true | true | public ChecksumParser(InputStream checksumsZipStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(checksumsZipStream);
// This probably only works when the zip-file only contain
zipInputStream.getNextEntry();
BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
String line;
while ((line = reader.readLine()) != null){
String[] splits = line.split(" ");
String name = splits[1].trim();
String checksum = splits[0].trim();
if (name.endsWith(".log")){
continue;
}
nameChecksumsMap.put(name, checksum);
}
System.out.println(nameChecksumsMap.size());
}
| public ChecksumParser(InputStream checksumsZipStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(checksumsZipStream);
// This probably only works when the zip-file contains exacly one (1) file
zipInputStream.getNextEntry();
BufferedReader reader = new BufferedReader(new InputStreamReader(zipInputStream));
String line;
while ((line = reader.readLine()) != null){
String[] splits = line.split(" ");
String name = splits[1].trim();
String checksum = splits[0].trim();
if (name.endsWith(".log")){
continue;
}
nameChecksumsMap.put(name, checksum);
}
System.out.println(nameChecksumsMap.size());
}
|
diff --git a/rexster-protocol/src/main/java/com/tinkerpop/rexster/protocol/filter/ScriptFilter.java b/rexster-protocol/src/main/java/com/tinkerpop/rexster/protocol/filter/ScriptFilter.java
index e266da41..463d7c35 100644
--- a/rexster-protocol/src/main/java/com/tinkerpop/rexster/protocol/filter/ScriptFilter.java
+++ b/rexster-protocol/src/main/java/com/tinkerpop/rexster/protocol/filter/ScriptFilter.java
@@ -1,161 +1,177 @@
package com.tinkerpop.rexster.protocol.filter;
import com.tinkerpop.rexster.protocol.msg.GraphSONScriptResponseMessage;
import com.tinkerpop.rexster.protocol.msg.MessageFlag;
import com.tinkerpop.rexster.protocol.msg.MessageTokens;
import com.tinkerpop.rexster.protocol.msg.MessageUtil;
import com.tinkerpop.rexster.server.RexsterApplication;
import com.tinkerpop.rexster.Tokens;
import com.tinkerpop.rexster.protocol.EngineController;
import com.tinkerpop.rexster.protocol.EngineHolder;
import com.tinkerpop.rexster.protocol.RexProSession;
import com.tinkerpop.rexster.protocol.RexProSessions;
import com.tinkerpop.rexster.protocol.msg.ConsoleScriptResponseMessage;
import com.tinkerpop.rexster.protocol.msg.MsgPackScriptResponseMessage;
import com.tinkerpop.rexster.protocol.msg.RexProMessage;
import com.tinkerpop.rexster.protocol.msg.ScriptRequestMessage;
import com.tinkerpop.rexster.protocol.msg.SessionRequestMessage;
import org.apache.log4j.Logger;
import org.glassfish.grizzly.filterchain.BaseFilter;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.filterchain.NextAction;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* Processes a ScriptRequestMessage against the script engine for the channel.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class ScriptFilter extends BaseFilter {
private static final Logger logger = Logger.getLogger(ScriptFilter.class);
private static final EngineController engineController = EngineController.getInstance();
private final RexsterApplication rexsterApplication;
public ScriptFilter(final RexsterApplication rexsterApplication) {
this.rexsterApplication = rexsterApplication;
}
public NextAction handleRead(final FilterChainContext ctx) throws IOException {
final RexProMessage message = ctx.getMessage();
// check message type to be ScriptRequestMessage
// short cut the session stuff
if (message.Flag == MessageFlag.SCRIPT_REQUEST_NO_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
try {
final EngineHolder engineHolder = engineController.getEngineByLanguageName(specificMessage.LanguageName);
final ScriptEngine scriptEngine = engineHolder.getEngine();
final Bindings bindings = scriptEngine.createBindings();
final Bindings rexsterBindings = specificMessage.getBindings();
for (Map.Entry<String,Object> e : rexsterBindings.entrySet()) {
bindings.put(e.getKey(), e.getValue());
}
bindings.put(Tokens.REXPRO_REXSTER_CONTEXT, this.rexsterApplication);
final Object result = scriptEngine.eval(specificMessage.Script, bindings);
final MsgPackScriptResponseMessage msgPackScriptResponseMessage = new MsgPackScriptResponseMessage();
msgPackScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
msgPackScriptResponseMessage.setSessionAsUUID(RexProMessage.EMPTY_SESSION);
msgPackScriptResponseMessage.Request = specificMessage.Request;
msgPackScriptResponseMessage.Results = MsgPackScriptResponseMessage.convertResultToBytes(result);
ctx.write(msgPackScriptResponseMessage);
return ctx.getStopAction();
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
+ ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
+ MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
+ specificMessage.LanguageName, cnfe.toString())));
} catch (Exception e) {
logger.error(e);
+ ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
+ MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
+ specificMessage.LanguageName, e.toString())));
}
}
// below here is all session related requests
if (message.Flag == MessageFlag.SCRIPT_REQUEST_IN_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
final RexProSession session = RexProSessions.getSession(specificMessage.sessionAsUUID().toString());
try {
final Object result = session.evaluate(specificMessage.Script, specificMessage.LanguageName, specificMessage.getBindings());
if (session.getChannel() == SessionRequestMessage.CHANNEL_CONSOLE) {
ctx.write(formatForConsoleChannel(specificMessage, session, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_MSGPACK) {
ctx.write(formatForMsgPackChannel(specificMessage, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_GRAPHSON) {
ctx.write(formatForGraphSONChannel(specificMessage, result));
}
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
+ ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
+ MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
+ specificMessage.LanguageName, cnfe.toString())));
} catch (IOException ioe) {
logger.error(ioe);
+ ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
+ MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
+ specificMessage.LanguageName, ioe.toString())));
} catch (Throwable t) {
logger.error(t);
+ //don't leave the client hanging!
+ ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
+ MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
+ specificMessage.LanguageName, t.toString())));
}
return ctx.getStopAction();
}
return ctx.getInvokeAction();
}
private static GraphSONScriptResponseMessage formatForGraphSONChannel(final ScriptRequestMessage specificMessage, final Object result) throws Exception {
final GraphSONScriptResponseMessage graphSONScriptResponseMessage = new GraphSONScriptResponseMessage();
graphSONScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
graphSONScriptResponseMessage.Session = specificMessage.Session;
graphSONScriptResponseMessage.Request = specificMessage.Request;
graphSONScriptResponseMessage.Results = GraphSONScriptResponseMessage.convertResultToBytes(result);
return graphSONScriptResponseMessage;
}
private static MsgPackScriptResponseMessage formatForMsgPackChannel(final ScriptRequestMessage specificMessage, final Object result) throws Exception {
final MsgPackScriptResponseMessage msgPackScriptResponseMessage = new MsgPackScriptResponseMessage();
msgPackScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
msgPackScriptResponseMessage.Session = specificMessage.Session;
msgPackScriptResponseMessage.Request = specificMessage.Request;
msgPackScriptResponseMessage.Results = MsgPackScriptResponseMessage.convertResultToBytes(result);
return msgPackScriptResponseMessage;
}
private static ConsoleScriptResponseMessage formatForConsoleChannel(final ScriptRequestMessage specificMessage, final RexProSession session, final Object result) throws Exception {
final ConsoleScriptResponseMessage consoleScriptResponseMessage = new ConsoleScriptResponseMessage();
consoleScriptResponseMessage.Bindings = ConsoleScriptResponseMessage.convertBindingsToConsoleLineByteArray(session.getBindings());
consoleScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
consoleScriptResponseMessage.Session = specificMessage.Session;
consoleScriptResponseMessage.Request = specificMessage.Request;
final List<String> consoleLines = ConsoleScriptResponseMessage.convertResultToConsoleLines(result);
consoleScriptResponseMessage.ConsoleLines = new String[consoleLines.size()];
consoleLines.toArray(consoleScriptResponseMessage.ConsoleLines);
return consoleScriptResponseMessage;
}
}
| false | true | public NextAction handleRead(final FilterChainContext ctx) throws IOException {
final RexProMessage message = ctx.getMessage();
// check message type to be ScriptRequestMessage
// short cut the session stuff
if (message.Flag == MessageFlag.SCRIPT_REQUEST_NO_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
try {
final EngineHolder engineHolder = engineController.getEngineByLanguageName(specificMessage.LanguageName);
final ScriptEngine scriptEngine = engineHolder.getEngine();
final Bindings bindings = scriptEngine.createBindings();
final Bindings rexsterBindings = specificMessage.getBindings();
for (Map.Entry<String,Object> e : rexsterBindings.entrySet()) {
bindings.put(e.getKey(), e.getValue());
}
bindings.put(Tokens.REXPRO_REXSTER_CONTEXT, this.rexsterApplication);
final Object result = scriptEngine.eval(specificMessage.Script, bindings);
final MsgPackScriptResponseMessage msgPackScriptResponseMessage = new MsgPackScriptResponseMessage();
msgPackScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
msgPackScriptResponseMessage.setSessionAsUUID(RexProMessage.EMPTY_SESSION);
msgPackScriptResponseMessage.Request = specificMessage.Request;
msgPackScriptResponseMessage.Results = MsgPackScriptResponseMessage.convertResultToBytes(result);
ctx.write(msgPackScriptResponseMessage);
return ctx.getStopAction();
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
} catch (Exception e) {
logger.error(e);
}
}
// below here is all session related requests
if (message.Flag == MessageFlag.SCRIPT_REQUEST_IN_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
final RexProSession session = RexProSessions.getSession(specificMessage.sessionAsUUID().toString());
try {
final Object result = session.evaluate(specificMessage.Script, specificMessage.LanguageName, specificMessage.getBindings());
if (session.getChannel() == SessionRequestMessage.CHANNEL_CONSOLE) {
ctx.write(formatForConsoleChannel(specificMessage, session, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_MSGPACK) {
ctx.write(formatForMsgPackChannel(specificMessage, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_GRAPHSON) {
ctx.write(formatForGraphSONChannel(specificMessage, result));
}
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
} catch (IOException ioe) {
logger.error(ioe);
} catch (Throwable t) {
logger.error(t);
}
return ctx.getStopAction();
}
return ctx.getInvokeAction();
}
| public NextAction handleRead(final FilterChainContext ctx) throws IOException {
final RexProMessage message = ctx.getMessage();
// check message type to be ScriptRequestMessage
// short cut the session stuff
if (message.Flag == MessageFlag.SCRIPT_REQUEST_NO_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
try {
final EngineHolder engineHolder = engineController.getEngineByLanguageName(specificMessage.LanguageName);
final ScriptEngine scriptEngine = engineHolder.getEngine();
final Bindings bindings = scriptEngine.createBindings();
final Bindings rexsterBindings = specificMessage.getBindings();
for (Map.Entry<String,Object> e : rexsterBindings.entrySet()) {
bindings.put(e.getKey(), e.getValue());
}
bindings.put(Tokens.REXPRO_REXSTER_CONTEXT, this.rexsterApplication);
final Object result = scriptEngine.eval(specificMessage.Script, bindings);
final MsgPackScriptResponseMessage msgPackScriptResponseMessage = new MsgPackScriptResponseMessage();
msgPackScriptResponseMessage.Flag = MessageFlag.SCRIPT_RESPONSE_COMPLETE_MESSAGE;
msgPackScriptResponseMessage.setSessionAsUUID(RexProMessage.EMPTY_SESSION);
msgPackScriptResponseMessage.Request = specificMessage.Request;
msgPackScriptResponseMessage.Results = MsgPackScriptResponseMessage.convertResultToBytes(result);
ctx.write(msgPackScriptResponseMessage);
return ctx.getStopAction();
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, cnfe.toString())));
} catch (Exception e) {
logger.error(e);
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, e.toString())));
}
}
// below here is all session related requests
if (message.Flag == MessageFlag.SCRIPT_REQUEST_IN_SESSION) {
final ScriptRequestMessage specificMessage = (ScriptRequestMessage) message;
final RexProSession session = RexProSessions.getSession(specificMessage.sessionAsUUID().toString());
try {
final Object result = session.evaluate(specificMessage.Script, specificMessage.LanguageName, specificMessage.getBindings());
if (session.getChannel() == SessionRequestMessage.CHANNEL_CONSOLE) {
ctx.write(formatForConsoleChannel(specificMessage, session, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_MSGPACK) {
ctx.write(formatForMsgPackChannel(specificMessage, result));
} else if (session.getChannel() == SessionRequestMessage.CHANNEL_GRAPHSON) {
ctx.write(formatForGraphSONChannel(specificMessage, result));
}
} catch (ScriptException se) {
logger.warn("Could not process script [" + specificMessage.Script + "] for language ["
+ specificMessage.LanguageName + "] on session [" + message.Session
+ "] and request [" + message.Request + "]");
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, se.getMessage())));
return ctx.getStopAction();
} catch (ClassNotFoundException cnfe) {
logger.error(cnfe);
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, cnfe.toString())));
} catch (IOException ioe) {
logger.error(ioe);
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, ioe.toString())));
} catch (Throwable t) {
logger.error(t);
//don't leave the client hanging!
ctx.write(MessageUtil.createErrorResponse(message.Request, RexProMessage.EMPTY_SESSION_AS_BYTES,
MessageFlag.ERROR_SCRIPT_FAILURE, String.format(MessageTokens.ERROR_IN_SCRIPT_PROCESSING,
specificMessage.LanguageName, t.toString())));
}
return ctx.getStopAction();
}
return ctx.getInvokeAction();
}
|
diff --git a/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java b/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
index 903782f..532ca28 100644
--- a/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
+++ b/src/me/shanked/nicatronTg/darklight/view/VulnerabilityOutputGenerator.java
@@ -1,98 +1,98 @@
package me.shanked.nicatronTg.darklight.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
/**
* Generates an html file using the template and current stats from the engine
*
* @author Isaac Grant
* @author Lucas Nicodemus
* @version .1
*
*/
public class VulnerabilityOutputGenerator {
private HashMap<String, String> fixedIssues = new HashMap<String, String>();
/**
*
* @return The fixedIssues HashMap used to format the template
*/
public HashMap<String, String> getFixedIssues() {
return fixedIssues;
}
/**
* Set the fixedIssues HashMap that the template is formatted with
* @param fixedIssues HashMap to format the template with
*/
public void setFixedIssues(HashMap<String, String> fixedIssues) {
this.fixedIssues = fixedIssues;
}
public VulnerabilityOutputGenerator() {
}
/**
* Format the template with the given issues and issue count
* @throws InvalidTemplateException The template does not contain the require flags ([fixedcount] and [issues])
* @throws IOException Template does not exist, or error reading/writing formatted template
*/
public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
File f = new File(new File("."), templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
- template += scanner.nextLine();
+ template += scanner.nextLine() + "\n";
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
- String tempString = "<li class=\"span10 offset2\">" + key + " - " + fixedIssues.get(key) + "</li>";
+ String tempString = "<li>" + key + " - " + fixedIssues.get(key) + "</li>\n";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
File outputFile = new File(new File("."), outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
class InvalidTemplateException extends Exception {
private static final long serialVersionUID = 8843494291724959640L;
public InvalidTemplateException() { }
public InvalidTemplateException(String msg) {
super(msg);
}
}
}
| false | true | public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
File f = new File(new File("."), templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
template += scanner.nextLine();
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
String tempString = "<li class=\"span10 offset2\">" + key + " - " + fixedIssues.get(key) + "</li>";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
File outputFile = new File(new File("."), outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
| public void writeFixedIssues(String templatePath, String outputPath) throws InvalidTemplateException, IOException {
File f = new File(new File("."), templatePath);
if (!f.exists()) {
throw new FileNotFoundException("Score template file missing! File " + templatePath + " does not exist.");
}
Scanner scanner = new Scanner(new FileInputStream(f));
String template = "";
while (scanner.hasNextLine()) {
template += scanner.nextLine() + "\n";
}
scanner.close();
if (!template.contains("[fixedcount]") || !template.contains("[issues]")) {
throw new InvalidTemplateException("The specified input template, " + templatePath + ", did not contain the required formatting tags and cannot be parsed.");
}
template = template.replace("[fixedcount]", "" + fixedIssues.size());
String tempIssuesList = "";
for (String key : fixedIssues.keySet()) {
String tempString = "<li>" + key + " - " + fixedIssues.get(key) + "</li>\n";
tempIssuesList += tempString;
}
template = template.replace("[issues]", tempIssuesList);
File outputFile = new File(new File("."), outputPath);
if (outputFile.exists()) {
outputFile.delete();
}
FileWriter fw = new FileWriter(outputFile);
fw.write(template);
fw.close();
}
|
diff --git a/components/interp/interp-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java b/components/interp/interp-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java
index 3f4e176af..1778264bc 100644
--- a/components/interp/interp-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java
+++ b/components/interp/interp-core/src/main/java/org/torquebox/interp/core/RubyRuntimeFactoryImpl.java
@@ -1,440 +1,441 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.torquebox.interp.core;
import java.io.File;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.jboss.beans.metadata.api.annotations.Create;
import org.jboss.kernel.Kernel;
import org.jboss.logging.Logger;
import org.jboss.vfs.TempFileProvider;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
import org.jruby.CompatVersion;
import org.jruby.Ruby;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyModule;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.util.ClassCache;
import org.torquebox.interp.spi.RubyRuntimeFactory;
import org.torquebox.interp.spi.RuntimeInitializer;
/**
* Default Ruby runtime interpreter factory implementation.
*
* @author Bob McWhirter <[email protected]>
*/
public class RubyRuntimeFactoryImpl implements RubyRuntimeFactory {
private static final Logger log = Logger.getLogger(RubyRuntimeFactoryImpl.class);
/** MC Kernel. */
private Kernel kernel;
/** Re-usable initializer. */
private RuntimeInitializer initializer;
/** ClassLoader for interpreter. */
private ClassLoader classLoader;
/** Shared interpreter class cache. */
private ClassCache<?> classCache;
/** Application name. */
private String applicationName;
/** Load paths for the interpreter. */
private List<String> loadPaths;
/** Output stream for the interpreter. */
private PrintStream outputStream = System.out;
/** Error stream for the interpreter. */
private PrintStream errorStream = System.err;
/** JRUBY_HOME. */
private String jrubyHome;
/** GEM_PATH. */
private String gemPath;
/** Should environment $JRUBY_HOME be considered? */
private boolean useJRubyHomeEnvVar = true;
/** Additional application environment variables. */
private Map<String, String> applicationEnvironment;
/** Undisposed runtimes created by this factory. */
private Set<Ruby> undisposed = new HashSet<Ruby>();
/** Ruby compatibility version. */
private CompatVersion rubyVersion;
/**
* Construct.
*/
public RubyRuntimeFactoryImpl() {
this(null);
}
/**
* Construct with an initializer.
*
* @param initializer
* The initializer (or null) to use for each created runtime.
*/
public RubyRuntimeFactoryImpl(RuntimeInitializer initializer) {
this.initializer = initializer;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getApplicationName() {
return this.applicationName;
}
public void setGemPath(String gemPath) {
this.gemPath = gemPath;
}
public String getGemPath() {
return this.gemPath;
}
public void setJRubyHome(String jrubyHome) {
this.jrubyHome = jrubyHome;
}
public String getJRubyHome() {
return this.jrubyHome;
}
public void setUseJRubyHomeEnvVar(boolean useJRubyEnvVar) {
this.useJRubyHomeEnvVar = useJRubyEnvVar;
}
public boolean useJRubyHomeEnvVar() {
return this.useJRubyHomeEnvVar;
}
/**
* Inject the Microcontainer kernel.
*
* @param kernel
* The microcontainer kernel.
*/
public void setKernel(Kernel kernel) {
this.kernel = kernel;
}
/**
* Retrieve the Microcontainer kernel.
*
* @return The microcontainer kernel.
*/
public Kernel getKernel() {
return this.kernel;
}
/**
* Set the interpreter classloader.
*
* @param classLoader
* The classloader.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Retrieve the interpreter classloader.
*
* @return The classloader.
*/
public ClassLoader getClassLoader() {
if (this.classLoader != null) {
return this.classLoader;
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null) {
return cl;
}
return getClass().getClassLoader();
}
/** Set the Ruby compatibility version.
*
* @param rubyVersion The version.
*/
public void setRubyVersion(CompatVersion rubyVersion) {
this.rubyVersion = rubyVersion;
}
/** Retrieve the Ruby compatibility version.
*
* @return The version.
*/
public CompatVersion getRubyVersion() {
return this.rubyVersion;
}
/**
* Set the application-specific environment additions.
*
* @param applicationEnvironment
* The environment.
*/
public void setApplicationEnvironment(Map<String, String> applicationEnvironment) {
this.applicationEnvironment = applicationEnvironment;
}
/**
* Retrieve the application-specific environment additions.
*
* @return The environment.
*/
public Map<String, String> getApplicationEnvironment() {
return this.applicationEnvironment;
}
/**
* Create a new instance of a fully-initialized runtime.
*/
@Create(ignored = true)
public synchronized Ruby create() throws Exception {
RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig();
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(getClassLoader());
}
config.setClassCache(classCache);
config.setLoadServiceCreator(new VFSLoadServiceCreator());
config.setCompatVersion( this.rubyVersion );
String jrubyHome = this.jrubyHome;
if (jrubyHome == null) {
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null && this.useJRubyHomeEnvVar && !"true".equals(System.getProperty("jruby_home.env.ignore"))) {
jrubyHome = System.getenv("JRUBY_HOME");
if (jrubyHome != null) {
if (!new File(jrubyHome).exists()) {
jrubyHome = null;
}
}
}
if (jrubyHome == null) {
String jbossHome = System.getProperty("jboss.home");
if (jbossHome != null) {
File candidatePath = new File(jbossHome, "../jruby");
if (candidatePath.exists() && candidatePath.isDirectory()) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
}
if (jrubyHome == null) {
jrubyHome = RubyInstanceConfig.class.getResource("/META-INF/jruby.home").toURI().getSchemeSpecificPart();
if (jrubyHome.startsWith("file:") && jrubyHome.contains("!/")) {
int slashLoc = jrubyHome.indexOf('/');
int bangLoc = jrubyHome.indexOf('!');
String jarPath = jrubyHome.substring(slashLoc, bangLoc);
String extraPath = jrubyHome.substring(bangLoc + 1);
VirtualFile vfsJar = VFS.getChild(jarPath);
if (vfsJar.exists()) {
if (!vfsJar.isDirectory()) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
TempFileProvider tempFileProvider = TempFileProvider.create("jruby.home", executor);
VFS.mountZip(vfsJar, vfsJar, tempFileProvider);
}
if (vfsJar.isDirectory()) {
VirtualFile vfsJrubyHome = vfsJar.getChild(extraPath);
if (vfsJrubyHome.exists()) {
jrubyHome = vfsJrubyHome.toURL().toExternalForm();
}
}
}
}
// jrubyHome = jrubyHome.replaceAll( "^file:", "vfs:" );
// jrubyHome = jrubyHome.replaceAll( "!/", "/" );
}
// System.err.println( "JRUBY_HOME=>[" + jrubyHome + "]" );
if (jrubyHome != null) {
config.setJRubyHome(jrubyHome);
}
config.setEnvironment(createEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
if (this.loadPaths != null) {
loadPath.addAll(this.loadPaths);
}
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
runtime.getLoadService().require("rubygems");
+ runtime.evalScriptlet("begin; require 'vfs'; puts 'Loaded VFS'; rescue Exception; puts 'Failed to load VFS'; end");
return runtime;
}
@Override
public synchronized void dispose(Ruby instance) {
if (undisposed.remove(instance)) {
instance.tearDown(false);
}
}
private void setUpConstants(Ruby runtime, String applicationName) {
runtime.evalScriptlet("require %q(org/torquebox/interp/core/runtime_constants)\n");
RubyModule jbossModule = runtime.getClassFromPath("JBoss");
JavaEmbedUtils.invokeMethod(runtime, jbossModule, "setup_constants", new Object[] { applicationName }, void.class);
}
private void injectKernel(Ruby runtime) {
runtime.evalScriptlet("require %q(org/torquebox/interp/core/kernel)");
RubyModule jbossKernel = runtime.getClassFromPath("TorqueBox::Kernel");
JavaEmbedUtils.invokeMethod(runtime, jbossKernel, "kernel=", new Object[] { this.kernel }, void.class);
}
protected Map<String, String> createEnvironment() {
Map<String, String> env = new HashMap<String, String>();
env.putAll(System.getenv());
String path = (String) env.get("PATH");
if (path == null) {
env.put("PATH", "");
}
if (this.gemPath != null) {
env.put("GEM_PATH", this.gemPath);
env.put("GEM_HOME", this.gemPath);
}
if (this.applicationEnvironment != null) {
env.putAll(this.applicationEnvironment);
}
// System.err.println( "environment=>" + env );
return env;
}
/**
* Set the interpreter output stream.
*
* @param outputStream
* The output stream.
*/
public void setOutput(PrintStream outputStream) {
this.outputStream = outputStream;
}
/**
* Retrieve the interpreter output stream.
*
* @return The output stream.
*/
public PrintStream getOutput() {
return this.outputStream;
}
/**
* Set the interpreter error stream.
*
* @param errorStream
* The error stream.
*/
public void setError(PrintStream errorStream) {
this.errorStream = errorStream;
}
/**
* Retrieve the interpreter error stream.
*
* @return The error stream.
*/
public PrintStream getError() {
return this.errorStream;
}
/**
* Set the interpreter load paths.
*
* <p>
* Load paths may be either real filesystem paths or VFS URLs
* </p>
*
* @param loadPaths
* The list of load paths.
*/
public void setLoadPaths(List<String> loadPaths) {
this.loadPaths = loadPaths;
}
/**
* Retrieve the interpreter load paths.
*
* @return The list of load paths.
*/
public List<String> getLoadPaths() {
return this.loadPaths;
}
public synchronized void destroy() {
for (Ruby ruby : undisposed) {
dispose(ruby);
}
}
}
| true | true | public synchronized Ruby create() throws Exception {
RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig();
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(getClassLoader());
}
config.setClassCache(classCache);
config.setLoadServiceCreator(new VFSLoadServiceCreator());
config.setCompatVersion( this.rubyVersion );
String jrubyHome = this.jrubyHome;
if (jrubyHome == null) {
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null && this.useJRubyHomeEnvVar && !"true".equals(System.getProperty("jruby_home.env.ignore"))) {
jrubyHome = System.getenv("JRUBY_HOME");
if (jrubyHome != null) {
if (!new File(jrubyHome).exists()) {
jrubyHome = null;
}
}
}
if (jrubyHome == null) {
String jbossHome = System.getProperty("jboss.home");
if (jbossHome != null) {
File candidatePath = new File(jbossHome, "../jruby");
if (candidatePath.exists() && candidatePath.isDirectory()) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
}
if (jrubyHome == null) {
jrubyHome = RubyInstanceConfig.class.getResource("/META-INF/jruby.home").toURI().getSchemeSpecificPart();
if (jrubyHome.startsWith("file:") && jrubyHome.contains("!/")) {
int slashLoc = jrubyHome.indexOf('/');
int bangLoc = jrubyHome.indexOf('!');
String jarPath = jrubyHome.substring(slashLoc, bangLoc);
String extraPath = jrubyHome.substring(bangLoc + 1);
VirtualFile vfsJar = VFS.getChild(jarPath);
if (vfsJar.exists()) {
if (!vfsJar.isDirectory()) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
TempFileProvider tempFileProvider = TempFileProvider.create("jruby.home", executor);
VFS.mountZip(vfsJar, vfsJar, tempFileProvider);
}
if (vfsJar.isDirectory()) {
VirtualFile vfsJrubyHome = vfsJar.getChild(extraPath);
if (vfsJrubyHome.exists()) {
jrubyHome = vfsJrubyHome.toURL().toExternalForm();
}
}
}
}
// jrubyHome = jrubyHome.replaceAll( "^file:", "vfs:" );
// jrubyHome = jrubyHome.replaceAll( "!/", "/" );
}
// System.err.println( "JRUBY_HOME=>[" + jrubyHome + "]" );
if (jrubyHome != null) {
config.setJRubyHome(jrubyHome);
}
config.setEnvironment(createEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
if (this.loadPaths != null) {
loadPath.addAll(this.loadPaths);
}
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
runtime.getLoadService().require("rubygems");
return runtime;
}
| public synchronized Ruby create() throws Exception {
RubyInstanceConfig config = new TorqueBoxRubyInstanceConfig();
if (this.classCache == null) {
this.classCache = new ClassCache<Object>(getClassLoader());
}
config.setClassCache(classCache);
config.setLoadServiceCreator(new VFSLoadServiceCreator());
config.setCompatVersion( this.rubyVersion );
String jrubyHome = this.jrubyHome;
if (jrubyHome == null) {
jrubyHome = System.getProperty("jruby.home");
if (jrubyHome == null && this.useJRubyHomeEnvVar && !"true".equals(System.getProperty("jruby_home.env.ignore"))) {
jrubyHome = System.getenv("JRUBY_HOME");
if (jrubyHome != null) {
if (!new File(jrubyHome).exists()) {
jrubyHome = null;
}
}
}
if (jrubyHome == null) {
String jbossHome = System.getProperty("jboss.home");
if (jbossHome != null) {
File candidatePath = new File(jbossHome, "../jruby");
if (candidatePath.exists() && candidatePath.isDirectory()) {
jrubyHome = candidatePath.getAbsolutePath();
}
}
}
}
if (jrubyHome == null) {
jrubyHome = RubyInstanceConfig.class.getResource("/META-INF/jruby.home").toURI().getSchemeSpecificPart();
if (jrubyHome.startsWith("file:") && jrubyHome.contains("!/")) {
int slashLoc = jrubyHome.indexOf('/');
int bangLoc = jrubyHome.indexOf('!');
String jarPath = jrubyHome.substring(slashLoc, bangLoc);
String extraPath = jrubyHome.substring(bangLoc + 1);
VirtualFile vfsJar = VFS.getChild(jarPath);
if (vfsJar.exists()) {
if (!vfsJar.isDirectory()) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
TempFileProvider tempFileProvider = TempFileProvider.create("jruby.home", executor);
VFS.mountZip(vfsJar, vfsJar, tempFileProvider);
}
if (vfsJar.isDirectory()) {
VirtualFile vfsJrubyHome = vfsJar.getChild(extraPath);
if (vfsJrubyHome.exists()) {
jrubyHome = vfsJrubyHome.toURL().toExternalForm();
}
}
}
}
// jrubyHome = jrubyHome.replaceAll( "^file:", "vfs:" );
// jrubyHome = jrubyHome.replaceAll( "!/", "/" );
}
// System.err.println( "JRUBY_HOME=>[" + jrubyHome + "]" );
if (jrubyHome != null) {
config.setJRubyHome(jrubyHome);
}
config.setEnvironment(createEnvironment());
config.setOutput(getOutput());
config.setError(getError());
List<String> loadPath = new ArrayList<String>();
if (this.loadPaths != null) {
loadPath.addAll(this.loadPaths);
}
Ruby runtime = JavaEmbedUtils.initialize(loadPath, config);
if (this.initializer != null) {
this.initializer.initialize(runtime);
}
injectKernel(runtime);
setUpConstants(runtime, this.applicationName);
runtime.getLoadService().require("rubygems");
runtime.evalScriptlet("begin; require 'vfs'; puts 'Loaded VFS'; rescue Exception; puts 'Failed to load VFS'; end");
return runtime;
}
|
diff --git a/src/net/gamerservices/npcx/myNPC.java b/src/net/gamerservices/npcx/myNPC.java
index d3608c1..80e7ada 100644
--- a/src/net/gamerservices/npcx/myNPC.java
+++ b/src/net/gamerservices/npcx/myNPC.java
@@ -1,51 +1,51 @@
package net.gamerservices.npcx;
import java.util.HashMap;
import redecouverte.npcspawner.BasicHumanNpc;
public class myNPC {
public npcx parent;
public String name = "dummy";
public String id = "0";
String category = "container";
public BasicHumanNpc npc;
public mySpawngroup spawngroup;
public HashMap<String, myTriggerword> triggerwords = new HashMap<String, myTriggerword>();
myNPC(npcx parent, HashMap<String, myTriggerword> triggerwords)
{
this.parent = parent;
this.triggerwords = triggerwords;
}
public void parseChat(myPlayer myplayer, String message)
{
int count = 0;
//myplayer.player.sendMessage("Parsing:" + message + ":" + Integer.toString(this.triggerwords.size()));
String message2=message+" ";
for (String word : message2.split(" "))
{
if(count == 0)
{
for (myTriggerword tw : triggerwords.values())
{
//myplayer.player.sendMessage("Test:" + word + ":"+ tw.word);
- if (word.matches(tw.word))
+ if (word.toLowerCase().contains(tw.word.toLowerCase()))
{
myplayer.player.sendMessage(npc.getName() + " says to you, '"+ tw.response +"'");
count++;
}
}
}
}
if (count == 0)
{
myplayer.player.sendMessage(npc.getName() + " says to you, 'I'm sorry. I'm rather busy right now.'");
}
}
}
| true | true | public void parseChat(myPlayer myplayer, String message)
{
int count = 0;
//myplayer.player.sendMessage("Parsing:" + message + ":" + Integer.toString(this.triggerwords.size()));
String message2=message+" ";
for (String word : message2.split(" "))
{
if(count == 0)
{
for (myTriggerword tw : triggerwords.values())
{
//myplayer.player.sendMessage("Test:" + word + ":"+ tw.word);
if (word.matches(tw.word))
{
myplayer.player.sendMessage(npc.getName() + " says to you, '"+ tw.response +"'");
count++;
}
}
}
}
if (count == 0)
{
myplayer.player.sendMessage(npc.getName() + " says to you, 'I'm sorry. I'm rather busy right now.'");
}
}
| public void parseChat(myPlayer myplayer, String message)
{
int count = 0;
//myplayer.player.sendMessage("Parsing:" + message + ":" + Integer.toString(this.triggerwords.size()));
String message2=message+" ";
for (String word : message2.split(" "))
{
if(count == 0)
{
for (myTriggerword tw : triggerwords.values())
{
//myplayer.player.sendMessage("Test:" + word + ":"+ tw.word);
if (word.toLowerCase().contains(tw.word.toLowerCase()))
{
myplayer.player.sendMessage(npc.getName() + " says to you, '"+ tw.response +"'");
count++;
}
}
}
}
if (count == 0)
{
myplayer.player.sendMessage(npc.getName() + " says to you, 'I'm sorry. I'm rather busy right now.'");
}
}
|
diff --git a/core/src/main/java/org/infinispan/marshall/AbstractMarshaller.java b/core/src/main/java/org/infinispan/marshall/AbstractMarshaller.java
index 06b737394e..759e21a0e5 100644
--- a/core/src/main/java/org/infinispan/marshall/AbstractMarshaller.java
+++ b/core/src/main/java/org/infinispan/marshall/AbstractMarshaller.java
@@ -1,24 +1,26 @@
package org.infinispan.marshall;
import org.infinispan.io.ExposedByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Abstract marshaller
*
* @author Manik Surtani
* @since 4.0
*/
public abstract class AbstractMarshaller implements Marshaller {
public Object objectFromInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {
- int len = inputStream.available();
+ // TODO: available() call commented until https://issues.apache.org/jira/browse/HTTPCORE-199 httcore-nio issue is fixed.
+ // int len = inputStream.available();
+ int len = 1024;
ExposedByteArrayOutputStream bytes = new ExposedByteArrayOutputStream(len);
byte[] buf = new byte[Math.min(len, 1024)];
int bytesRead;
while ((bytesRead = inputStream.read(buf, 0, buf.length)) != -1) bytes.write(buf, 0, bytesRead);
return objectFromByteBuffer(bytes.getRawBuffer(), 0, bytes.size());
}
}
| true | true | public Object objectFromInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {
int len = inputStream.available();
ExposedByteArrayOutputStream bytes = new ExposedByteArrayOutputStream(len);
byte[] buf = new byte[Math.min(len, 1024)];
int bytesRead;
while ((bytesRead = inputStream.read(buf, 0, buf.length)) != -1) bytes.write(buf, 0, bytesRead);
return objectFromByteBuffer(bytes.getRawBuffer(), 0, bytes.size());
}
| public Object objectFromInputStream(InputStream inputStream) throws IOException, ClassNotFoundException {
// TODO: available() call commented until https://issues.apache.org/jira/browse/HTTPCORE-199 httcore-nio issue is fixed.
// int len = inputStream.available();
int len = 1024;
ExposedByteArrayOutputStream bytes = new ExposedByteArrayOutputStream(len);
byte[] buf = new byte[Math.min(len, 1024)];
int bytesRead;
while ((bytesRead = inputStream.read(buf, 0, buf.length)) != -1) bytes.write(buf, 0, bytesRead);
return objectFromByteBuffer(bytes.getRawBuffer(), 0, bytes.size());
}
|
diff --git a/JavaSource/org/unitime/timetable/solver/exam/ui/ExamProposedChange.java b/JavaSource/org/unitime/timetable/solver/exam/ui/ExamProposedChange.java
index d0368597..31a906f3 100644
--- a/JavaSource/org/unitime/timetable/solver/exam/ui/ExamProposedChange.java
+++ b/JavaSource/org/unitime/timetable/solver/exam/ui/ExamProposedChange.java
@@ -1,278 +1,278 @@
package org.unitime.timetable.solver.exam.ui;
import java.io.Serializable;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.unitime.timetable.model.PreferenceLevel;
import org.unitime.timetable.solver.interactive.ClassAssignmentDetails;
import net.sf.cpsolver.exam.model.Exam;
import net.sf.cpsolver.exam.model.ExamModel;
import net.sf.cpsolver.exam.model.ExamPlacement;
public class ExamProposedChange implements Serializable, Comparable<ExamProposedChange> {
private Vector<ExamAssignmentInfo> iAssignments = null;
private Vector<ExamAssignment> iConflicts = null;
private Hashtable<Long,ExamAssignment> iInitials = null;
private double iValue = 0;
private int iNrAssigned = 0;
public ExamProposedChange() {
iAssignments = new Vector(); iConflicts = new Vector(); iInitials = new Hashtable();
}
public ExamProposedChange(ExamModel model, Hashtable<Exam,ExamPlacement> initialAssignment, Hashtable<Exam,ExamAssignment> initialInfo, Collection<ExamPlacement> conflicts, Vector<Exam> resolvedExams) {
iValue = model.getTotalValue(); iNrAssigned = model.nrAssignedVariables();
if (conflicts!=null) {
iConflicts = new Vector();
for (ExamPlacement conflict : conflicts) iConflicts.add(initialInfo.get((Exam)conflict.variable()));
}
iAssignments = new Vector();
iInitials = new Hashtable();
for (Exam exam : resolvedExams) {
ExamPlacement current = (ExamPlacement)exam.getAssignment();
ExamPlacement initial = initialAssignment.get(exam);
if (initial==null) {
iAssignments.add(new ExamAssignmentInfo(exam,current));
} else if (!initial.equals(current)) {
iAssignments.add(new ExamAssignmentInfo(exam,current));
iInitials.put(exam.getId(),initialInfo.get(exam));
}
}
for (Enumeration e=model.assignedVariables().elements();e.hasMoreElements();) {
Exam exam = (Exam)e.nextElement();
if (resolvedExams.contains(exam)) continue;
ExamPlacement current = (ExamPlacement)exam.getAssignment();
ExamPlacement initial = initialAssignment.get(exam);
if (initial==null) {
iAssignments.add(new ExamAssignmentInfo(exam,current));
} else if (!initial.equals(current)) {
iAssignments.add(new ExamAssignmentInfo(exam,current));
iInitials.put(exam.getId(),initialInfo.get(exam));
}
}
}
public void addChange(ExamAssignmentInfo change, ExamAssignment initial) {
for (ExamAssignment assignment : iAssignments) {
if (assignment.getExamId().equals(change.getExamId())) {
iAssignments.remove(assignment); iInitials.remove(assignment.getExamId()); break;
}
}
for (ExamAssignment conflict : iAssignments) {
if (conflict.getExamId().equals(change.getExamId())) {
iConflicts.remove(conflict); break;
}
}
if (initial!=null && initial.assignmentEquals(change)) return;
if (change.getPeriodId()!=null) {
iAssignments.add(change);
if (initial!=null && initial.getPeriodId()!=null)
iInitials.put(initial.getExamId(),initial);
} else {
iConflicts.add(initial);
}
}
public boolean isEmpty() {
return iConflicts.isEmpty() && iAssignments.isEmpty();
}
public boolean isBetter(ExamModel model) {
if (iNrAssigned>model.nrAssignedVariables()) return true;
if (iNrAssigned==model.nrAssignedVariables() && iValue<model.getTotalValue()) return true;
return false;
}
public Collection<ExamAssignment> getConflicts() { return iConflicts; }
public Collection<ExamAssignmentInfo> getAssignments() { return iAssignments; }
public Hashtable<Long,ExamAssignment> getAssignmentTable() {
Hashtable<Long,ExamAssignment> table = new Hashtable();
try {
for (ExamAssignment conflict : iConflicts)
table.put(conflict.getExamId(), new ExamAssignment(conflict.getExam(),null,null));
} catch (Exception e) {}
for (ExamAssignment assignment : iAssignments)
table.put(assignment.getExamId(), assignment);
return table;
}
public ExamAssignment getInitial(ExamAssignment current) { return iInitials.get(current.getExamId()); }
public ExamAssignmentInfo getCurrent(ExamInfo exam) {
return getCurrent(exam.getExamId());
}
public ExamAssignmentInfo getCurrent(Long examId) {
for (ExamAssignmentInfo assignment : iAssignments)
if (assignment.getExamId().equals(examId)) return assignment;
return null;
}
public ExamAssignment getConflict(ExamInfo exam) {
return getConflict(exam.getExamId());
}
public ExamAssignment getConflict(Long examId) {
for (ExamAssignment conflict : iConflicts)
if (conflict.getExamId().equals(examId)) return conflict;
return null;
}
public ExamAssignment getInitial(Long currentId) { return iInitials.get(currentId); }
public int getNrAssigned() { return iAssignments.size(); }
public int getNrUnassigned() { return iConflicts.size(); }
public double getValue() {
double value = 0;
for (ExamAssignment conflict : iConflicts) value -= conflict.getPlacementValue();
for (ExamAssignment current : iAssignments) value += current.getPlacementValue();
for (ExamAssignment initial : iInitials.values()) value -= initial.getPlacementValue();
return value;
}
public int compareTo(ExamProposedChange change) {
int cmp = Double.compare(getNrUnassigned(), change.getNrUnassigned());
if (cmp!=0) return cmp;
return Double.compare(getValue(), change.getValue());
}
public String getHtmlTable() {
String ret = "<table border='0' cellspacing='0' cellpadding='3' width='100%'>";
ret += "<tr>";
ret += "<td><i>Examination</i></td>";
ret += "<td><i>Period Change</i></td>";
ret += "<td><i>Room Change</i></td>";
ret += "<td><i>Direct</i></td>";
ret += "<td><i>>2 A Day</i></td>";
ret += "<td><i>BTB</i></td>";
ret += "</tr>";
for (ExamAssignment current : iAssignments) {
ExamAssignment initial = iInitials.get(current.getExamId());
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+current.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += "<img src='images/Delete16.gif' border='0' onclick=\"document.location='examInfo.do?delete="+current.getExamId()+"&op=Select';event.cancelBubble=true;\"> ";
ret += current.getExamNameHtml();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getPeriodId().equals(current.getPeriodId()))
ret += initial.getPeriodAbbreviationWithPref() + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getPeriodAbbreviationWithPref();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getRoomIds().equals(current.getRoomIds()))
ret += initial.getRoomsNameWithPref(", ") + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getRoomsNameWithPref(", ");
- if (current.getNrRooms()==0 && current.getMaxRooms()>0) ret += "<i>Select bellow ...</i>";
+ if (current.getNrRooms()==0 && current.getMaxRooms()>0) ret += "<i>Select below ...</i>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDirectConflicts()), current.getPlacementNrDirectConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrMoreThanTwoADayConflicts()), current.getPlacementNrMoreThanTwoADayConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrBackToBackConflicts()), current.getPlacementNrBackToBackConflicts());
if (current.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDistanceBackToBackConflicts()), current.getPlacementNrDistanceBackToBackConflicts())+")";
ret += "</td></tr>";
}
for (ExamAssignment conflict : iConflicts) {
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+conflict.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += conflict.getExamNameHtml();
ret += "</td><td nowrap>";
ret += conflict.getPeriodAbbreviationWithPref() + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>"+"</td>";
ret += "</td><td nowrap>";
ret += conflict.getRoomsNameWithPref(", ") + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrDirectConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrMoreThanTwoADayConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrBackToBackConflicts(), 0);
if (conflict.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(true,conflict.getPlacementNrDistanceBackToBackConflicts(), 0)+")";
ret += "</td></tr>";
}
ret += "</table>";
return ret;
}
public String getHtmlLine(int index) {
String ret = "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?suggestion="+index+"&op=Select';\">";
String name = "", period = "", room = "", dc = "", btb = "", m2d = "";
for (ExamAssignment current : iAssignments) {
ExamAssignment initial = iInitials.get(current.getExamId());
if (name.length()>0) { name += "<br>"; period += "<br>"; room += "<br>"; dc += "<br>"; m2d += "<br>"; btb += "<br>"; }
name += current.getExamNameHtml();
if (initial!=null && !initial.getPeriodId().equals(current.getPeriodId()))
period += initial.getPeriodAbbreviationWithPref() + " → ";
period += current.getPeriodAbbreviationWithPref();
if (initial!=null && !initial.getRoomIds().equals(current.getRoomIds()))
room += initial.getRoomsNameWithPref(", ") + " → ";
room += current.getRoomsNameWithPref(", ");
dc += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDirectConflicts()), current.getPlacementNrDirectConflicts());
m2d += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrMoreThanTwoADayConflicts()), current.getPlacementNrMoreThanTwoADayConflicts());
btb += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrBackToBackConflicts()), current.getPlacementNrBackToBackConflicts());
if (current.getPlacementNrDistanceBackToBackConflicts()>0)
btb += " (d:"+ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDistanceBackToBackConflicts()), current.getPlacementNrDistanceBackToBackConflicts())+")";
}
for (ExamAssignment conflict : iConflicts) {
if (name.length()>0) { name += "<br>"; period += "<br>"; room += "<br>"; dc += "<br>"; m2d += "<br>"; btb += "<br>"; }
name += conflict.getExamNameHtml();
period += conflict.getPeriodAbbreviationWithPref() + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>"+"</td>";
room += conflict.getRoomsNameWithPref(", ") + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>";
dc += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrDirectConflicts(), 0);
m2d += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrMoreThanTwoADayConflicts(), 0);
btb += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrBackToBackConflicts(), 0);
if (conflict.getPlacementNrDistanceBackToBackConflicts()>0)
btb += " (d:"+ClassAssignmentDetails.dispNumberShort(true,conflict.getPlacementNrDistanceBackToBackConflicts(), 0)+")";
}
ret += "<td align='right' width='1%' nowrap>"+ClassAssignmentDetails.dispNumber(Math.round(getValue()))+"</td><td nowrap>";
ret += name;
ret += "</td><td nowrap>";
ret += period;
ret += "</td><td nowrap>";
ret += room;
ret += "</td><td nowrap>";
ret += dc;
ret += "</td><td nowrap>";
ret += m2d;
ret += "</td><td nowrap>";
ret += btb;
ret += "</td></tr>";
return ret;
}
public String toString(String delim) {
String ret = "";
for (ExamAssignment conflict : iConflicts) {
if (ret.length()>0) ret+=delim;
ret += conflict.getExamName() + " " + conflict.getPeriodName()+" "+conflict.getRoomsName(", ") + " -> Not Assigned";
}
for (ExamAssignment current : iAssignments) {
if (ret.length()>0) ret+=delim;
ExamAssignment initial = iInitials.get(current.getExamId());
ret += current.getExamName() + " " + (initial==null?"Not Assigned":initial.getPeriodName()+" "+initial.getRoomsName(", ")) + " -> " + current.getPeriodName()+" "+current.getRoomsName(", ");
}
return ret;
}
public String toString() { return toString("\n"); }
public boolean isUnassigned(Long examId) {
for (ExamAssignment conflict : getConflicts())
if (examId.equals(conflict.getExamId())) return true;
return false;
}
}
| true | true | public String getHtmlTable() {
String ret = "<table border='0' cellspacing='0' cellpadding='3' width='100%'>";
ret += "<tr>";
ret += "<td><i>Examination</i></td>";
ret += "<td><i>Period Change</i></td>";
ret += "<td><i>Room Change</i></td>";
ret += "<td><i>Direct</i></td>";
ret += "<td><i>>2 A Day</i></td>";
ret += "<td><i>BTB</i></td>";
ret += "</tr>";
for (ExamAssignment current : iAssignments) {
ExamAssignment initial = iInitials.get(current.getExamId());
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+current.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += "<img src='images/Delete16.gif' border='0' onclick=\"document.location='examInfo.do?delete="+current.getExamId()+"&op=Select';event.cancelBubble=true;\"> ";
ret += current.getExamNameHtml();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getPeriodId().equals(current.getPeriodId()))
ret += initial.getPeriodAbbreviationWithPref() + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getPeriodAbbreviationWithPref();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getRoomIds().equals(current.getRoomIds()))
ret += initial.getRoomsNameWithPref(", ") + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getRoomsNameWithPref(", ");
if (current.getNrRooms()==0 && current.getMaxRooms()>0) ret += "<i>Select bellow ...</i>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDirectConflicts()), current.getPlacementNrDirectConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrMoreThanTwoADayConflicts()), current.getPlacementNrMoreThanTwoADayConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrBackToBackConflicts()), current.getPlacementNrBackToBackConflicts());
if (current.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDistanceBackToBackConflicts()), current.getPlacementNrDistanceBackToBackConflicts())+")";
ret += "</td></tr>";
}
for (ExamAssignment conflict : iConflicts) {
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+conflict.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += conflict.getExamNameHtml();
ret += "</td><td nowrap>";
ret += conflict.getPeriodAbbreviationWithPref() + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>"+"</td>";
ret += "</td><td nowrap>";
ret += conflict.getRoomsNameWithPref(", ") + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrDirectConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrMoreThanTwoADayConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrBackToBackConflicts(), 0);
if (conflict.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(true,conflict.getPlacementNrDistanceBackToBackConflicts(), 0)+")";
ret += "</td></tr>";
}
ret += "</table>";
return ret;
}
| public String getHtmlTable() {
String ret = "<table border='0' cellspacing='0' cellpadding='3' width='100%'>";
ret += "<tr>";
ret += "<td><i>Examination</i></td>";
ret += "<td><i>Period Change</i></td>";
ret += "<td><i>Room Change</i></td>";
ret += "<td><i>Direct</i></td>";
ret += "<td><i>>2 A Day</i></td>";
ret += "<td><i>BTB</i></td>";
ret += "</tr>";
for (ExamAssignment current : iAssignments) {
ExamAssignment initial = iInitials.get(current.getExamId());
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+current.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += "<img src='images/Delete16.gif' border='0' onclick=\"document.location='examInfo.do?delete="+current.getExamId()+"&op=Select';event.cancelBubble=true;\"> ";
ret += current.getExamNameHtml();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getPeriodId().equals(current.getPeriodId()))
ret += initial.getPeriodAbbreviationWithPref() + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getPeriodAbbreviationWithPref();
ret += "</td><td nowrap>";
if (initial!=null && !initial.getRoomIds().equals(current.getRoomIds()))
ret += initial.getRoomsNameWithPref(", ") + " → ";
if (initial==null)
ret += "<font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font> → ";
ret += current.getRoomsNameWithPref(", ");
if (current.getNrRooms()==0 && current.getMaxRooms()>0) ret += "<i>Select below ...</i>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDirectConflicts()), current.getPlacementNrDirectConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrMoreThanTwoADayConflicts()), current.getPlacementNrMoreThanTwoADayConflicts());
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrBackToBackConflicts()), current.getPlacementNrBackToBackConflicts());
if (current.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(false,(initial==null?0:initial.getPlacementNrDistanceBackToBackConflicts()), current.getPlacementNrDistanceBackToBackConflicts())+")";
ret += "</td></tr>";
}
for (ExamAssignment conflict : iConflicts) {
ret += "<tr onmouseover=\"this.style.backgroundColor='rgb(223,231,242)';this.style.cursor='hand';this.style.cursor='pointer';\" onmouseout=\"this.style.backgroundColor='transparent';\" onclick=\"document.location='examInfo.do?examId="+conflict.getExamId()+"&op=Select';\">";
ret += "<td nowrap>";
ret += conflict.getExamNameHtml();
ret += "</td><td nowrap>";
ret += conflict.getPeriodAbbreviationWithPref() + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>"+"</td>";
ret += "</td><td nowrap>";
ret += conflict.getRoomsNameWithPref(", ") + " → <font color='"+PreferenceLevel.prolog2color("P")+"'><i>not-assigned</i></font>";
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrDirectConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrMoreThanTwoADayConflicts(), 0);
ret += "</td><td nowrap>";
ret += ClassAssignmentDetails.dispNumberShort(true, conflict.getPlacementNrBackToBackConflicts(), 0);
if (conflict.getPlacementNrDistanceBackToBackConflicts()>0)
ret += " (d:"+ClassAssignmentDetails.dispNumberShort(true,conflict.getPlacementNrDistanceBackToBackConflicts(), 0)+")";
ret += "</td></tr>";
}
ret += "</table>";
return ret;
}
|
diff --git a/BetterWifiOnOff/src/com/asksven/betterwifionoff/MyWidgetProvider.java b/BetterWifiOnOff/src/com/asksven/betterwifionoff/MyWidgetProvider.java
index b492166..e3105e5 100644
--- a/BetterWifiOnOff/src/com/asksven/betterwifionoff/MyWidgetProvider.java
+++ b/BetterWifiOnOff/src/com/asksven/betterwifionoff/MyWidgetProvider.java
@@ -1,168 +1,168 @@
/*
* Copyright (C) 2012 asksven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asksven.betterwifionoff;
import com.asksven.android.common.utils.DateUtils;
import com.asksven.betterwifionoff.data.EventLogger;
import com.asksven.betterwifionoff.handlers.ScreenEventHandler;
import com.asksven.betterwifionoff.services.UpdateWidgetService;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
public class MyWidgetProvider extends AppWidgetProvider
{
public static final String ACTION_REFRESH = "ACTION_REFRESH";
public static final String ACTION_ENABLE = "ACTION_DISABLE";
public static final String ACTION_DISABLE = "ACTION_ENABLE";
private static final String TAG = "BetterWifiOnOff.MyWidgetProvider";
public static final String ACTION_CLICK = "ACTION_CLICK";
@Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
Log.i(TAG, "onReceive method called, action = '" + intent.getAction() + "' at " + DateUtils.now());
if ( (ACTION_CLICK.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = sharedPrefs.getBoolean("disable_control", false);
// write back the new value
boolean bNewState = !bDisabled;
SharedPreferences.Editor editor = sharedPrefs.edit();
if (bNewState)
{
EventLogger.getInstance(context).addStatusChangedEvent(
- context.getString(R.string.event_disable_due_to_user_interaction));
+ context.getString(R.string.event_disable_by_widget));
}
else
{
EventLogger.getInstance(context).addStatusChangedEvent(
- context.getString(R.string.event_enable_due_to_user_interaction));
+ context.getString(R.string.event_enable_by_widget));
// turn Wifi on
ScreenEventHandler.wifiOn(context);
}
editor.putBoolean("disable_control", bNewState);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_ENABLE.equals(intent.getAction())) || (ACTION_DISABLE.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = false;
if (ACTION_ENABLE.equals(intent.getAction()))
{
bDisabled = false;
}
else
{
bDisabled = true;
}
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("disable_control", bDisabled);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_REFRESH.equals(intent.getAction())) )
{
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
Log.w(TAG, "onUpdate method called");
// Get all ids
ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
// Build the intent to call the service
Intent intent = new Intent(context.getApplicationContext(), UpdateWidgetService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
// Update the widgets via the service
context.startService(intent);
}
}
| false | true | public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
Log.i(TAG, "onReceive method called, action = '" + intent.getAction() + "' at " + DateUtils.now());
if ( (ACTION_CLICK.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = sharedPrefs.getBoolean("disable_control", false);
// write back the new value
boolean bNewState = !bDisabled;
SharedPreferences.Editor editor = sharedPrefs.edit();
if (bNewState)
{
EventLogger.getInstance(context).addStatusChangedEvent(
context.getString(R.string.event_disable_due_to_user_interaction));
}
else
{
EventLogger.getInstance(context).addStatusChangedEvent(
context.getString(R.string.event_enable_due_to_user_interaction));
// turn Wifi on
ScreenEventHandler.wifiOn(context);
}
editor.putBoolean("disable_control", bNewState);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_ENABLE.equals(intent.getAction())) || (ACTION_DISABLE.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = false;
if (ACTION_ENABLE.equals(intent.getAction()))
{
bDisabled = false;
}
else
{
bDisabled = true;
}
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("disable_control", bDisabled);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_REFRESH.equals(intent.getAction())) )
{
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
}
| public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
Log.i(TAG, "onReceive method called, action = '" + intent.getAction() + "' at " + DateUtils.now());
if ( (ACTION_CLICK.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = sharedPrefs.getBoolean("disable_control", false);
// write back the new value
boolean bNewState = !bDisabled;
SharedPreferences.Editor editor = sharedPrefs.edit();
if (bNewState)
{
EventLogger.getInstance(context).addStatusChangedEvent(
context.getString(R.string.event_disable_by_widget));
}
else
{
EventLogger.getInstance(context).addStatusChangedEvent(
context.getString(R.string.event_enable_by_widget));
// turn Wifi on
ScreenEventHandler.wifiOn(context);
}
editor.putBoolean("disable_control", bNewState);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_ENABLE.equals(intent.getAction())) || (ACTION_DISABLE.equals(intent.getAction())) )
{
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean bDisabled = false;
if (ACTION_ENABLE.equals(intent.getAction()))
{
bDisabled = false;
}
else
{
bDisabled = true;
}
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("disable_control", bDisabled);
editor.commit();
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
if ( (ACTION_REFRESH.equals(intent.getAction())) )
{
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName thisAppWidget = new ComponentName(
context.getPackageName(),
this.getClass().getName());
int[] appWidgetIds = appWidgetManager
.getAppWidgetIds(thisAppWidget);
if (appWidgetIds.length > 0)
{
onUpdate(context, appWidgetManager, appWidgetIds);
}
else
{
Log.i(TAG, "No widget found to update");
}
}
}
|
diff --git a/src/main/java/de/taimos/aws/route53update/Starter.java b/src/main/java/de/taimos/aws/route53update/Starter.java
index 4b44db3..aa16efa 100644
--- a/src/main/java/de/taimos/aws/route53update/Starter.java
+++ b/src/main/java/de/taimos/aws/route53update/Starter.java
@@ -1,96 +1,96 @@
package de.taimos.aws.route53update;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.route53.AmazonRoute53Client;
import com.amazonaws.services.route53.model.Change;
import com.amazonaws.services.route53.model.ChangeBatch;
import com.amazonaws.services.route53.model.ChangeResourceRecordSetsRequest;
import com.amazonaws.services.route53.model.HostedZone;
import com.amazonaws.services.route53.model.ListHostedZonesResult;
import com.amazonaws.services.route53.model.ListResourceRecordSetsRequest;
import com.amazonaws.services.route53.model.ListResourceRecordSetsResult;
import com.amazonaws.services.route53.model.RRType;
import com.amazonaws.services.route53.model.ResourceRecord;
import com.amazonaws.services.route53.model.ResourceRecordSet;
import de.taimos.httputils.WS;
public class Starter {
/**
* @param args
*/
public static void main(String[] args) {
if (args.length != 2) {
- System.out.println("usage: java -jar route53-updater.jar <domain> <host>");
+ System.out.println("usage: route53-updater <domain> <host>");
System.exit(1);
}
String domain = args[0] + ".";
System.out.println("Domain: " + domain);
String host = args[1] + "." + domain;
System.out.println("Host: " + host);
String zoneId = Starter.findZoneId(domain);
String publicHostname = Starter.getPublicHostname();
ResourceRecordSet set = Starter.findCurrentSet(zoneId, host);
List<Change> changes = new ArrayList<>();
if (set != null) {
System.out.println("Deleting current set: " + set);
changes.add(new Change("DELETE", set));
}
ResourceRecordSet rrs = new ResourceRecordSet(host, RRType.CNAME).withTTL(60L).withResourceRecords(new ResourceRecord(publicHostname));
System.out.println("Creating new set: " + rrs);
changes.add(new Change("CREATE", rrs));
try {
AmazonRoute53Client cl = Starter.createClient();
ChangeResourceRecordSetsRequest req = new ChangeResourceRecordSetsRequest(zoneId, new ChangeBatch(changes));
cl.changeResourceRecordSets(req);
} catch (Exception e) {
e.printStackTrace();
}
}
private static ResourceRecordSet findCurrentSet(String zoneId, String host) {
AmazonRoute53Client cl = Starter.createClient();
ListResourceRecordSetsRequest req = new ListResourceRecordSetsRequest(zoneId);
ListResourceRecordSetsResult sets = cl.listResourceRecordSets(req);
List<ResourceRecordSet> recordSets = sets.getResourceRecordSets();
for (ResourceRecordSet rrs : recordSets) {
if (rrs.getName().equals(host)) {
return rrs;
}
}
return null;
}
private static String findZoneId(String domain) {
AmazonRoute53Client cl = Starter.createClient();
ListHostedZonesResult zones = cl.listHostedZones();
List<HostedZone> hostedZones = zones.getHostedZones();
for (HostedZone hz : hostedZones) {
if (hz.getName().equals(domain)) {
return hz.getId();
}
}
throw new RuntimeException("Cannot find zone: " + domain);
}
private static String getPublicHostname() {
HttpResponse res = WS.url("http://169.254.169.254/latest/meta-data/public-hostname").get();
return WS.getResponseAsString(res);
}
private static AmazonRoute53Client createClient() {
AmazonRoute53Client cl = new AmazonRoute53Client();
cl.setRegion(Region.getRegion(Regions.EU_WEST_1));
return cl;
}
}
| true | true | public static void main(String[] args) {
if (args.length != 2) {
System.out.println("usage: java -jar route53-updater.jar <domain> <host>");
System.exit(1);
}
String domain = args[0] + ".";
System.out.println("Domain: " + domain);
String host = args[1] + "." + domain;
System.out.println("Host: " + host);
String zoneId = Starter.findZoneId(domain);
String publicHostname = Starter.getPublicHostname();
ResourceRecordSet set = Starter.findCurrentSet(zoneId, host);
List<Change> changes = new ArrayList<>();
if (set != null) {
System.out.println("Deleting current set: " + set);
changes.add(new Change("DELETE", set));
}
ResourceRecordSet rrs = new ResourceRecordSet(host, RRType.CNAME).withTTL(60L).withResourceRecords(new ResourceRecord(publicHostname));
System.out.println("Creating new set: " + rrs);
changes.add(new Change("CREATE", rrs));
try {
AmazonRoute53Client cl = Starter.createClient();
ChangeResourceRecordSetsRequest req = new ChangeResourceRecordSetsRequest(zoneId, new ChangeBatch(changes));
cl.changeResourceRecordSets(req);
} catch (Exception e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
if (args.length != 2) {
System.out.println("usage: route53-updater <domain> <host>");
System.exit(1);
}
String domain = args[0] + ".";
System.out.println("Domain: " + domain);
String host = args[1] + "." + domain;
System.out.println("Host: " + host);
String zoneId = Starter.findZoneId(domain);
String publicHostname = Starter.getPublicHostname();
ResourceRecordSet set = Starter.findCurrentSet(zoneId, host);
List<Change> changes = new ArrayList<>();
if (set != null) {
System.out.println("Deleting current set: " + set);
changes.add(new Change("DELETE", set));
}
ResourceRecordSet rrs = new ResourceRecordSet(host, RRType.CNAME).withTTL(60L).withResourceRecords(new ResourceRecord(publicHostname));
System.out.println("Creating new set: " + rrs);
changes.add(new Change("CREATE", rrs));
try {
AmazonRoute53Client cl = Starter.createClient();
ChangeResourceRecordSetsRequest req = new ChangeResourceRecordSetsRequest(zoneId, new ChangeBatch(changes));
cl.changeResourceRecordSets(req);
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/core/src/test/java/org/springframework/security/config/CustomAfterInvocationProviderBeanDefinitionDecoratorTests.java b/core/src/test/java/org/springframework/security/config/CustomAfterInvocationProviderBeanDefinitionDecoratorTests.java
index 04bfc718c..6fe121ac9 100644
--- a/core/src/test/java/org/springframework/security/config/CustomAfterInvocationProviderBeanDefinitionDecoratorTests.java
+++ b/core/src/test/java/org/springframework/security/config/CustomAfterInvocationProviderBeanDefinitionDecoratorTests.java
@@ -1,43 +1,43 @@
package org.springframework.security.config;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.security.afterinvocation.AfterInvocationProviderManager;
import org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor;
import org.springframework.security.util.InMemoryXmlApplicationContext;
public class CustomAfterInvocationProviderBeanDefinitionDecoratorTests {
private AbstractXmlApplicationContext appContext;
@After
public void closeAppContext() {
if (appContext != null) {
appContext.close();
appContext = null;
}
}
@Test
- public void customAuthenticationProviderIsAddedToInterceptor() {
+ public void customAfterInvocationProviderIsAddedToInterceptor() {
setContext(
"<global-method-security />" +
"<b:bean id='aip' class='org.springframework.security.config.MockAfterInvocationProvider'>" +
" <custom-after-invocation-provider />" +
"</b:bean>" +
HttpSecurityBeanDefinitionParserTests.AUTH_PROVIDER_XML
);
MethodSecurityInterceptor msi = (MethodSecurityInterceptor) appContext.getBean(BeanIds.METHOD_SECURITY_INTERCEPTOR);
AfterInvocationProviderManager apm = (AfterInvocationProviderManager) msi.getAfterInvocationManager();
assertNotNull(apm);
assertEquals(1, apm.getProviders().size());
assertTrue(apm.getProviders().get(0) instanceof MockAfterInvocationProvider);
}
private void setContext(String context) {
appContext = new InMemoryXmlApplicationContext(context);
}
}
| true | true | public void customAuthenticationProviderIsAddedToInterceptor() {
setContext(
"<global-method-security />" +
"<b:bean id='aip' class='org.springframework.security.config.MockAfterInvocationProvider'>" +
" <custom-after-invocation-provider />" +
"</b:bean>" +
HttpSecurityBeanDefinitionParserTests.AUTH_PROVIDER_XML
);
MethodSecurityInterceptor msi = (MethodSecurityInterceptor) appContext.getBean(BeanIds.METHOD_SECURITY_INTERCEPTOR);
AfterInvocationProviderManager apm = (AfterInvocationProviderManager) msi.getAfterInvocationManager();
assertNotNull(apm);
assertEquals(1, apm.getProviders().size());
assertTrue(apm.getProviders().get(0) instanceof MockAfterInvocationProvider);
}
| public void customAfterInvocationProviderIsAddedToInterceptor() {
setContext(
"<global-method-security />" +
"<b:bean id='aip' class='org.springframework.security.config.MockAfterInvocationProvider'>" +
" <custom-after-invocation-provider />" +
"</b:bean>" +
HttpSecurityBeanDefinitionParserTests.AUTH_PROVIDER_XML
);
MethodSecurityInterceptor msi = (MethodSecurityInterceptor) appContext.getBean(BeanIds.METHOD_SECURITY_INTERCEPTOR);
AfterInvocationProviderManager apm = (AfterInvocationProviderManager) msi.getAfterInvocationManager();
assertNotNull(apm);
assertEquals(1, apm.getProviders().size());
assertTrue(apm.getProviders().get(0) instanceof MockAfterInvocationProvider);
}
|
diff --git a/plugins/org.eclipse.mylyn.docs.intent.client.linkresolver/src/org/eclipse/mylyn/docs/intent/client/linkresolver/repository/LinkResolverJob.java b/plugins/org.eclipse.mylyn.docs.intent.client.linkresolver/src/org/eclipse/mylyn/docs/intent/client/linkresolver/repository/LinkResolverJob.java
index e2d80c42..52160ec8 100644
--- a/plugins/org.eclipse.mylyn.docs.intent.client.linkresolver/src/org/eclipse/mylyn/docs/intent/client/linkresolver/repository/LinkResolverJob.java
+++ b/plugins/org.eclipse.mylyn.docs.intent.client.linkresolver/src/org/eclipse/mylyn/docs/intent/client/linkresolver/repository/LinkResolverJob.java
@@ -1,86 +1,85 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.docs.intent.client.linkresolver.repository;
import com.google.common.collect.Lists;
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;
import org.eclipse.mylyn.docs.intent.client.linkresolver.resolver.LinkResolver;
import org.eclipse.mylyn.docs.intent.collab.common.location.IntentLocations;
import org.eclipse.mylyn.docs.intent.collab.common.logger.IIntentLogger.LogType;
import org.eclipse.mylyn.docs.intent.collab.common.logger.IntentLogger;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.IntentCommand;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.ReadOnlyException;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.RepositoryAdapter;
import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.SaveException;
/**
* A job that will triger the link resolving of all references to Intent Structured Element (sections,
* chapters...).
*
* @author <a href="mailto:[email protected]">Alex Lagarde</a>
*/
public class LinkResolverJob extends Job {
private static final String LINK_RESOLVER_JOB_NAME = "Resolving references inside Intent Document";
/**
* The repository Adapter to use for manipulating the Intent repository.
*/
private RepositoryAdapter repositoryAdapter;
private LinkResolver linkResolver;
/**
* Creates a new {@link LinkResolverJob}.
*
* @param repositoryAdapter
* the repository Adapter to use for manipulating the Intent repository
*/
public LinkResolverJob(RepositoryAdapter repositoryAdapter) {
super(LINK_RESOLVER_JOB_NAME);
this.repositoryAdapter = repositoryAdapter;
this.linkResolver = new LinkResolver(repositoryAdapter);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected IStatus run(final IProgressMonitor monitor) {
repositoryAdapter.execute(new IntentCommand() {
public void execute() {
- linkResolver.resolve(monitor);
+ try {
+ repositoryAdapter.openSaveContext();
+ linkResolver.resolve(monitor);
+ repositoryAdapter.setSendSessionWarningBeforeSaving(Lists
+ .newArrayList(IntentLocations.INTENT_FOLDER));
+ repositoryAdapter.save();
+ } catch (ReadOnlyException e) {
+ IntentLogger.getInstance().log(LogType.ERROR,
+ "Failed to resolve links inside the Intent Document: insufficiant rights");
+ } catch (SaveException e) {
+ IntentLogger.getInstance().log(LogType.ERROR,
+ "Failed to resolve links inside the Intent Document:" + e.getMessage());
+ }
}
});
- if (!monitor.isCanceled()) {
- try {
- repositoryAdapter.setSendSessionWarningBeforeSaving(Lists
- .newArrayList(IntentLocations.INTENT_FOLDER));
- repositoryAdapter.save();
- } catch (ReadOnlyException e) {
- IntentLogger.getInstance().log(LogType.ERROR,
- "Failed to resolve links inside the Intent Document: insufficiant rights");
- } catch (SaveException e) {
- IntentLogger.getInstance().log(LogType.ERROR,
- "Failed to resolve links inside the Intent Document:" + e.getMessage());
- }
- }
return Status.OK_STATUS;
}
}
| false | true | protected IStatus run(final IProgressMonitor monitor) {
repositoryAdapter.execute(new IntentCommand() {
public void execute() {
linkResolver.resolve(monitor);
}
});
if (!monitor.isCanceled()) {
try {
repositoryAdapter.setSendSessionWarningBeforeSaving(Lists
.newArrayList(IntentLocations.INTENT_FOLDER));
repositoryAdapter.save();
} catch (ReadOnlyException e) {
IntentLogger.getInstance().log(LogType.ERROR,
"Failed to resolve links inside the Intent Document: insufficiant rights");
} catch (SaveException e) {
IntentLogger.getInstance().log(LogType.ERROR,
"Failed to resolve links inside the Intent Document:" + e.getMessage());
}
}
return Status.OK_STATUS;
}
| protected IStatus run(final IProgressMonitor monitor) {
repositoryAdapter.execute(new IntentCommand() {
public void execute() {
try {
repositoryAdapter.openSaveContext();
linkResolver.resolve(monitor);
repositoryAdapter.setSendSessionWarningBeforeSaving(Lists
.newArrayList(IntentLocations.INTENT_FOLDER));
repositoryAdapter.save();
} catch (ReadOnlyException e) {
IntentLogger.getInstance().log(LogType.ERROR,
"Failed to resolve links inside the Intent Document: insufficiant rights");
} catch (SaveException e) {
IntentLogger.getInstance().log(LogType.ERROR,
"Failed to resolve links inside the Intent Document:" + e.getMessage());
}
}
});
return Status.OK_STATUS;
}
|
diff --git a/asm/src/org/objectweb/asm/ClassWriter.java b/asm/src/org/objectweb/asm/ClassWriter.java
index a2e5c53e..e5dc24fa 100644
--- a/asm/src/org/objectweb/asm/ClassWriter.java
+++ b/asm/src/org/objectweb/asm/ClassWriter.java
@@ -1,1672 +1,1672 @@
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm;
/**
* A {@link ClassVisitor} that generates classes in bytecode form. More
* precisely this visitor generates a byte array conforming to the Java class
* file format. It can be used alone, to generate a Java class "from scratch",
* or with one or more {@link ClassReader ClassReader} and adapter class visitor
* to generate a modified class from one or more existing Java classes.
*
* @author Eric Bruneton
*/
public class ClassWriter extends ClassVisitor {
/**
* Flag to automatically compute the maximum stack size and the maximum
* number of local variables of methods. If this flag is set, then the
* arguments of the {@link MethodVisitor#visitMaxs visitMaxs} method of the
* {@link MethodVisitor} returned by the {@link #visitMethod visitMethod}
* method will be ignored, and computed automatically from the signature and
* the bytecode of each method.
*
* @see #ClassWriter(int)
*/
public static final int COMPUTE_MAXS = 1;
/**
* Flag to automatically compute the stack map frames of methods from
* scratch. If this flag is set, then the calls to the
* {@link MethodVisitor#visitFrame} method are ignored, and the stack map
* frames are recomputed from the methods bytecode. The arguments of the
* {@link MethodVisitor#visitMaxs visitMaxs} method are also ignored and
* recomputed from the bytecode. In other words, computeFrames implies
* computeMaxs.
*
* @see #ClassWriter(int)
*/
public static final int COMPUTE_FRAMES = 2;
/**
* Pseudo access flag to distinguish between the synthetic attribute and
* the synthetic access flag.
*/
static final int ACC_SYNTHETIC_ATTRIBUTE = 0x40000;
/**
* The type of instructions without any argument.
*/
static final int NOARG_INSN = 0;
/**
* The type of instructions with an signed byte argument.
*/
static final int SBYTE_INSN = 1;
/**
* The type of instructions with an signed short argument.
*/
static final int SHORT_INSN = 2;
/**
* The type of instructions with a local variable index argument.
*/
static final int VAR_INSN = 3;
/**
* The type of instructions with an implicit local variable index argument.
*/
static final int IMPLVAR_INSN = 4;
/**
* The type of instructions with a type descriptor argument.
*/
static final int TYPE_INSN = 5;
/**
* The type of field and method invocations instructions.
*/
static final int FIELDORMETH_INSN = 6;
/**
* The type of the INVOKEINTERFACE/INVOKEDYNAMIC instruction.
*/
static final int ITFMETH_INSN = 7;
/**
* The type of the INVOKEDYNAMIC instruction.
*/
static final int INDYMETH_INSN = 8;
/**
* The type of instructions with a 2 bytes bytecode offset label.
*/
static final int LABEL_INSN = 9;
/**
* The type of instructions with a 4 bytes bytecode offset label.
*/
static final int LABELW_INSN = 10;
/**
* The type of the LDC instruction.
*/
static final int LDC_INSN = 11;
/**
* The type of the LDC_W and LDC2_W instructions.
*/
static final int LDCW_INSN = 12;
/**
* The type of the IINC instruction.
*/
static final int IINC_INSN = 13;
/**
* The type of the TABLESWITCH instruction.
*/
static final int TABL_INSN = 14;
/**
* The type of the LOOKUPSWITCH instruction.
*/
static final int LOOK_INSN = 15;
/**
* The type of the MULTIANEWARRAY instruction.
*/
static final int MANA_INSN = 16;
/**
* The type of the WIDE instruction.
*/
static final int WIDE_INSN = 17;
/**
* The instruction types of all JVM opcodes.
*/
static final byte[] TYPE;
/**
* The type of CONSTANT_Class constant pool items.
*/
static final int CLASS = 7;
/**
* The type of CONSTANT_Fieldref constant pool items.
*/
static final int FIELD = 9;
/**
* The type of CONSTANT_Methodref constant pool items.
*/
static final int METH = 10;
/**
* The type of CONSTANT_InterfaceMethodref constant pool items.
*/
static final int IMETH = 11;
/**
* The type of CONSTANT_String constant pool items.
*/
static final int STR = 8;
/**
* The type of CONSTANT_Integer constant pool items.
*/
static final int INT = 3;
/**
* The type of CONSTANT_Float constant pool items.
*/
static final int FLOAT = 4;
/**
* The type of CONSTANT_Long constant pool items.
*/
static final int LONG = 5;
/**
* The type of CONSTANT_Double constant pool items.
*/
static final int DOUBLE = 6;
/**
* The type of CONSTANT_NameAndType constant pool items.
*/
static final int NAME_TYPE = 12;
/**
* The type of CONSTANT_Utf8 constant pool items.
*/
static final int UTF8 = 1;
/**
* The type of CONSTANT_MethodType constant pool items.
*/
static final int MTYPE = 16;
/**
* The type of CONSTANT_MethodHandle constant pool items.
*/
static final int HANDLE = 15;
/**
* The type of CONSTANT_InvokeDynamic constant pool items.
*/
static final int INDY = 18;
/**
* The base value for all CONSTANT_MethodHandle constant pool items.
* Internally, ASM store the 9 variations of CONSTANT_MethodHandle into
* 9 different items.
*/
static final int HANDLE_BASE = 20;
/**
* Normal type Item stored in the ClassWriter {@link ClassWriter#typeTable},
* instead of the constant pool, in order to avoid clashes with normal
* constant pool items in the ClassWriter constant pool's hash table.
*/
static final int TYPE_NORMAL = 30;
/**
* Uninitialized type Item stored in the ClassWriter
* {@link ClassWriter#typeTable}, instead of the constant pool, in order to
* avoid clashes with normal constant pool items in the ClassWriter constant
* pool's hash table.
*/
static final int TYPE_UNINIT = 31;
/**
* Merged type Item stored in the ClassWriter {@link ClassWriter#typeTable},
* instead of the constant pool, in order to avoid clashes with normal
* constant pool items in the ClassWriter constant pool's hash table.
*/
static final int TYPE_MERGED = 32;
/**
* The type of BootstrapMethods items. These items are stored in a
* special class attribute named BootstrapMethods and
* not in the constant pool.
*/
static final int BSM = 33;
/**
* The class reader from which this class writer was constructed, if any.
*/
ClassReader cr;
/**
* Minor and major version numbers of the class to be generated.
*/
int version;
/**
* Index of the next item to be added in the constant pool.
*/
int index;
/**
* The constant pool of this class.
*/
final ByteVector pool;
/**
* The constant pool's hash table data.
*/
Item[] items;
/**
* The threshold of the constant pool's hash table.
*/
int threshold;
/**
* A reusable key used to look for items in the {@link #items} hash table.
*/
final Item key;
/**
* A reusable key used to look for items in the {@link #items} hash table.
*/
final Item key2;
/**
* A reusable key used to look for items in the {@link #items} hash table.
*/
final Item key3;
/**
* A reusable key used to look for items in the {@link #items} hash table.
*/
final Item key4;
/**
* A type table used to temporarily store internal names that will not
* necessarily be stored in the constant pool. This type table is used by
* the control flow and data flow analysis algorithm used to compute stack
* map frames from scratch. This array associates to each index <tt>i</tt>
* the Item whose index is <tt>i</tt>. All Item objects stored in this
* array are also stored in the {@link #items} hash table. These two arrays
* allow to retrieve an Item from its index or, conversely, to get the index
* of an Item from its value. Each Item stores an internal name in its
* {@link Item#strVal1} field.
*/
Item[] typeTable;
/**
* Number of elements in the {@link #typeTable} array.
*/
private short typeCount;
/**
* The access flags of this class.
*/
private int access;
/**
* The constant pool item that contains the internal name of this class.
*/
private int name;
/**
* The internal name of this class.
*/
String thisName;
/**
* The constant pool item that contains the signature of this class.
*/
private int signature;
/**
* The constant pool item that contains the internal name of the super class
* of this class.
*/
private int superName;
/**
* Number of interfaces implemented or extended by this class or interface.
*/
private int interfaceCount;
/**
* The interfaces implemented or extended by this class or interface. More
* precisely, this array contains the indexes of the constant pool items
* that contain the internal names of these interfaces.
*/
private int[] interfaces;
/**
* The index of the constant pool item that contains the name of the source
* file from which this class was compiled.
*/
private int sourceFile;
/**
* The SourceDebug attribute of this class.
*/
private ByteVector sourceDebug;
/**
* The constant pool item that contains the name of the enclosing class of
* this class.
*/
private int enclosingMethodOwner;
/**
* The constant pool item that contains the name and descriptor of the
* enclosing method of this class.
*/
private int enclosingMethod;
/**
* The runtime visible annotations of this class.
*/
private AnnotationWriter anns;
/**
* The runtime invisible annotations of this class.
*/
private AnnotationWriter ianns;
/**
* The non standard attributes of this class.
*/
private Attribute attrs;
/**
* The number of entries in the InnerClasses attribute.
*/
private int innerClassesCount;
/**
* The InnerClasses attribute.
*/
private ByteVector innerClasses;
/**
* The number of entries in the BootstrapMethods attribute.
*/
int bootstrapMethodsCount;
/**
* The BootstrapMethods attribute.
*/
ByteVector bootstrapMethods;
/**
* The fields of this class. These fields are stored in a linked list of
* {@link FieldWriter} objects, linked to each other by their
* {@link FieldWriter#fv} field. This field stores the first element of
* this list.
*/
FieldWriter firstField;
/**
* The fields of this class. These fields are stored in a linked list of
* {@link FieldWriter} objects, linked to each other by their
* {@link FieldWriter#fv} field. This field stores the last element of
* this list.
*/
FieldWriter lastField;
/**
* The methods of this class. These methods are stored in a linked list of
* {@link MethodWriter} objects, linked to each other by their
* {@link MethodWriter#mv} field. This field stores the first element of
* this list.
*/
MethodWriter firstMethod;
/**
* The methods of this class. These methods are stored in a linked list of
* {@link MethodWriter} objects, linked to each other by their
* {@link MethodWriter#mv} field. This field stores the last element of
* this list.
*/
MethodWriter lastMethod;
/**
* <tt>true</tt> if the maximum stack size and number of local variables
* must be automatically computed.
*/
private final boolean computeMaxs;
/**
* <tt>true</tt> if the stack map frames must be recomputed from scratch.
*/
private final boolean computeFrames;
/**
* <tt>true</tt> if the stack map tables of this class are invalid. The
* {@link MethodWriter#resizeInstructions} method cannot transform existing
* stack map tables, and so produces potentially invalid classes when it is
* executed. In this case the class is reread and rewritten with the
* {@link #COMPUTE_FRAMES} option (the resizeInstructions method can resize
* stack map tables when this option is used).
*/
boolean invalidFrames;
// ------------------------------------------------------------------------
// Static initializer
// ------------------------------------------------------------------------
/**
* Computes the instruction types of JVM opcodes.
*/
static {
int i;
byte[] b = new byte[220];
String s = "AAAAAAAAAAAAAAAABCLMMDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADD"
+ "DDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+ "AAAAAAAAAAAAAAAAANAAAAAAAAAAAAAAAAAAAAJJJJJJJJJJJJJJJJDOPAA"
+ "AAAAGGGGGGGHIFBFAAFFAARQJJKKJJJJJJJJJJJJJJJJJJ";
for (i = 0; i < b.length; ++i) {
b[i] = (byte) (s.charAt(i) - 'A');
}
TYPE = b;
// code to generate the above string
//
// // SBYTE_INSN instructions
// b[Constants.NEWARRAY] = SBYTE_INSN;
// b[Constants.BIPUSH] = SBYTE_INSN;
//
// // SHORT_INSN instructions
// b[Constants.SIPUSH] = SHORT_INSN;
//
// // (IMPL)VAR_INSN instructions
// b[Constants.RET] = VAR_INSN;
// for (i = Constants.ILOAD; i <= Constants.ALOAD; ++i) {
// b[i] = VAR_INSN;
// }
// for (i = Constants.ISTORE; i <= Constants.ASTORE; ++i) {
// b[i] = VAR_INSN;
// }
// for (i = 26; i <= 45; ++i) { // ILOAD_0 to ALOAD_3
// b[i] = IMPLVAR_INSN;
// }
// for (i = 59; i <= 78; ++i) { // ISTORE_0 to ASTORE_3
// b[i] = IMPLVAR_INSN;
// }
//
// // TYPE_INSN instructions
// b[Constants.NEW] = TYPE_INSN;
// b[Constants.ANEWARRAY] = TYPE_INSN;
// b[Constants.CHECKCAST] = TYPE_INSN;
// b[Constants.INSTANCEOF] = TYPE_INSN;
//
// // (Set)FIELDORMETH_INSN instructions
// for (i = Constants.GETSTATIC; i <= Constants.INVOKESTATIC; ++i) {
// b[i] = FIELDORMETH_INSN;
// }
// b[Constants.INVOKEINTERFACE] = ITFMETH_INSN;
// b[Constants.INVOKEDYNAMIC] = INDYMETH_INSN;
//
// // LABEL(W)_INSN instructions
// for (i = Constants.IFEQ; i <= Constants.JSR; ++i) {
// b[i] = LABEL_INSN;
// }
// b[Constants.IFNULL] = LABEL_INSN;
// b[Constants.IFNONNULL] = LABEL_INSN;
// b[200] = LABELW_INSN; // GOTO_W
// b[201] = LABELW_INSN; // JSR_W
// // temporary opcodes used internally by ASM - see Label and
// MethodWriter
// for (i = 202; i < 220; ++i) {
// b[i] = LABEL_INSN;
// }
//
// // LDC(_W) instructions
// b[Constants.LDC] = LDC_INSN;
// b[19] = LDCW_INSN; // LDC_W
// b[20] = LDCW_INSN; // LDC2_W
//
// // special instructions
// b[Constants.IINC] = IINC_INSN;
// b[Constants.TABLESWITCH] = TABL_INSN;
// b[Constants.LOOKUPSWITCH] = LOOK_INSN;
// b[Constants.MULTIANEWARRAY] = MANA_INSN;
// b[196] = WIDE_INSN; // WIDE
//
// for (i = 0; i < b.length; ++i) {
// System.err.print((char)('A' + b[i]));
// }
// System.err.println();
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
/**
* Constructs a new {@link ClassWriter} object.
*
* @param flags option flags that can be used to modify the default behavior
* of this class. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}.
*/
public ClassWriter(final int flags) {
super(Opcodes.ASM4);
index = 1;
pool = new ByteVector();
items = new Item[256];
threshold = (int) (0.75d * items.length);
key = new Item();
key2 = new Item();
key3 = new Item();
key4 = new Item();
this.computeMaxs = (flags & COMPUTE_MAXS) != 0;
this.computeFrames = (flags & COMPUTE_FRAMES) != 0;
}
/**
* Constructs a new {@link ClassWriter} object and enables optimizations for
* "mostly add" bytecode transformations. These optimizations are the
* following:
*
* <ul> <li>The constant pool from the original class is copied as is in the
* new class, which saves time. New constant pool entries will be added at
* the end if necessary, but unused constant pool entries <i>won't be
* removed</i>.</li> <li>Methods that are not transformed are copied as is
* in the new class, directly from the original class bytecode (i.e. without
* emitting visit events for all the method instructions), which saves a
* <i>lot</i> of time. Untransformed methods are detected by the fact that
* the {@link ClassReader} receives {@link MethodVisitor} objects that come
* from a {@link ClassWriter} (and not from any other {@link ClassVisitor}
* instance).</li> </ul>
*
* @param classReader the {@link ClassReader} used to read the original
* class. It will be used to copy the entire constant pool from the
* original class and also to copy other fragments of original
* bytecode where applicable.
* @param flags option flags that can be used to modify the default behavior
* of this class. <i>These option flags do not affect methods that
* are copied as is in the new class. This means that the maximum
* stack size nor the stack frames will be computed for these
* methods</i>. See {@link #COMPUTE_MAXS}, {@link #COMPUTE_FRAMES}.
*/
public ClassWriter(final ClassReader classReader, final int flags) {
this(flags);
classReader.copyPool(this);
this.cr = classReader;
}
// ------------------------------------------------------------------------
// Implementation of the ClassVisitor abstract class
// ------------------------------------------------------------------------
@Override
public final void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces)
{
this.version = version;
this.access = access;
this.name = newClass(name);
thisName = name;
if (ClassReader.SIGNATURES && signature != null) {
this.signature = newUTF8(signature);
}
this.superName = superName == null ? 0 : newClass(superName);
if (interfaces != null && interfaces.length > 0) {
interfaceCount = interfaces.length;
this.interfaces = new int[interfaceCount];
for (int i = 0; i < interfaceCount; ++i) {
this.interfaces[i] = newClass(interfaces[i]);
}
}
}
@Override
public final void visitSource(final String file, final String debug) {
if (file != null) {
sourceFile = newUTF8(file);
}
if (debug != null) {
sourceDebug = new ByteVector().putUTF8(debug);
}
}
@Override
public final void visitOuterClass(
final String owner,
final String name,
final String desc)
{
enclosingMethodOwner = newClass(owner);
if (name != null && desc != null) {
enclosingMethod = newNameType(name, desc);
}
}
@Override
public final AnnotationVisitor visitAnnotation(
final String desc,
final boolean visible)
{
if (!ClassReader.ANNOTATIONS) {
return null;
}
ByteVector bv = new ByteVector();
// write type, and reserve space for values count
bv.putShort(newUTF8(desc)).putShort(0);
AnnotationWriter aw = new AnnotationWriter(this, true, bv, bv, 2);
if (visible) {
aw.next = anns;
anns = aw;
} else {
aw.next = ianns;
ianns = aw;
}
return aw;
}
@Override
public final void visitAttribute(final Attribute attr) {
attr.next = attrs;
attrs = attr;
}
@Override
public final void visitInnerClass(
final String name,
final String outerName,
final String innerName,
final int access)
{
if (innerClasses == null) {
innerClasses = new ByteVector();
}
++innerClassesCount;
innerClasses.putShort(name == null ? 0 : newClass(name));
innerClasses.putShort(outerName == null ? 0 : newClass(outerName));
innerClasses.putShort(innerName == null ? 0 : newUTF8(innerName));
innerClasses.putShort(access);
}
@Override
public final FieldVisitor visitField(
final int access,
final String name,
final String desc,
final String signature,
final Object value)
{
return new FieldWriter(this, access, name, desc, signature, value);
}
@Override
public final MethodVisitor visitMethod(
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions)
{
return new MethodWriter(this,
access,
name,
desc,
signature,
exceptions,
computeMaxs,
computeFrames);
}
@Override
public final void visitEnd() {
}
// ------------------------------------------------------------------------
// Other public methods
// ------------------------------------------------------------------------
/**
* Returns the bytecode of the class that was build with this class writer.
*
* @return the bytecode of the class that was build with this class writer.
*/
public byte[] toByteArray() {
- if (index > Short.MAX_VALUE) {
+ if (index > 0xFFFF) {
throw new RuntimeException("Class file too large!");
}
// computes the real size of the bytecode of this class
int size = 24 + 2 * interfaceCount;
int nbFields = 0;
FieldWriter fb = firstField;
while (fb != null) {
++nbFields;
size += fb.getSize();
fb = (FieldWriter) fb.fv;
}
int nbMethods = 0;
MethodWriter mb = firstMethod;
while (mb != null) {
++nbMethods;
size += mb.getSize();
mb = (MethodWriter) mb.mv;
}
int attributeCount = 0;
if (bootstrapMethods != null) { // we put it as first argument in order
// to improve a bit ClassReader.copyBootstrapMethods
++attributeCount;
size += 8 + bootstrapMethods.length;
newUTF8("BootstrapMethods");
}
if (ClassReader.SIGNATURES && signature != 0) {
++attributeCount;
size += 8;
newUTF8("Signature");
}
if (sourceFile != 0) {
++attributeCount;
size += 8;
newUTF8("SourceFile");
}
if (sourceDebug != null) {
++attributeCount;
size += sourceDebug.length + 4;
newUTF8("SourceDebugExtension");
}
if (enclosingMethodOwner != 0) {
++attributeCount;
size += 10;
newUTF8("EnclosingMethod");
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
size += 6;
newUTF8("Deprecated");
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
++attributeCount;
size += 6;
newUTF8("Synthetic");
}
if (innerClasses != null) {
++attributeCount;
size += 8 + innerClasses.length;
newUTF8("InnerClasses");
}
if (ClassReader.ANNOTATIONS && anns != null) {
++attributeCount;
size += 8 + anns.getSize();
newUTF8("RuntimeVisibleAnnotations");
}
if (ClassReader.ANNOTATIONS && ianns != null) {
++attributeCount;
size += 8 + ianns.getSize();
newUTF8("RuntimeInvisibleAnnotations");
}
if (attrs != null) {
attributeCount += attrs.getCount();
size += attrs.getSize(this, null, 0, -1, -1);
}
size += pool.length;
// allocates a byte vector of this size, in order to avoid unnecessary
// arraycopy operations in the ByteVector.enlarge() method
ByteVector out = new ByteVector(size);
out.putInt(0xCAFEBABE).putInt(version);
out.putShort(index).putByteArray(pool.data, 0, pool.length);
int mask = Opcodes.ACC_DEPRECATED
| ClassWriter.ACC_SYNTHETIC_ATTRIBUTE
| ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC));
out.putShort(access & ~mask).putShort(name).putShort(superName);
out.putShort(interfaceCount);
for (int i = 0; i < interfaceCount; ++i) {
out.putShort(interfaces[i]);
}
out.putShort(nbFields);
fb = firstField;
while (fb != null) {
fb.put(out);
fb = (FieldWriter) fb.fv;
}
out.putShort(nbMethods);
mb = firstMethod;
while (mb != null) {
mb.put(out);
mb = (MethodWriter) mb.mv;
}
out.putShort(attributeCount);
if (bootstrapMethods != null) { // should be the first class attribute ?
out.putShort(newUTF8("BootstrapMethods"));
out.putInt(bootstrapMethods.length + 2).putShort(bootstrapMethodsCount);
out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
}
if (ClassReader.SIGNATURES && signature != 0) {
out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
}
if (sourceFile != 0) {
out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
}
if (sourceDebug != null) {
int len = sourceDebug.length - 2;
out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
out.putByteArray(sourceDebug.data, 2, len);
}
if (enclosingMethodOwner != 0) {
out.putShort(newUTF8("EnclosingMethod")).putInt(4);
out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
out.putShort(newUTF8("Deprecated")).putInt(0);
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
out.putShort(newUTF8("Synthetic")).putInt(0);
}
if (innerClasses != null) {
out.putShort(newUTF8("InnerClasses"));
out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
out.putByteArray(innerClasses.data, 0, innerClasses.length);
}
if (ClassReader.ANNOTATIONS && anns != null) {
out.putShort(newUTF8("RuntimeVisibleAnnotations"));
anns.put(out);
}
if (ClassReader.ANNOTATIONS && ianns != null) {
out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
ianns.put(out);
}
if (attrs != null) {
attrs.put(this, null, 0, -1, -1, out);
}
if (invalidFrames) {
ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
new ClassReader(out.data).accept(cw, ClassReader.SKIP_FRAMES);
return cw.toByteArray();
}
return out.data;
}
// ------------------------------------------------------------------------
// Utility methods: constant pool management
// ------------------------------------------------------------------------
/**
* Adds a number or string constant to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
*
* @param cst the value of the constant to be added to the constant pool.
* This parameter must be an {@link Integer}, a {@link Float}, a
* {@link Long}, a {@link Double}, a {@link String} or a
* {@link Type}.
* @return a new or already existing constant item with the given value.
*/
Item newConstItem(final Object cst) {
if (cst instanceof Integer) {
int val = ((Integer) cst).intValue();
return newInteger(val);
} else if (cst instanceof Byte) {
int val = ((Byte) cst).intValue();
return newInteger(val);
} else if (cst instanceof Character) {
int val = ((Character) cst).charValue();
return newInteger(val);
} else if (cst instanceof Short) {
int val = ((Short) cst).intValue();
return newInteger(val);
} else if (cst instanceof Boolean) {
int val = ((Boolean) cst).booleanValue() ? 1 : 0;
return newInteger(val);
} else if (cst instanceof Float) {
float val = ((Float) cst).floatValue();
return newFloat(val);
} else if (cst instanceof Long) {
long val = ((Long) cst).longValue();
return newLong(val);
} else if (cst instanceof Double) {
double val = ((Double) cst).doubleValue();
return newDouble(val);
} else if (cst instanceof String) {
return newString((String) cst);
} else if (cst instanceof Type) {
Type t = (Type) cst;
int s = t.getSort();
if (s == Type.OBJECT) {
return newClassItem(t.getInternalName());
} else if (s == Type.METHOD) {
return newMethodTypeItem(t.getDescriptor());
} else { // s == primitive type or array
return newClassItem(t.getDescriptor());
}
} else if (cst instanceof Handle) {
Handle h = (Handle) cst;
return newHandleItem(h.tag, h.owner, h.name, h.desc);
} else {
throw new IllegalArgumentException("value " + cst);
}
}
/**
* Adds a number or string constant to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param cst the value of the constant to be added to the constant pool.
* This parameter must be an {@link Integer}, a {@link Float}, a
* {@link Long}, a {@link Double} or a {@link String}.
* @return the index of a new or already existing constant item with the
* given value.
*/
public int newConst(final Object cst) {
return newConstItem(cst).index;
}
/**
* Adds an UTF8 string to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item. <i>This
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param value the String value.
* @return the index of a new or already existing UTF8 item.
*/
public int newUTF8(final String value) {
key.set(UTF8, value, null, null);
Item result = get(key);
if (result == null) {
pool.putByte(UTF8).putUTF8(value);
result = new Item(index++, key);
put(result);
}
return result.index;
}
/**
* Adds a class reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param value the internal name of the class.
* @return a new or already existing class reference item.
*/
Item newClassItem(final String value) {
key2.set(CLASS, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(CLASS, newUTF8(value));
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds a class reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param value the internal name of the class.
* @return the index of a new or already existing class reference item.
*/
public int newClass(final String value) {
return newClassItem(value).index;
}
/**
* Adds a method type reference to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param methodDesc method descriptor of the method type.
* @return a new or already existing method type reference item.
*/
Item newMethodTypeItem(final String methodDesc) {
key2.set(MTYPE, methodDesc, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(MTYPE, newUTF8(methodDesc));
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds a method type reference to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param methodDesc method descriptor of the method type.
* @return the index of a new or already existing method type reference
* item.
*/
public int newMethodType(final String methodDesc) {
return newMethodTypeItem(methodDesc).index;
}
/**
* Adds a handle to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item. <i>This method is
* intended for {@link Attribute} sub classes, and is normally not needed by
* class generators or adapters.</i>
*
* @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
* {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
* {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
* {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL},
* {@link Opcodes#H_NEWINVOKESPECIAL} or
* {@link Opcodes#H_INVOKEINTERFACE}.
* @param owner the internal name of the field or method owner class.
* @param name the name of the field or method.
* @param desc the descriptor of the field or method.
* @return a new or an already existing method type reference item.
*/
Item newHandleItem(
final int tag,
final String owner,
final String name,
final String desc)
{
key4.set(HANDLE_BASE + tag, owner, name, desc);
Item result = get(key4);
if (result == null) {
if (tag <= Opcodes.H_PUTSTATIC) {
put112(HANDLE, tag, newField(owner, name, desc));
} else {
put112(HANDLE, tag, newMethod(owner,
name,
desc,
tag == Opcodes.H_INVOKEINTERFACE));
}
result = new Item(index++, key4);
put(result);
}
return result;
}
/**
* Adds a handle to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD},
* {@link Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD},
* {@link Opcodes#H_PUTSTATIC}, {@link Opcodes#H_INVOKEVIRTUAL},
* {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL},
* {@link Opcodes#H_NEWINVOKESPECIAL} or
* {@link Opcodes#H_INVOKEINTERFACE}.
* @param owner the internal name of the field or method owner class.
* @param name the name of the field or method.
* @param desc the descriptor of the field or method.
* @return the index of a new or already existing method type reference
* item.
*/
public int newHandle(
final int tag,
final String owner,
final String name,
final String desc)
{
return newHandleItem(tag, owner, name, desc).index;
}
/**
* Adds an invokedynamic reference to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param name name of the invoked method.
* @param desc descriptor of the invoke method.
* @param bsm the bootstrap method.
* @param bsmArgs the bootstrap method constant arguments.
*
* @return a new or an already existing invokedynamic type reference item.
*/
Item newInvokeDynamicItem(
final String name,
final String desc,
final Handle bsm,
final Object... bsmArgs)
{
// cache for performance
ByteVector bootstrapMethods = this.bootstrapMethods;
if (bootstrapMethods == null) {
bootstrapMethods = this.bootstrapMethods = new ByteVector();
}
int position = bootstrapMethods.length; // record current position
int hashCode = bsm.hashCode();
bootstrapMethods.putShort(newHandle(bsm.tag,
bsm.owner,
bsm.name,
bsm.desc));
int argsLength = bsmArgs.length;
bootstrapMethods.putShort(argsLength);
for (int i = 0; i < argsLength; i++) {
Object bsmArg = bsmArgs[i];
hashCode ^= bsmArg.hashCode();
bootstrapMethods.putShort(newConst(bsmArg));
}
byte[] data = bootstrapMethods.data;
int length = (1 + 1 + argsLength) << 1; // (bsm + argCount + arguments)
hashCode &= 0x7FFFFFFF;
Item result = items[hashCode % items.length];
loop: while (result != null) {
if (result.type != BSM || result.hashCode != hashCode) {
result = result.next;
continue;
}
// because the data encode the size of the argument
// we don't need to test if these size are equals
int resultPosition = result.intVal;
for (int p = 0; p < length; p++) {
if (data[position + p] != data[resultPosition + p]) {
result = result.next;
continue loop;
}
}
break;
}
int bootstrapMethodIndex;
if (result != null) {
bootstrapMethodIndex = result.index;
bootstrapMethods.length = position; // revert to old position
} else {
bootstrapMethodIndex = bootstrapMethodsCount++;
result = new Item(bootstrapMethodIndex);
result.set(position, hashCode);
put(result);
}
// now, create the InvokeDynamic constant
key3.set(name, desc, bootstrapMethodIndex);
result = get(key3);
if (result == null) {
put122(INDY, bootstrapMethodIndex, newNameType(name, desc));
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds an invokedynamic reference to the constant pool of the class being
* build. Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param name name of the invoked method.
* @param desc descriptor of the invoke method.
* @param bsm the bootstrap method.
* @param bsmArgs the bootstrap method constant arguments.
*
* @return the index of a new or already existing invokedynamic
* reference item.
*/
public int newInvokeDynamic(
final String name,
final String desc,
final Handle bsm,
final Object... bsmArgs)
{
return newInvokeDynamicItem(name, desc, bsm, bsmArgs).index;
}
/**
* Adds a field reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
*
* @param owner the internal name of the field's owner class.
* @param name the field's name.
* @param desc the field's descriptor.
* @return a new or already existing field reference item.
*/
Item newFieldItem(final String owner, final String name, final String desc)
{
key3.set(FIELD, owner, name, desc);
Item result = get(key3);
if (result == null) {
put122(FIELD, newClass(owner), newNameType(name, desc));
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds a field reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param owner the internal name of the field's owner class.
* @param name the field's name.
* @param desc the field's descriptor.
* @return the index of a new or already existing field reference item.
*/
public int newField(final String owner, final String name, final String desc)
{
return newFieldItem(owner, name, desc).index;
}
/**
* Adds a method reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
*
* @param owner the internal name of the method's owner class.
* @param name the method's name.
* @param desc the method's descriptor.
* @param itf <tt>true</tt> if <tt>owner</tt> is an interface.
* @return a new or already existing method reference item.
*/
Item newMethodItem(
final String owner,
final String name,
final String desc,
final boolean itf)
{
int type = itf ? IMETH : METH;
key3.set(type, owner, name, desc);
Item result = get(key3);
if (result == null) {
put122(type, newClass(owner), newNameType(name, desc));
result = new Item(index++, key3);
put(result);
}
return result;
}
/**
* Adds a method reference to the constant pool of the class being build.
* Does nothing if the constant pool already contains a similar item.
* <i>This method is intended for {@link Attribute} sub classes, and is
* normally not needed by class generators or adapters.</i>
*
* @param owner the internal name of the method's owner class.
* @param name the method's name.
* @param desc the method's descriptor.
* @param itf <tt>true</tt> if <tt>owner</tt> is an interface.
* @return the index of a new or already existing method reference item.
*/
public int newMethod(
final String owner,
final String name,
final String desc,
final boolean itf)
{
return newMethodItem(owner, name, desc, itf).index;
}
/**
* Adds an integer to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item.
*
* @param value the int value.
* @return a new or already existing int item.
*/
Item newInteger(final int value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(INT).putInt(value);
result = new Item(index++, key);
put(result);
}
return result;
}
/**
* Adds a float to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the float value.
* @return a new or already existing float item.
*/
Item newFloat(final float value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(FLOAT).putInt(key.intVal);
result = new Item(index++, key);
put(result);
}
return result;
}
/**
* Adds a long to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the long value.
* @return a new or already existing long item.
*/
Item newLong(final long value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(LONG).putLong(value);
result = new Item(index, key);
index += 2;
put(result);
}
return result;
}
/**
* Adds a double to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the double value.
* @return a new or already existing double item.
*/
Item newDouble(final double value) {
key.set(value);
Item result = get(key);
if (result == null) {
pool.putByte(DOUBLE).putLong(key.longVal);
result = new Item(index, key);
index += 2;
put(result);
}
return result;
}
/**
* Adds a string to the constant pool of the class being build. Does nothing
* if the constant pool already contains a similar item.
*
* @param value the String value.
* @return a new or already existing string item.
*/
private Item newString(final String value) {
key2.set(STR, value, null, null);
Item result = get(key2);
if (result == null) {
pool.put12(STR, newUTF8(value));
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds a name and type to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item. <i>This
* method is intended for {@link Attribute} sub classes, and is normally not
* needed by class generators or adapters.</i>
*
* @param name a name.
* @param desc a type descriptor.
* @return the index of a new or already existing name and type item.
*/
public int newNameType(final String name, final String desc) {
return newNameTypeItem(name, desc).index;
}
/**
* Adds a name and type to the constant pool of the class being build. Does
* nothing if the constant pool already contains a similar item.
*
* @param name a name.
* @param desc a type descriptor.
* @return a new or already existing name and type item.
*/
Item newNameTypeItem(final String name, final String desc) {
key2.set(NAME_TYPE, name, desc, null);
Item result = get(key2);
if (result == null) {
put122(NAME_TYPE, newUTF8(name), newUTF8(desc));
result = new Item(index++, key2);
put(result);
}
return result;
}
/**
* Adds the given internal name to {@link #typeTable} and returns its index.
* Does nothing if the type table already contains this internal name.
*
* @param type the internal name to be added to the type table.
* @return the index of this internal name in the type table.
*/
int addType(final String type) {
key.set(TYPE_NORMAL, type, null, null);
Item result = get(key);
if (result == null) {
result = addType(key);
}
return result.index;
}
/**
* Adds the given "uninitialized" type to {@link #typeTable} and returns its
* index. This method is used for UNINITIALIZED types, made of an internal
* name and a bytecode offset.
*
* @param type the internal name to be added to the type table.
* @param offset the bytecode offset of the NEW instruction that created
* this UNINITIALIZED type value.
* @return the index of this internal name in the type table.
*/
int addUninitializedType(final String type, final int offset) {
key.type = TYPE_UNINIT;
key.intVal = offset;
key.strVal1 = type;
key.hashCode = 0x7FFFFFFF & (TYPE_UNINIT + type.hashCode() + offset);
Item result = get(key);
if (result == null) {
result = addType(key);
}
return result.index;
}
/**
* Adds the given Item to {@link #typeTable}.
*
* @param item the value to be added to the type table.
* @return the added Item, which a new Item instance with the same value as
* the given Item.
*/
private Item addType(final Item item) {
++typeCount;
Item result = new Item(typeCount, key);
put(result);
if (typeTable == null) {
typeTable = new Item[16];
}
if (typeCount == typeTable.length) {
Item[] newTable = new Item[2 * typeTable.length];
System.arraycopy(typeTable, 0, newTable, 0, typeTable.length);
typeTable = newTable;
}
typeTable[typeCount] = result;
return result;
}
/**
* Returns the index of the common super type of the two given types. This
* method calls {@link #getCommonSuperClass} and caches the result in the
* {@link #items} hash table to speedup future calls with the same
* parameters.
*
* @param type1 index of an internal name in {@link #typeTable}.
* @param type2 index of an internal name in {@link #typeTable}.
* @return the index of the common super type of the two given types.
*/
int getMergedType(final int type1, final int type2) {
key2.type = TYPE_MERGED;
key2.longVal = type1 | (((long) type2) << 32);
key2.hashCode = 0x7FFFFFFF & (TYPE_MERGED + type1 + type2);
Item result = get(key2);
if (result == null) {
String t = typeTable[type1].strVal1;
String u = typeTable[type2].strVal1;
key2.intVal = addType(getCommonSuperClass(t, u));
result = new Item((short) 0, key2);
put(result);
}
return result.intVal;
}
/**
* Returns the common super type of the two given types. The default
* implementation of this method <i>loads<i> the two given classes and uses
* the java.lang.Class methods to find the common super class. It can be
* overridden to compute this common super type in other ways, in particular
* without actually loading any class, or to take into account the class
* that is currently being generated by this ClassWriter, which can of
* course not be loaded since it is under construction.
*
* @param type1 the internal name of a class.
* @param type2 the internal name of another class.
* @return the internal name of the common super class of the two given
* classes.
*/
protected String getCommonSuperClass(final String type1, final String type2)
{
Class<?> c, d;
ClassLoader classLoader = getClass().getClassLoader();
try {
c = Class.forName(type1.replace('/', '.'), false, classLoader);
d = Class.forName(type2.replace('/', '.'), false, classLoader);
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
if (c.isAssignableFrom(d)) {
return type1;
}
if (d.isAssignableFrom(c)) {
return type2;
}
if (c.isInterface() || d.isInterface()) {
return "java/lang/Object";
} else {
do {
c = c.getSuperclass();
} while (!c.isAssignableFrom(d));
return c.getName().replace('.', '/');
}
}
/**
* Returns the constant pool's hash table item which is equal to the given
* item.
*
* @param key a constant pool item.
* @return the constant pool's hash table item which is equal to the given
* item, or <tt>null</tt> if there is no such item.
*/
private Item get(final Item key) {
Item i = items[key.hashCode % items.length];
while (i != null && (i.type != key.type || !key.isEqualTo(i))) {
i = i.next;
}
return i;
}
/**
* Puts the given item in the constant pool's hash table. The hash table
* <i>must</i> not already contains this item.
*
* @param i the item to be added to the constant pool's hash table.
*/
private void put(final Item i) {
if (index + typeCount > threshold) {
int ll = items.length;
int nl = ll * 2 + 1;
Item[] newItems = new Item[nl];
for (int l = ll - 1; l >= 0; --l) {
Item j = items[l];
while (j != null) {
int index = j.hashCode % newItems.length;
Item k = j.next;
j.next = newItems[index];
newItems[index] = j;
j = k;
}
}
items = newItems;
threshold = (int) (nl * 0.75);
}
int index = i.hashCode % items.length;
i.next = items[index];
items[index] = i;
}
/**
* Puts one byte and two shorts into the constant pool.
*
* @param b a byte.
* @param s1 a short.
* @param s2 another short.
*/
private void put122(final int b, final int s1, final int s2) {
pool.put12(b, s1).putShort(s2);
}
/**
* Puts two bytes and one short into the constant pool.
*
* @param b1 a byte.
* @param b2 another byte.
* @param s a short.
*/
private void put112(final int b1, final int b2, final int s) {
pool.put11(b1, b2).putShort(s);
}
}
| true | true | public byte[] toByteArray() {
if (index > Short.MAX_VALUE) {
throw new RuntimeException("Class file too large!");
}
// computes the real size of the bytecode of this class
int size = 24 + 2 * interfaceCount;
int nbFields = 0;
FieldWriter fb = firstField;
while (fb != null) {
++nbFields;
size += fb.getSize();
fb = (FieldWriter) fb.fv;
}
int nbMethods = 0;
MethodWriter mb = firstMethod;
while (mb != null) {
++nbMethods;
size += mb.getSize();
mb = (MethodWriter) mb.mv;
}
int attributeCount = 0;
if (bootstrapMethods != null) { // we put it as first argument in order
// to improve a bit ClassReader.copyBootstrapMethods
++attributeCount;
size += 8 + bootstrapMethods.length;
newUTF8("BootstrapMethods");
}
if (ClassReader.SIGNATURES && signature != 0) {
++attributeCount;
size += 8;
newUTF8("Signature");
}
if (sourceFile != 0) {
++attributeCount;
size += 8;
newUTF8("SourceFile");
}
if (sourceDebug != null) {
++attributeCount;
size += sourceDebug.length + 4;
newUTF8("SourceDebugExtension");
}
if (enclosingMethodOwner != 0) {
++attributeCount;
size += 10;
newUTF8("EnclosingMethod");
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
size += 6;
newUTF8("Deprecated");
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
++attributeCount;
size += 6;
newUTF8("Synthetic");
}
if (innerClasses != null) {
++attributeCount;
size += 8 + innerClasses.length;
newUTF8("InnerClasses");
}
if (ClassReader.ANNOTATIONS && anns != null) {
++attributeCount;
size += 8 + anns.getSize();
newUTF8("RuntimeVisibleAnnotations");
}
if (ClassReader.ANNOTATIONS && ianns != null) {
++attributeCount;
size += 8 + ianns.getSize();
newUTF8("RuntimeInvisibleAnnotations");
}
if (attrs != null) {
attributeCount += attrs.getCount();
size += attrs.getSize(this, null, 0, -1, -1);
}
size += pool.length;
// allocates a byte vector of this size, in order to avoid unnecessary
// arraycopy operations in the ByteVector.enlarge() method
ByteVector out = new ByteVector(size);
out.putInt(0xCAFEBABE).putInt(version);
out.putShort(index).putByteArray(pool.data, 0, pool.length);
int mask = Opcodes.ACC_DEPRECATED
| ClassWriter.ACC_SYNTHETIC_ATTRIBUTE
| ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC));
out.putShort(access & ~mask).putShort(name).putShort(superName);
out.putShort(interfaceCount);
for (int i = 0; i < interfaceCount; ++i) {
out.putShort(interfaces[i]);
}
out.putShort(nbFields);
fb = firstField;
while (fb != null) {
fb.put(out);
fb = (FieldWriter) fb.fv;
}
out.putShort(nbMethods);
mb = firstMethod;
while (mb != null) {
mb.put(out);
mb = (MethodWriter) mb.mv;
}
out.putShort(attributeCount);
if (bootstrapMethods != null) { // should be the first class attribute ?
out.putShort(newUTF8("BootstrapMethods"));
out.putInt(bootstrapMethods.length + 2).putShort(bootstrapMethodsCount);
out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
}
if (ClassReader.SIGNATURES && signature != 0) {
out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
}
if (sourceFile != 0) {
out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
}
if (sourceDebug != null) {
int len = sourceDebug.length - 2;
out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
out.putByteArray(sourceDebug.data, 2, len);
}
if (enclosingMethodOwner != 0) {
out.putShort(newUTF8("EnclosingMethod")).putInt(4);
out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
out.putShort(newUTF8("Deprecated")).putInt(0);
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
out.putShort(newUTF8("Synthetic")).putInt(0);
}
if (innerClasses != null) {
out.putShort(newUTF8("InnerClasses"));
out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
out.putByteArray(innerClasses.data, 0, innerClasses.length);
}
if (ClassReader.ANNOTATIONS && anns != null) {
out.putShort(newUTF8("RuntimeVisibleAnnotations"));
anns.put(out);
}
if (ClassReader.ANNOTATIONS && ianns != null) {
out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
ianns.put(out);
}
if (attrs != null) {
attrs.put(this, null, 0, -1, -1, out);
}
if (invalidFrames) {
ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
new ClassReader(out.data).accept(cw, ClassReader.SKIP_FRAMES);
return cw.toByteArray();
}
return out.data;
}
| public byte[] toByteArray() {
if (index > 0xFFFF) {
throw new RuntimeException("Class file too large!");
}
// computes the real size of the bytecode of this class
int size = 24 + 2 * interfaceCount;
int nbFields = 0;
FieldWriter fb = firstField;
while (fb != null) {
++nbFields;
size += fb.getSize();
fb = (FieldWriter) fb.fv;
}
int nbMethods = 0;
MethodWriter mb = firstMethod;
while (mb != null) {
++nbMethods;
size += mb.getSize();
mb = (MethodWriter) mb.mv;
}
int attributeCount = 0;
if (bootstrapMethods != null) { // we put it as first argument in order
// to improve a bit ClassReader.copyBootstrapMethods
++attributeCount;
size += 8 + bootstrapMethods.length;
newUTF8("BootstrapMethods");
}
if (ClassReader.SIGNATURES && signature != 0) {
++attributeCount;
size += 8;
newUTF8("Signature");
}
if (sourceFile != 0) {
++attributeCount;
size += 8;
newUTF8("SourceFile");
}
if (sourceDebug != null) {
++attributeCount;
size += sourceDebug.length + 4;
newUTF8("SourceDebugExtension");
}
if (enclosingMethodOwner != 0) {
++attributeCount;
size += 10;
newUTF8("EnclosingMethod");
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
++attributeCount;
size += 6;
newUTF8("Deprecated");
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
++attributeCount;
size += 6;
newUTF8("Synthetic");
}
if (innerClasses != null) {
++attributeCount;
size += 8 + innerClasses.length;
newUTF8("InnerClasses");
}
if (ClassReader.ANNOTATIONS && anns != null) {
++attributeCount;
size += 8 + anns.getSize();
newUTF8("RuntimeVisibleAnnotations");
}
if (ClassReader.ANNOTATIONS && ianns != null) {
++attributeCount;
size += 8 + ianns.getSize();
newUTF8("RuntimeInvisibleAnnotations");
}
if (attrs != null) {
attributeCount += attrs.getCount();
size += attrs.getSize(this, null, 0, -1, -1);
}
size += pool.length;
// allocates a byte vector of this size, in order to avoid unnecessary
// arraycopy operations in the ByteVector.enlarge() method
ByteVector out = new ByteVector(size);
out.putInt(0xCAFEBABE).putInt(version);
out.putShort(index).putByteArray(pool.data, 0, pool.length);
int mask = Opcodes.ACC_DEPRECATED
| ClassWriter.ACC_SYNTHETIC_ATTRIBUTE
| ((access & ClassWriter.ACC_SYNTHETIC_ATTRIBUTE) / (ClassWriter.ACC_SYNTHETIC_ATTRIBUTE / Opcodes.ACC_SYNTHETIC));
out.putShort(access & ~mask).putShort(name).putShort(superName);
out.putShort(interfaceCount);
for (int i = 0; i < interfaceCount; ++i) {
out.putShort(interfaces[i]);
}
out.putShort(nbFields);
fb = firstField;
while (fb != null) {
fb.put(out);
fb = (FieldWriter) fb.fv;
}
out.putShort(nbMethods);
mb = firstMethod;
while (mb != null) {
mb.put(out);
mb = (MethodWriter) mb.mv;
}
out.putShort(attributeCount);
if (bootstrapMethods != null) { // should be the first class attribute ?
out.putShort(newUTF8("BootstrapMethods"));
out.putInt(bootstrapMethods.length + 2).putShort(bootstrapMethodsCount);
out.putByteArray(bootstrapMethods.data, 0, bootstrapMethods.length);
}
if (ClassReader.SIGNATURES && signature != 0) {
out.putShort(newUTF8("Signature")).putInt(2).putShort(signature);
}
if (sourceFile != 0) {
out.putShort(newUTF8("SourceFile")).putInt(2).putShort(sourceFile);
}
if (sourceDebug != null) {
int len = sourceDebug.length - 2;
out.putShort(newUTF8("SourceDebugExtension")).putInt(len);
out.putByteArray(sourceDebug.data, 2, len);
}
if (enclosingMethodOwner != 0) {
out.putShort(newUTF8("EnclosingMethod")).putInt(4);
out.putShort(enclosingMethodOwner).putShort(enclosingMethod);
}
if ((access & Opcodes.ACC_DEPRECATED) != 0) {
out.putShort(newUTF8("Deprecated")).putInt(0);
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0
&& ((version & 0xFFFF) < Opcodes.V1_5 || (access & ACC_SYNTHETIC_ATTRIBUTE) != 0))
{
out.putShort(newUTF8("Synthetic")).putInt(0);
}
if (innerClasses != null) {
out.putShort(newUTF8("InnerClasses"));
out.putInt(innerClasses.length + 2).putShort(innerClassesCount);
out.putByteArray(innerClasses.data, 0, innerClasses.length);
}
if (ClassReader.ANNOTATIONS && anns != null) {
out.putShort(newUTF8("RuntimeVisibleAnnotations"));
anns.put(out);
}
if (ClassReader.ANNOTATIONS && ianns != null) {
out.putShort(newUTF8("RuntimeInvisibleAnnotations"));
ianns.put(out);
}
if (attrs != null) {
attrs.put(this, null, 0, -1, -1, out);
}
if (invalidFrames) {
ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
new ClassReader(out.data).accept(cw, ClassReader.SKIP_FRAMES);
return cw.toByteArray();
}
return out.data;
}
|
diff --git a/src/main/java/jstreamserver/http/LiveStreamHandler.java b/src/main/java/jstreamserver/http/LiveStreamHandler.java
index db682ed..853e0da 100755
--- a/src/main/java/jstreamserver/http/LiveStreamHandler.java
+++ b/src/main/java/jstreamserver/http/LiveStreamHandler.java
@@ -1,314 +1,314 @@
/*
* Copyright (c) 2011 Sergey Prilukin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package jstreamserver.http;
import anhttpserver.HttpRequestContext;
import jstreamserver.utils.Config;
import jstreamserver.utils.HttpUtils;
import jstreamserver.utils.ffmpeg.FFMpegSegmenter;
import jstreamserver.utils.ffmpeg.FrameMessage;
import jstreamserver.utils.ffmpeg.ProgressListener;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TimeZone;
/**
* HTTP Live stream handler
* which implements <a href="http://developer.apple.com/resources/http-streaming/">HTTP Live Streaming</a>
* {@code FFMpeg} and some implementation of {@code video segmenter} are used on backend.
*
* @author Sergey Prilukin
*/
public final class LiveStreamHandler extends BaseHandler {
public static final String HANDLE_PATH = "/livestream";
public static final String LIVE_STREAM_FILE_PREFIX = "stream";
public static final String PLAYLIST_EXTENSION = "m3u8";
public static final String LIVE_STREAM_FILE_PATH = HANDLE_PATH.substring(1) + "/" + LIVE_STREAM_FILE_PREFIX;
public static final String PLAYLIST_FULL_PATH = HANDLE_PATH + "/" + LIVE_STREAM_FILE_PREFIX + "." + PLAYLIST_EXTENSION;
public static final SimpleDateFormat FFMPEG_SS_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
static {
FFMPEG_SS_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
}
private FFMpegSegmenter ffMpegSegmenter;
private final Object ffmpegSegmenterMonitor = new Object();
private final Object playListCreatedMonitor = new Object();
private ProgressListener progressListener = new LiveStreamProgressListener();
private SegmenterKiller segmenterKiller;
public LiveStreamHandler() {
super();
}
@Override
public InputStream getResponseInternal(HttpRequestContext httpRequestContext) throws IOException {
if (PLAYLIST_FULL_PATH.equals(httpRequestContext.getRequestURI().getPath())) {
return getPlayList(LIVE_STREAM_FILE_PATH + "." + PLAYLIST_EXTENSION, httpRequestContext);
} else if (HANDLE_PATH.equals(httpRequestContext.getRequestURI().getPath())) {
Map<String, String> params = HttpUtils.getURLParams(httpRequestContext.getRequestURI().getRawQuery());
String fileString = params.get("file");
String audioStreamId = params.get("stream");
File file = getFile(URLDecoder.decode(fileString, HttpUtils.DEFAULT_ENCODING));
if (!file.exists() || !file.isFile() || file.isHidden()) {
return rendeResourceNotFound(fileString, httpRequestContext);
} else {
//String startTime = params.containsKey("time") ? params.get("time") : FFMPEG_SS_DATE_FORMAT.format(new Date(0)); // start from the beginning by default
return getLiveStream(file, fileString, audioStreamId, httpRequestContext);
}
} else {
String path = httpRequestContext.getRequestURI().getPath();
File file = new File(path.substring(1));
if (file.exists() && file.isFile()) {
updateSegmenterKiller();
return getResource(file, httpRequestContext);
} else {
return rendeResourceNotFound(path, httpRequestContext);
}
}
}
/*
* Playlist file is written at the same time by another thread (by segmenter namely)
* and thus this thread can read non-completed version of the file.
* In this method we ensure that last line of playlist matches one of the possible formats
*/
private InputStream getPlayList(String playlist, HttpRequestContext httpRequestContext) throws IOException {
boolean fileIsOk = false;
StringBuilder sb = null;
while (!fileIsOk) {
BufferedReader reader = new BufferedReader(new FileReader(playlist));
sb = new StringBuilder();
String line = "";
while (true) {
String temp = reader.readLine();
if (temp != null) {
line = temp;
sb.append(line).append("\n");
} else {
fileIsOk = line.matches("^(.*\\.ts|#.*)$");
reader.close();
break;
}
}
}
String extension = FilenameUtils.getExtension(new File(playlist).getName());
String mimeType = getMimeProperties().getProperty(extension.toLowerCase());
setContentType(mimeType != null ? mimeType : "application/octet-stream", httpRequestContext);
setResponseHeader("Expires", HTTP_HEADER_DATE_FORMAT.get().format(new Date(0)), httpRequestContext);
setResponseHeader("Pragma", "no-cache", httpRequestContext);
setResponseHeader("Cache-Control", "no-store,private,no-cache", httpRequestContext);
setResponseHeader("Connection", "keep-alive", httpRequestContext);
setResponseHeader("Content-Disposition", "attachment", httpRequestContext);
setResponseCode(HttpURLConnection.HTTP_OK, httpRequestContext);
return new ByteArrayInputStream(sb.toString().getBytes());
}
private void cleanResources() {
synchronized (ffmpegSegmenterMonitor) {
if (ffMpegSegmenter != null) {
ffMpegSegmenter.destroy();
ffMpegSegmenter = null;
}
}
File streamDir = new File(HANDLE_PATH.substring(1));
if (!streamDir.exists()) {
streamDir.mkdirs();
}
//Remove all .ts and .m3u8 files
String[] files = streamDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String extension = FilenameUtils.getExtension(name);
return extension.equals(PLAYLIST_EXTENSION) || extension.equals("ts");
}
});
for (String fileName: files) {
File file = new File(streamDir + "/" + fileName);
if (file.exists()) {
file.delete();
}
}
}
private InputStream getLiveStream(File file, String fileString, String audioStreamId, HttpRequestContext httpRequestContext) throws IOException {
cleanResources();
String ffmpegMapStreamParams = audioStreamId != null ? String.format(Config.FFMPEG_AUDIO_STREAM_SELECTION_FORMAT, audioStreamId) : "";
synchronized (ffmpegSegmenterMonitor) {
ffMpegSegmenter = new FFMpegSegmenter();
ffMpegSegmenter.start(
getConfig().getFfmpegLocation(),
getConfig().getSegmenterLocation(),
String.format(getConfig().getFfmpegParams(), file.getAbsolutePath(), ffmpegMapStreamParams),
String.format(getConfig().getSegmenterParams(), LIVE_STREAM_FILE_PATH, PLAYLIST_FULL_PATH.substring(1)),
progressListener);
try {
synchronized (playListCreatedMonitor) {
playListCreatedMonitor.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
byte[] result = null;
try {
JSONObject jsonObject = new JSONObject();
JSONObject liveStreamSource = new JSONObject();
liveStreamSource.put("url", PLAYLIST_FULL_PATH);
liveStreamSource.put("type", getMimeProperties().getProperty(PLAYLIST_EXTENSION));
String extension = FilenameUtils.getExtension(file.getPath());
JSONObject originalSource = new JSONObject();
originalSource.put("url", "/?path=" + fileString);
originalSource.put("type", getMimeProperties().getProperty(extension));
JSONArray sources = new JSONArray();
sources.put(liveStreamSource);
sources.put(originalSource);
jsonObject.put("sources", sources);
//getFile
String subtitlesString = fileString.substring(0, fileString.length() - extension.length() - 1) + ".srt";
File subtitles = getFile(URLDecoder.decode(subtitlesString, HttpUtils.DEFAULT_ENCODING));
if (subtitles.exists()) {
FileInputStream fis = new FileInputStream(subtitles);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(fis, baos);
jsonObject.put("subtitle", baos.toString(getConfig().getDefaultTextCharset()));
} else {
- jsonObject.put("subtitle", null);
+ jsonObject.put("subtitle", "");
}
result = jsonObject.toString().getBytes();
setResponseCode(HttpURLConnection.HTTP_OK, httpRequestContext);
setContentType("text/x-json", httpRequestContext);
return renderCompressedView(new ByteArrayInputStream(result), httpRequestContext);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void updateSegmenterKiller() {
if (segmenterKiller == null) {
segmenterKiller = new SegmenterKiller();
segmenterKiller.start();
} else {
segmenterKiller.clearTimeout();
}
}
class SegmenterKiller extends Thread {
private boolean timeoutFlag = false;
public void clearTimeout() {
synchronized (ffmpegSegmenterMonitor) {
timeoutFlag = false;
ffmpegSegmenterMonitor.notify();
}
}
@Override
public void run() {
try {
synchronized (ffmpegSegmenterMonitor) {
while (true) {
timeoutFlag = true;
ffmpegSegmenterMonitor.wait(getConfig().getSegmenterMaxtimeout());
if (timeoutFlag && ffMpegSegmenter != null) {
System.out.println("Destroying idle ffmpeg segmenter...");
timeoutFlag = false;
cleanResources();
ffmpegSegmenterMonitor.wait();
}
}
}
} catch (InterruptedException e) {
/* do nothing */
}
}
}
class LiveStreamProgressListener implements ProgressListener {
@Override
public void onFrameMessage(FrameMessage frameMessage) {
}
@Override
public void onProgress(String progressString) {
}
@Override
public void onPlayListCreated() {
synchronized (playListCreatedMonitor) {
playListCreatedMonitor.notify();
}
}
@Override
public void onFinish(int exitCode) {
System.out.println("Segmenter finished. Exit code: " + exitCode);
}
}
}
| true | true | private InputStream getLiveStream(File file, String fileString, String audioStreamId, HttpRequestContext httpRequestContext) throws IOException {
cleanResources();
String ffmpegMapStreamParams = audioStreamId != null ? String.format(Config.FFMPEG_AUDIO_STREAM_SELECTION_FORMAT, audioStreamId) : "";
synchronized (ffmpegSegmenterMonitor) {
ffMpegSegmenter = new FFMpegSegmenter();
ffMpegSegmenter.start(
getConfig().getFfmpegLocation(),
getConfig().getSegmenterLocation(),
String.format(getConfig().getFfmpegParams(), file.getAbsolutePath(), ffmpegMapStreamParams),
String.format(getConfig().getSegmenterParams(), LIVE_STREAM_FILE_PATH, PLAYLIST_FULL_PATH.substring(1)),
progressListener);
try {
synchronized (playListCreatedMonitor) {
playListCreatedMonitor.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
byte[] result = null;
try {
JSONObject jsonObject = new JSONObject();
JSONObject liveStreamSource = new JSONObject();
liveStreamSource.put("url", PLAYLIST_FULL_PATH);
liveStreamSource.put("type", getMimeProperties().getProperty(PLAYLIST_EXTENSION));
String extension = FilenameUtils.getExtension(file.getPath());
JSONObject originalSource = new JSONObject();
originalSource.put("url", "/?path=" + fileString);
originalSource.put("type", getMimeProperties().getProperty(extension));
JSONArray sources = new JSONArray();
sources.put(liveStreamSource);
sources.put(originalSource);
jsonObject.put("sources", sources);
//getFile
String subtitlesString = fileString.substring(0, fileString.length() - extension.length() - 1) + ".srt";
File subtitles = getFile(URLDecoder.decode(subtitlesString, HttpUtils.DEFAULT_ENCODING));
if (subtitles.exists()) {
FileInputStream fis = new FileInputStream(subtitles);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(fis, baos);
jsonObject.put("subtitle", baos.toString(getConfig().getDefaultTextCharset()));
} else {
jsonObject.put("subtitle", null);
}
result = jsonObject.toString().getBytes();
setResponseCode(HttpURLConnection.HTTP_OK, httpRequestContext);
setContentType("text/x-json", httpRequestContext);
return renderCompressedView(new ByteArrayInputStream(result), httpRequestContext);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
| private InputStream getLiveStream(File file, String fileString, String audioStreamId, HttpRequestContext httpRequestContext) throws IOException {
cleanResources();
String ffmpegMapStreamParams = audioStreamId != null ? String.format(Config.FFMPEG_AUDIO_STREAM_SELECTION_FORMAT, audioStreamId) : "";
synchronized (ffmpegSegmenterMonitor) {
ffMpegSegmenter = new FFMpegSegmenter();
ffMpegSegmenter.start(
getConfig().getFfmpegLocation(),
getConfig().getSegmenterLocation(),
String.format(getConfig().getFfmpegParams(), file.getAbsolutePath(), ffmpegMapStreamParams),
String.format(getConfig().getSegmenterParams(), LIVE_STREAM_FILE_PATH, PLAYLIST_FULL_PATH.substring(1)),
progressListener);
try {
synchronized (playListCreatedMonitor) {
playListCreatedMonitor.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
byte[] result = null;
try {
JSONObject jsonObject = new JSONObject();
JSONObject liveStreamSource = new JSONObject();
liveStreamSource.put("url", PLAYLIST_FULL_PATH);
liveStreamSource.put("type", getMimeProperties().getProperty(PLAYLIST_EXTENSION));
String extension = FilenameUtils.getExtension(file.getPath());
JSONObject originalSource = new JSONObject();
originalSource.put("url", "/?path=" + fileString);
originalSource.put("type", getMimeProperties().getProperty(extension));
JSONArray sources = new JSONArray();
sources.put(liveStreamSource);
sources.put(originalSource);
jsonObject.put("sources", sources);
//getFile
String subtitlesString = fileString.substring(0, fileString.length() - extension.length() - 1) + ".srt";
File subtitles = getFile(URLDecoder.decode(subtitlesString, HttpUtils.DEFAULT_ENCODING));
if (subtitles.exists()) {
FileInputStream fis = new FileInputStream(subtitles);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(fis, baos);
jsonObject.put("subtitle", baos.toString(getConfig().getDefaultTextCharset()));
} else {
jsonObject.put("subtitle", "");
}
result = jsonObject.toString().getBytes();
setResponseCode(HttpURLConnection.HTTP_OK, httpRequestContext);
setContentType("text/x-json", httpRequestContext);
return renderCompressedView(new ByteArrayInputStream(result), httpRequestContext);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java b/src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java
index 9008b40..958f6d5 100644
--- a/src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java
+++ b/src/main/java/net/sf/katta/index/indexer/merge/SequenceFileToIndexJob.java
@@ -1,93 +1,93 @@
/**
* Copyright 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.katta.index.indexer.merge;
import net.sf.katta.index.indexer.ShardSelectionMapper;
import net.sf.katta.util.IndexConfiguration;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.log4j.Logger;
public class SequenceFileToIndexJob implements Configurable {
private final static Logger LOG = Logger.getLogger(SequenceFileToIndexJob.class);
private Configuration _configuration;
public void sequenceFileToIndex(Path sequenceFilePath, Path outputFolder) throws Exception {
JobConf jobConf = new IndexConfiguration().createJobConf(_configuration);
jobConf.setJobName("SequenceFileToIndex");
// input and output format
jobConf.setInputFormat(SequenceFileInputFormat.class);
// no output format will be reduced because the index will be creat local
// and will be copied into the hds
// input and output path
// overwrite the settet input path which is set via IndexJobConf.create
jobConf.set("mapred.input.dir", "");
LOG.info("read document informations from sequence file: " + sequenceFilePath);
jobConf.addInputPath(sequenceFilePath);
// configure the mapper
jobConf.setMapOutputKeyClass(Text.class);
jobConf.setMapOutputValueClass(BytesWritable.class);
jobConf.setMapperClass(ShardSelectionMapper.class);
// the input key and input value class which is saved in the sequence file
// will be mapped out as value: BytesWritable
jobConf.set("index.input.key.class", Text.class.getName());
jobConf.set("index.input.value.class", DocumentInformation.class.getName());
- Path newOutputPath = new Path(jobConf.get(IndexConfiguration.MAPRED_OUTPUT_PATH), outputFolder.getName());
+ Path newOutputPath = new Path(jobConf.getOutputPath(), outputFolder.getName());
LOG.info("set mapred folder to: " + newOutputPath);
jobConf.setOutputPath(newOutputPath);
LOG.info("set index upload folder: '" + outputFolder + "'");
jobConf.set(IndexConfiguration.INDEX_UPLOAD_PATH, outputFolder.toString());
jobConf.set("document.factory.class", DfsIndexDocumentFactory.class.getName());
// run the job
JobClient.runJob(jobConf);
}
public void setConf(Configuration configuration) {
_configuration = configuration;
}
public Configuration getConf() {
return _configuration;
}
public static void main(String[] args) throws Exception {
SequenceFileToIndexJob mergeJob = new SequenceFileToIndexJob();
JobConf jobConf = new JobConf();
jobConf.setJarByClass(SequenceFileToIndexJob.class);
new IndexConfiguration().enrichJobConf(jobConf, IndexConfiguration.INDEX_SHARD_KEY_GENERATOR_CLASS);
mergeJob.setConf(jobConf);
mergeJob.sequenceFileToIndex(new Path(args[0]), new Path("/tmp/" + System.currentTimeMillis()));
}
}
| true | true | public void sequenceFileToIndex(Path sequenceFilePath, Path outputFolder) throws Exception {
JobConf jobConf = new IndexConfiguration().createJobConf(_configuration);
jobConf.setJobName("SequenceFileToIndex");
// input and output format
jobConf.setInputFormat(SequenceFileInputFormat.class);
// no output format will be reduced because the index will be creat local
// and will be copied into the hds
// input and output path
// overwrite the settet input path which is set via IndexJobConf.create
jobConf.set("mapred.input.dir", "");
LOG.info("read document informations from sequence file: " + sequenceFilePath);
jobConf.addInputPath(sequenceFilePath);
// configure the mapper
jobConf.setMapOutputKeyClass(Text.class);
jobConf.setMapOutputValueClass(BytesWritable.class);
jobConf.setMapperClass(ShardSelectionMapper.class);
// the input key and input value class which is saved in the sequence file
// will be mapped out as value: BytesWritable
jobConf.set("index.input.key.class", Text.class.getName());
jobConf.set("index.input.value.class", DocumentInformation.class.getName());
Path newOutputPath = new Path(jobConf.get(IndexConfiguration.MAPRED_OUTPUT_PATH), outputFolder.getName());
LOG.info("set mapred folder to: " + newOutputPath);
jobConf.setOutputPath(newOutputPath);
LOG.info("set index upload folder: '" + outputFolder + "'");
jobConf.set(IndexConfiguration.INDEX_UPLOAD_PATH, outputFolder.toString());
jobConf.set("document.factory.class", DfsIndexDocumentFactory.class.getName());
// run the job
JobClient.runJob(jobConf);
}
| public void sequenceFileToIndex(Path sequenceFilePath, Path outputFolder) throws Exception {
JobConf jobConf = new IndexConfiguration().createJobConf(_configuration);
jobConf.setJobName("SequenceFileToIndex");
// input and output format
jobConf.setInputFormat(SequenceFileInputFormat.class);
// no output format will be reduced because the index will be creat local
// and will be copied into the hds
// input and output path
// overwrite the settet input path which is set via IndexJobConf.create
jobConf.set("mapred.input.dir", "");
LOG.info("read document informations from sequence file: " + sequenceFilePath);
jobConf.addInputPath(sequenceFilePath);
// configure the mapper
jobConf.setMapOutputKeyClass(Text.class);
jobConf.setMapOutputValueClass(BytesWritable.class);
jobConf.setMapperClass(ShardSelectionMapper.class);
// the input key and input value class which is saved in the sequence file
// will be mapped out as value: BytesWritable
jobConf.set("index.input.key.class", Text.class.getName());
jobConf.set("index.input.value.class", DocumentInformation.class.getName());
Path newOutputPath = new Path(jobConf.getOutputPath(), outputFolder.getName());
LOG.info("set mapred folder to: " + newOutputPath);
jobConf.setOutputPath(newOutputPath);
LOG.info("set index upload folder: '" + outputFolder + "'");
jobConf.set(IndexConfiguration.INDEX_UPLOAD_PATH, outputFolder.toString());
jobConf.set("document.factory.class", DfsIndexDocumentFactory.class.getName());
// run the job
JobClient.runJob(jobConf);
}
|
diff --git a/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java b/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java
index 4b7d1ed..c8c7810 100644
--- a/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java
+++ b/src/me/sacnoth/bottledexp/BottledExpCommandExecutor.java
@@ -1,73 +1,74 @@
package me.sacnoth.bottledexp;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class BottledExpCommandExecutor implements CommandExecutor {
public BottledExpCommandExecutor(BottledExp plugin) {
}
@Override
public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
if ((sender instanceof Player)) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("bottle") && BottledExp.checkPermission("bottle.use", player)) {
int currentxp = player.getTotalExperience();
if (args.length == 0) {
sender.sendMessage(BottledExp.langCurrentXP + ": "
+ currentxp + " XP!");
} else if (args.length == 1) {
int amount;
if (args[0].equals("max")) {
if (BottledExp.checkPermission("bottle.max", player)) {
amount = (int) Math.floor(currentxp / 10);
}
else
{
return false;
}
} else {
try {
amount = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException nfe) {
sender.sendMessage(ChatColor.RED
+ BottledExp.errAmount);
return false;
}
}
if (currentxp < amount * BottledExp.xpCost) {
sender.sendMessage(ChatColor.RED + BottledExp.errXP);
}
- else if (amount == 0) {
+ else if (amount <= 0) {
+ amount = 0;
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
else {
PlayerInventory inventory = player.getInventory();
ItemStack items = new ItemStack(384, amount);
inventory.addItem(items);
player.setTotalExperience(0);
player.setLevel(0);
player.setExp(0);
player.giveExp(currentxp - (amount * BottledExp.xpCost));
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
}
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player!");
return false;
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
if ((sender instanceof Player)) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("bottle") && BottledExp.checkPermission("bottle.use", player)) {
int currentxp = player.getTotalExperience();
if (args.length == 0) {
sender.sendMessage(BottledExp.langCurrentXP + ": "
+ currentxp + " XP!");
} else if (args.length == 1) {
int amount;
if (args[0].equals("max")) {
if (BottledExp.checkPermission("bottle.max", player)) {
amount = (int) Math.floor(currentxp / 10);
}
else
{
return false;
}
} else {
try {
amount = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException nfe) {
sender.sendMessage(ChatColor.RED
+ BottledExp.errAmount);
return false;
}
}
if (currentxp < amount * BottledExp.xpCost) {
sender.sendMessage(ChatColor.RED + BottledExp.errXP);
}
else if (amount == 0) {
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
else {
PlayerInventory inventory = player.getInventory();
ItemStack items = new ItemStack(384, amount);
inventory.addItem(items);
player.setTotalExperience(0);
player.setLevel(0);
player.setExp(0);
player.giveExp(currentxp - (amount * BottledExp.xpCost));
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
}
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player!");
return false;
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd,
String commandLabel, String[] args) {
if ((sender instanceof Player)) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("bottle") && BottledExp.checkPermission("bottle.use", player)) {
int currentxp = player.getTotalExperience();
if (args.length == 0) {
sender.sendMessage(BottledExp.langCurrentXP + ": "
+ currentxp + " XP!");
} else if (args.length == 1) {
int amount;
if (args[0].equals("max")) {
if (BottledExp.checkPermission("bottle.max", player)) {
amount = (int) Math.floor(currentxp / 10);
}
else
{
return false;
}
} else {
try {
amount = Integer.valueOf(args[0]).intValue();
} catch (NumberFormatException nfe) {
sender.sendMessage(ChatColor.RED
+ BottledExp.errAmount);
return false;
}
}
if (currentxp < amount * BottledExp.xpCost) {
sender.sendMessage(ChatColor.RED + BottledExp.errXP);
}
else if (amount <= 0) {
amount = 0;
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
else {
PlayerInventory inventory = player.getInventory();
ItemStack items = new ItemStack(384, amount);
inventory.addItem(items);
player.setTotalExperience(0);
player.setLevel(0);
player.setExp(0);
player.giveExp(currentxp - (amount * BottledExp.xpCost));
sender.sendMessage(BottledExp.langOrder1 + " " + amount
+ " " + BottledExp.langOrder2);
}
}
return true;
}
} else {
sender.sendMessage(ChatColor.RED + "You must be a player!");
return false;
}
return false;
}
|
diff --git a/src/gnu/io/RXTXCommDriver.java b/src/gnu/io/RXTXCommDriver.java
index 4bc0e93..494289f 100644
--- a/src/gnu/io/RXTXCommDriver.java
+++ b/src/gnu/io/RXTXCommDriver.java
@@ -1,158 +1,159 @@
/*-------------------------------------------------------------------------
| A wrapper to convert RXTX into Linux Java Comm
| Copyright 1998 Kevin Hester, [email protected]
|
| This library is free software; you can redistribute it and/or
| modify it under the terms of the GNU Library General Public
| License as published by the Free Software Foundation; either
| version 2 of the License, or (at your option) any later version.
|
| This library is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
| Library General Public License for more details.
|
| You should have received a copy of the GNU Library General Public
| License along with this library; if not, write to the Free
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--------------------------------------------------------------------------*/
package gnu.io;
import java.io.*;
import javax.comm.*;
/**
This is the JavaComm for Linux driver.
*/
public class RXTXCommDriver implements CommDriver {
static String OS;
static
{
OS = System.getProperty("os.name");
if(OS.equals("Linux"))
{
System.loadLibrary( "Serial" );
}
if(OS.equals("Win95"))
{
System.loadLibrary("SerialW95");
}
//... propably not needed. hmm.
}
/** Get the Serial port prefixes for the running OS */
private native boolean IsDeviceGood(String dev);
private final String[] getPortPrefixes(String AllKnownPorts[]) {
int i=0;
String PortString[]=new String [256];
for(int j=0;j<AllKnownPorts.length;j++){
if(IsDeviceGood(AllKnownPorts[j])) {
PortString[i++]=AllKnownPorts[j];
}
}
String PortString2[] =new String[i];
for(int j=0;j<i;j++){
PortString2[j]=PortString[j];
}
return PortString2;
}
private void RegisterValidPorts(
String devs[],
String Prefix[],
int PortType
) {
for( int i = 0; i < devs.length; i++ ) {
for( int p = 0; p < Prefix.length; p++ ) {
if( devs[ i ].startsWith( Prefix[ p ] ) ) {
String portName = "/dev/" + devs[ i ];
File port = new File( portName );
if( port.canRead() && port.canWrite() )
CommPortIdentifier.addPortName(
portName,
PortType,
this
);
}
}
}
}
/*
* initialize() will be called by the CommPortIdentifier's static
* initializer. The responsibility of this method is:
* 1) Ensure that that the hardware is present.
* 2) Load any required native libraries.
* 3) Register the port names with the CommPortIdentifier.
*
* <p>From the NullDriver.java CommAPI sample.
*
* added printerport stuff
* Holger Lehmann
* July 12, 1999
* IBM
*/
public void initialize() {
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts={
"modem",// linux symbolic link to modem.
+ "cuaa", // FreeBSD Serial Ports
"ttyS", // linux Serial Ports
"ttyI", // linux virtual modems
"ttyW", // linux specialix cards
"ttyC", // linux cyclades cards
"ttyR", // linux comtrol cards
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"ttyd", // irix serial ports
"tty0" // netbsd serial ports
};
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts={
"lp" // linux printer port
};
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
}
/*
* getCommPort() will be called by CommPortIdentifier from its openPort()
* method. portName is a string that was registered earlier using the
* CommPortIdentifier.addPortName() method. getCommPort() returns an
* object that extends either SerialPort or ParallelPort.
*
* <p>From the NullDriver.java CommAPI sample.
*/
public CommPort getCommPort( String portName, int portType ) {
try {
if (portType==CommPortIdentifier.PORT_SERIAL)
{
return new RXTXPort( portName );
}
else if (portType==CommPortIdentifier.PORT_PARALLEL)
{
return new LPRPort( portName );
}
} catch( IOException e ) {
e.printStackTrace();
}
return null;
}
}
| true | true | public void initialize() {
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts={
"modem",// linux symbolic link to modem.
"ttyS", // linux Serial Ports
"ttyI", // linux virtual modems
"ttyW", // linux specialix cards
"ttyC", // linux cyclades cards
"ttyR", // linux comtrol cards
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"ttyd", // irix serial ports
"tty0" // netbsd serial ports
};
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts={
"lp" // linux printer port
};
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
}
| public void initialize() {
File dev = new File( "/dev" );
String[] devs = dev.list();
String[] AllKnownSerialPorts={
"modem",// linux symbolic link to modem.
"cuaa", // FreeBSD Serial Ports
"ttyS", // linux Serial Ports
"ttyI", // linux virtual modems
"ttyW", // linux specialix cards
"ttyC", // linux cyclades cards
"ttyR", // linux comtrol cards
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"ttyd", // irix serial ports
"tty0" // netbsd serial ports
};
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
String[] AllKnownParallelPorts={
"lp" // linux printer port
};
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownSerialPorts),
CommPortIdentifier.PORT_SERIAL
);
RegisterValidPorts(
devs,
getPortPrefixes(AllKnownParallelPorts),
CommPortIdentifier.PORT_PARALLEL
);
}
|
diff --git a/araqne-log-api/src/main/java/org/araqne/log/api/WtmpLogger.java b/araqne-log-api/src/main/java/org/araqne/log/api/WtmpLogger.java
index 2ee66c01..5f3c49dc 100644
--- a/araqne-log-api/src/main/java/org/araqne/log/api/WtmpLogger.java
+++ b/araqne-log-api/src/main/java/org/araqne/log/api/WtmpLogger.java
@@ -1,135 +1,135 @@
/*
* Copyright 2013 Eediom Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.araqne.log.api;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
public class WtmpLogger extends AbstractLogger {
private final org.slf4j.Logger slog = org.slf4j.LoggerFactory.getLogger(WtmpLogger.class);
private final File dataDir;
private final String path;
public WtmpLogger(LoggerSpecification spec, LoggerFactory factory) {
super(spec, factory);
dataDir = new File(System.getProperty("araqne.data.dir"), "araqne-log-api");
dataDir.mkdirs();
path = spec.getConfig().get("path");
// try migration at boot
File oldLastFile = getLastLogFile();
if (oldLastFile.exists()) {
Map<String, LastPosition> lastPositions = LastPositionHelper.readLastPositions(oldLastFile);
setStates(LastPositionHelper.serialize(lastPositions));
oldLastFile.renameTo(new File(oldLastFile.getAbsolutePath() + ".migrated"));
}
}
private WtmpEntryParser buildParser(String server) {
if (server == null)
return new WtmpEntryParserLinux();
server = server.toLowerCase();
if (server.equals("solaris"))
return new WtmpEntryParserSolaris();
else if (server.equals("aix"))
return new WtmpEntryParserAix();
else if (server.equals("hpux"))
return new WtmpEntryParserHpUx();
return new WtmpEntryParserLinux();
}
@Override
protected void runOnce() {
Map<String, LastPosition> lastPositions = LastPositionHelper.deserialize(getStates());
LastPosition inform = lastPositions.get(path);
if (inform == null)
inform = new LastPosition(path);
long pos = inform.getPosition();
File wtmpFile = new File(path);
if (!wtmpFile.exists()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] doesn't exist", getFullName(), path);
return;
}
if (!wtmpFile.canRead()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] no read permission", getFullName(), path);
return;
}
// log rotated case, reset read offset
if (wtmpFile.length() < pos) {
pos = 0;
}
WtmpEntryParser parser = buildParser(getConfigs().get("server"));
int blockSize = parser.getBlockSize();
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(wtmpFile, "r");
raf.seek(pos);
byte[] block = new byte[blockSize];
while (true) {
raf.readFully(block);
WtmpEntry e = parser.parseEntry(ByteBuffer.wrap(block));
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", e.getType().toString());
data.put("host", e.getHost());
data.put("pid", e.getPid());
data.put("session", e.getSession());
data.put("user", e.getUser());
- data.put("deviceName", e.getDeviceName());
- data.put("initTabId", e.getInitTabId());
+ data.put("device", e.getDeviceName());
+ data.put("inittab_id", e.getInitTabId());
write(new SimpleLog(e.getDate(), getFullName(), data));
pos += blockSize;
}
} catch (EOFException e) {
// ignore
} catch (Throwable t) {
slog.error("araqne log api: logger [" + getFullName() + "] cannot load wtmp file [" + path + "]", t);
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
inform.setPosition(pos);
lastPositions.put(path, inform);
setStates(LastPositionHelper.serialize(lastPositions));
}
}
protected File getLastLogFile() {
return new File(dataDir, "wtmp-" + getName() + ".lastlog");
}
}
| true | true | protected void runOnce() {
Map<String, LastPosition> lastPositions = LastPositionHelper.deserialize(getStates());
LastPosition inform = lastPositions.get(path);
if (inform == null)
inform = new LastPosition(path);
long pos = inform.getPosition();
File wtmpFile = new File(path);
if (!wtmpFile.exists()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] doesn't exist", getFullName(), path);
return;
}
if (!wtmpFile.canRead()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] no read permission", getFullName(), path);
return;
}
// log rotated case, reset read offset
if (wtmpFile.length() < pos) {
pos = 0;
}
WtmpEntryParser parser = buildParser(getConfigs().get("server"));
int blockSize = parser.getBlockSize();
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(wtmpFile, "r");
raf.seek(pos);
byte[] block = new byte[blockSize];
while (true) {
raf.readFully(block);
WtmpEntry e = parser.parseEntry(ByteBuffer.wrap(block));
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", e.getType().toString());
data.put("host", e.getHost());
data.put("pid", e.getPid());
data.put("session", e.getSession());
data.put("user", e.getUser());
data.put("deviceName", e.getDeviceName());
data.put("initTabId", e.getInitTabId());
write(new SimpleLog(e.getDate(), getFullName(), data));
pos += blockSize;
}
} catch (EOFException e) {
// ignore
} catch (Throwable t) {
slog.error("araqne log api: logger [" + getFullName() + "] cannot load wtmp file [" + path + "]", t);
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
inform.setPosition(pos);
lastPositions.put(path, inform);
setStates(LastPositionHelper.serialize(lastPositions));
}
}
| protected void runOnce() {
Map<String, LastPosition> lastPositions = LastPositionHelper.deserialize(getStates());
LastPosition inform = lastPositions.get(path);
if (inform == null)
inform = new LastPosition(path);
long pos = inform.getPosition();
File wtmpFile = new File(path);
if (!wtmpFile.exists()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] doesn't exist", getFullName(), path);
return;
}
if (!wtmpFile.canRead()) {
slog.debug("araqne log api: logger [{}] wtmp file [{}] no read permission", getFullName(), path);
return;
}
// log rotated case, reset read offset
if (wtmpFile.length() < pos) {
pos = 0;
}
WtmpEntryParser parser = buildParser(getConfigs().get("server"));
int blockSize = parser.getBlockSize();
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(wtmpFile, "r");
raf.seek(pos);
byte[] block = new byte[blockSize];
while (true) {
raf.readFully(block);
WtmpEntry e = parser.parseEntry(ByteBuffer.wrap(block));
Map<String, Object> data = new HashMap<String, Object>();
data.put("type", e.getType().toString());
data.put("host", e.getHost());
data.put("pid", e.getPid());
data.put("session", e.getSession());
data.put("user", e.getUser());
data.put("device", e.getDeviceName());
data.put("inittab_id", e.getInitTabId());
write(new SimpleLog(e.getDate(), getFullName(), data));
pos += blockSize;
}
} catch (EOFException e) {
// ignore
} catch (Throwable t) {
slog.error("araqne log api: logger [" + getFullName() + "] cannot load wtmp file [" + path + "]", t);
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {
}
}
inform.setPosition(pos);
lastPositions.put(path, inform);
setStates(LastPositionHelper.serialize(lastPositions));
}
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/ClusteredAgentManagerService.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/ClusteredAgentManagerService.java
index 939d5d0e..37f4b0fc 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/agent/service/ClusteredAgentManagerService.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/service/ClusteredAgentManagerService.java
@@ -1,414 +1,414 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.agent.service;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import net.grinder.common.processidentity.AgentIdentity;
import net.grinder.engine.controller.AgentControllerIdentityImplementation;
import net.sf.ehcache.Ehcache;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.mutable.MutableInt;
import org.ngrinder.agent.model.ClusteredAgentRequest;
import org.ngrinder.infra.logger.CoreLogger;
import org.ngrinder.infra.schedule.ScheduledTaskService;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.model.User;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.ngrinder.region.service.RegionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static net.grinder.message.console.AgentControllerState.INACTIVE;
import static net.grinder.message.console.AgentControllerState.WRONG_REGION;
import static org.ngrinder.agent.model.ClusteredAgentRequest.RequestType.*;
import static org.ngrinder.agent.repository.AgentManagerSpecification.active;
import static org.ngrinder.agent.repository.AgentManagerSpecification.visible;
import static org.ngrinder.common.util.CollectionUtils.newArrayList;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
import static org.ngrinder.common.util.TypeConvertUtils.cast;
/**
* Cluster enabled version of {@link AgentManagerService}.
*
* @author JunHo Yoon
* @since 3.1
*/
public class ClusteredAgentManagerService extends AgentManagerService {
private static final Logger LOGGER = LoggerFactory.getLogger(ClusteredAgentManagerService.class);
@Autowired
CacheManager cacheManager;
private Cache agentRequestCache;
private Cache agentMonitoringTargetsCache;
@Autowired
private ScheduledTaskService scheduledTaskService;
@Autowired
private RegionService regionService;
/**
* Initialize.
*/
@PostConstruct
public void init() {
agentMonitoringTargetsCache = cacheManager.getCache("agent_monitoring_targets");
if (getConfig().isClustered()) {
agentRequestCache = cacheManager.getCache("agent_request");
scheduledTaskService.addFixedDelayedScheduledTask(new Runnable() {
@Override
public void run() {
List<String> keys = cast(((Ehcache) agentRequestCache.getNativeCache())
.getKeysWithExpiryCheck());
String region = getConfig().getRegion() + "|";
for (String each : keys) {
if (each.startsWith(region)) {
if (agentRequestCache.get(each) != null) {
try {
ClusteredAgentRequest agentRequest = cast(agentRequestCache.get(each).get());
if (agentRequest.getRequestType() ==
ClusteredAgentRequest.RequestType.EXPIRE_LOCAL_CACHE) {
expireLocalCache();
} else {
AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(
agentRequest.getAgentIp(), agentRequest.getAgentName());
if (agentIdentity != null) {
agentRequest.getRequestType().process(ClusteredAgentManagerService.this,
agentIdentity);
}
}
agentRequestCache.evict(each);
} catch (Exception e) {
CoreLogger.LOGGER.error(e.getMessage(), e);
}
}
}
}
}
}, 3000);
}
}
/**
* Run a scheduled task to check the agent statuses.
*
* @since 3.1
*/
public void checkAgentState() {
List<AgentInfo> newAgents = newArrayList(0);
List<AgentInfo> updatedAgents = newArrayList(0);
List<AgentInfo> stateUpdatedAgents = newArrayList(0);
Set<AgentIdentity> allAttachedAgents = getAgentManager().getAllAttachedAgents();
Map<String, AgentControllerIdentityImplementation> attachedAgentMap = newHashMap(allAttachedAgents);
for (AgentIdentity agentIdentity : allAttachedAgents) {
AgentControllerIdentityImplementation existingAgent = cast(agentIdentity);
attachedAgentMap.put(createKey(existingAgent), existingAgent);
}
Map<String, AgentInfo> agentsInDBMap = Maps.newHashMap();
// step1. check all agents in DB, whether they are attached to
// controller.
for (AgentInfo eachAgentInDB : getAllLocal()) {
String keyOfAgentInDB = createKey(eachAgentInDB);
agentsInDBMap.put(keyOfAgentInDB, eachAgentInDB);
AgentControllerIdentityImplementation agentIdentity = attachedAgentMap.remove(keyOfAgentInDB);
if (agentIdentity != null) {
// if the agent attached to current controller
if (!isCurrentRegion(agentIdentity)) {
if (eachAgentInDB.getState() != WRONG_REGION) {
eachAgentInDB.setApproved(false);
eachAgentInDB.setRegion(getConfig().getRegion());
eachAgentInDB.setState(WRONG_REGION);
updatedAgents.add(eachAgentInDB);
}
} else if (!hasSameInfo(eachAgentInDB, agentIdentity)) {
fillUp(eachAgentInDB, agentIdentity);
updatedAgents.add(eachAgentInDB);
} else if (!hasSameState(eachAgentInDB, agentIdentity)) {
eachAgentInDB.setState(getAgentManager().getAgentState(agentIdentity));
stateUpdatedAgents.add(eachAgentInDB);
} else if (eachAgentInDB.getApproved() == null) {
updatedAgents.add(fillUpApproval(eachAgentInDB));
}
} else { // the agent in DB is not attached to current controller
if (eachAgentInDB.getState() != INACTIVE) {
eachAgentInDB.setState(INACTIVE);
stateUpdatedAgents.add(eachAgentInDB);
}
}
}
// step2. check all attached agents, whether they are new, and not saved
// in DB.
for (AgentControllerIdentityImplementation agentIdentity : attachedAgentMap.values()) {
AgentInfo agentInfo = agentManagerRepository.findByIpAndHostName(
agentIdentity.getIp(),
agentIdentity.getName());
if (agentInfo == null) {
agentInfo = new AgentInfo();
newAgents.add(fillUp(agentInfo, agentIdentity));
} else {
updatedAgents.add(fillUp(agentInfo, agentIdentity));
}
if (!isCurrentRegion(agentIdentity)) {
agentInfo.setState(WRONG_REGION);
agentInfo.setApproved(false);
}
}
cachedLocalAgentService.updateAgents(newAgents, updatedAgents, stateUpdatedAgents, null);
- if (!newAgents.isEmpty()) {
+ if (!newAgents.isEmpty() || !updatedAgents.isEmpty()) {
expireLocalCache();
}
}
private Gson gson = new Gson();
/**
* Collect the agent system info every second.
*/
@Scheduled(fixedDelay = 1000)
@Transactional
public void collectAgentSystemData() {
Ehcache nativeCache = (Ehcache) agentMonitoringTargetsCache.getNativeCache();
List<String> keysWithExpiryCheck = cast(nativeCache.getKeysWithExpiryCheck());
for (String each : keysWithExpiryCheck) {
ValueWrapper value = agentMonitoringTargetsCache.get(each);
AgentControllerIdentityImplementation agentIdentity = cast(value.get());
if (agentIdentity != null) {
// Is Same Region
if (isCurrentRegion(agentIdentity)) {
try {
updateSystemStat(agentIdentity);
} catch (IllegalStateException e) {
LOGGER.error("error while update system stat.");
}
}
}
}
}
public void updateSystemStat(final AgentControllerIdentityImplementation agentIdentity) {
cachedLocalAgentService.doSthInTransaction(new Runnable() {
public void run() {
agentManagerRepository.updateSystemStat(agentIdentity.getIp(),
agentIdentity.getName(),
gson.toJson(getSystemDataModel(agentIdentity)));
}
});
}
private SystemDataModel getSystemDataModel(AgentIdentity agentIdentity) {
return getAgentManager().getSystemDataModel(agentIdentity);
}
public List<AgentInfo> getAllActive() {
return agentManagerRepository.findAll(active());
}
public List<AgentInfo> getAllVisible() {
return agentManagerRepository.findAll(visible());
}
/**
* Get the available agent count map in all regions of the user, including
* the free agents and user specified agents.
*
* @param user current user
* @return user available agent count map
*/
@Override
public Map<String, MutableInt> getAvailableAgentCountMap(User user) {
Set<String> regions = getRegions();
Map<String, MutableInt> availShareAgents = newHashMap(regions);
Map<String, MutableInt> availUserOwnAgent = newHashMap(regions);
for (String region : regions) {
availShareAgents.put(region, new MutableInt(0));
availUserOwnAgent.put(region, new MutableInt(0));
}
String myAgentSuffix = "owned_" + user.getUserId();
for (AgentInfo agentInfo : getAllActive()) {
// Skip all agents which are disapproved, inactive or
// have no region prefix.
if (!agentInfo.isApproved()) {
continue;
}
String fullRegion = agentInfo.getRegion();
String region = extractRegionFromAgentRegion(fullRegion);
if (StringUtils.isBlank(region) || !regions.contains(region)) {
continue;
}
// It's my own agent
if (fullRegion.endsWith(myAgentSuffix)) {
incrementAgentCount(availUserOwnAgent, region, user.getUserId());
} else if (!fullRegion.contains("owned_")) {
incrementAgentCount(availShareAgents, region, user.getUserId());
}
}
int maxAgentSizePerConsole = getMaxAgentSizePerConsole();
for (String region : regions) {
MutableInt mutableInt = availShareAgents.get(region);
int shareAgentCount = mutableInt.intValue();
mutableInt.setValue(Math.min(shareAgentCount, maxAgentSizePerConsole));
mutableInt.add(availUserOwnAgent.get(region));
}
return availShareAgents;
}
protected Set<String> getRegions() {
return regionService.getAll().keySet();
}
protected boolean isCurrentRegion(AgentControllerIdentityImplementation agentIdentity) {
return StringUtils.equals(extractRegionFromAgentRegion(agentIdentity.getRegion()), getConfig().getRegion());
}
private void incrementAgentCount(Map<String, MutableInt> agentMap, String region, String userId) {
if (!agentMap.containsKey(region)) {
LOGGER.warn("Region :{} not exist in cluster nor owned by user:{}.", region, userId);
} else {
agentMap.get(region).increment();
}
}
@Override
public AgentInfo approve(Long id, boolean approve) {
AgentInfo agent = super.approve(id, approve);
if (agent != null) {
agentRequestCache.put(extractRegionFromAgentRegion(agent.getRegion()) + "|" + createKey(agent),
new ClusteredAgentRequest(agent.getIp(), agent.getName(), EXPIRE_LOCAL_CACHE));
}
return agent;
}
/**
* Stop agent. In cluster mode, it queues the agent stop request to
* agentRequestCache.
*
* @param id agent id in db
*/
@Override
public void stopAgent(Long id) {
AgentInfo agent = getOne(id);
if (agent == null) {
return;
}
agentRequestCache.put(extractRegionFromAgentRegion(agent.getRegion()) + "|" + createKey(agent),
new ClusteredAgentRequest(agent.getIp(), agent.getName(), STOP_AGENT));
}
/**
* Add the agent system data model share request on cache.
*
* @param id agent id in db.
*/
@Override
public void requestShareAgentSystemDataModel(Long id) {
AgentInfo agent = getOne(id);
if (agent == null) {
return;
}
agentRequestCache.put(extractRegionFromAgentRegion(agent.getRegion()) + "|" + createKey(agent),
new ClusteredAgentRequest(agent.getIp(), agent.getName(), SHARE_AGENT_SYSTEM_DATA_MODEL));
}
/**
* Get the agent system data model for the given IP. This method is cluster
* aware.
*
* @param ip agent ip
* @param name agent name
* @return {@link SystemDataModel} instance.
*/
@Override
public SystemDataModel getSystemDataModel(String ip, String name) {
AgentInfo found = agentManagerRepository.findByIpAndHostName(ip, name);
String systemStat = (found == null) ? null : found.getSystemStat();
return (StringUtils.isEmpty(systemStat)) ? new SystemDataModel() : gson.fromJson(systemStat,
SystemDataModel.class);
}
/**
* Register agent monitoring target. This method should be called in the
* controller in which the given agent exists.
*
* @param agentIdentity agent identity
*/
public void addAgentMonitoringTarget(AgentControllerIdentityImplementation agentIdentity) {
agentMonitoringTargetsCache.put(createKey(agentIdentity), agentIdentity);
}
/**
* Stop agent.
*
* @param agentIdentity agent identity to be stopped.
*/
public void stopAgent(AgentControllerIdentityImplementation agentIdentity) {
getAgentManager().stopAgent(agentIdentity);
}
/**
* Update agent by id.
*
* @param id agent id
*/
@Override
public void update(Long id) {
AgentInfo agent = getOne(id);
if (agent == null) {
return;
}
agentRequestCache.put(extractRegionFromAgentRegion(agent.getRegion()) + "|" + createKey(agent),
new ClusteredAgentRequest(agent.getIp(), agent.getName(), UPDATE_AGENT));
}
/**
* Clean up the agents from db which belongs to the inactive regions.
*/
@Transactional
public void cleanup() {
super.cleanup();
final Set<String> regions = getRegions();
for (AgentInfo each : agentManagerRepository.findAll()) {
if (!regions.contains(extractRegionFromAgentRegion(each.getRegion()))) {
agentManagerRepository.delete(each);
}
}
}
}
| true | true | public void checkAgentState() {
List<AgentInfo> newAgents = newArrayList(0);
List<AgentInfo> updatedAgents = newArrayList(0);
List<AgentInfo> stateUpdatedAgents = newArrayList(0);
Set<AgentIdentity> allAttachedAgents = getAgentManager().getAllAttachedAgents();
Map<String, AgentControllerIdentityImplementation> attachedAgentMap = newHashMap(allAttachedAgents);
for (AgentIdentity agentIdentity : allAttachedAgents) {
AgentControllerIdentityImplementation existingAgent = cast(agentIdentity);
attachedAgentMap.put(createKey(existingAgent), existingAgent);
}
Map<String, AgentInfo> agentsInDBMap = Maps.newHashMap();
// step1. check all agents in DB, whether they are attached to
// controller.
for (AgentInfo eachAgentInDB : getAllLocal()) {
String keyOfAgentInDB = createKey(eachAgentInDB);
agentsInDBMap.put(keyOfAgentInDB, eachAgentInDB);
AgentControllerIdentityImplementation agentIdentity = attachedAgentMap.remove(keyOfAgentInDB);
if (agentIdentity != null) {
// if the agent attached to current controller
if (!isCurrentRegion(agentIdentity)) {
if (eachAgentInDB.getState() != WRONG_REGION) {
eachAgentInDB.setApproved(false);
eachAgentInDB.setRegion(getConfig().getRegion());
eachAgentInDB.setState(WRONG_REGION);
updatedAgents.add(eachAgentInDB);
}
} else if (!hasSameInfo(eachAgentInDB, agentIdentity)) {
fillUp(eachAgentInDB, agentIdentity);
updatedAgents.add(eachAgentInDB);
} else if (!hasSameState(eachAgentInDB, agentIdentity)) {
eachAgentInDB.setState(getAgentManager().getAgentState(agentIdentity));
stateUpdatedAgents.add(eachAgentInDB);
} else if (eachAgentInDB.getApproved() == null) {
updatedAgents.add(fillUpApproval(eachAgentInDB));
}
} else { // the agent in DB is not attached to current controller
if (eachAgentInDB.getState() != INACTIVE) {
eachAgentInDB.setState(INACTIVE);
stateUpdatedAgents.add(eachAgentInDB);
}
}
}
// step2. check all attached agents, whether they are new, and not saved
// in DB.
for (AgentControllerIdentityImplementation agentIdentity : attachedAgentMap.values()) {
AgentInfo agentInfo = agentManagerRepository.findByIpAndHostName(
agentIdentity.getIp(),
agentIdentity.getName());
if (agentInfo == null) {
agentInfo = new AgentInfo();
newAgents.add(fillUp(agentInfo, agentIdentity));
} else {
updatedAgents.add(fillUp(agentInfo, agentIdentity));
}
if (!isCurrentRegion(agentIdentity)) {
agentInfo.setState(WRONG_REGION);
agentInfo.setApproved(false);
}
}
cachedLocalAgentService.updateAgents(newAgents, updatedAgents, stateUpdatedAgents, null);
if (!newAgents.isEmpty()) {
expireLocalCache();
}
}
| public void checkAgentState() {
List<AgentInfo> newAgents = newArrayList(0);
List<AgentInfo> updatedAgents = newArrayList(0);
List<AgentInfo> stateUpdatedAgents = newArrayList(0);
Set<AgentIdentity> allAttachedAgents = getAgentManager().getAllAttachedAgents();
Map<String, AgentControllerIdentityImplementation> attachedAgentMap = newHashMap(allAttachedAgents);
for (AgentIdentity agentIdentity : allAttachedAgents) {
AgentControllerIdentityImplementation existingAgent = cast(agentIdentity);
attachedAgentMap.put(createKey(existingAgent), existingAgent);
}
Map<String, AgentInfo> agentsInDBMap = Maps.newHashMap();
// step1. check all agents in DB, whether they are attached to
// controller.
for (AgentInfo eachAgentInDB : getAllLocal()) {
String keyOfAgentInDB = createKey(eachAgentInDB);
agentsInDBMap.put(keyOfAgentInDB, eachAgentInDB);
AgentControllerIdentityImplementation agentIdentity = attachedAgentMap.remove(keyOfAgentInDB);
if (agentIdentity != null) {
// if the agent attached to current controller
if (!isCurrentRegion(agentIdentity)) {
if (eachAgentInDB.getState() != WRONG_REGION) {
eachAgentInDB.setApproved(false);
eachAgentInDB.setRegion(getConfig().getRegion());
eachAgentInDB.setState(WRONG_REGION);
updatedAgents.add(eachAgentInDB);
}
} else if (!hasSameInfo(eachAgentInDB, agentIdentity)) {
fillUp(eachAgentInDB, agentIdentity);
updatedAgents.add(eachAgentInDB);
} else if (!hasSameState(eachAgentInDB, agentIdentity)) {
eachAgentInDB.setState(getAgentManager().getAgentState(agentIdentity));
stateUpdatedAgents.add(eachAgentInDB);
} else if (eachAgentInDB.getApproved() == null) {
updatedAgents.add(fillUpApproval(eachAgentInDB));
}
} else { // the agent in DB is not attached to current controller
if (eachAgentInDB.getState() != INACTIVE) {
eachAgentInDB.setState(INACTIVE);
stateUpdatedAgents.add(eachAgentInDB);
}
}
}
// step2. check all attached agents, whether they are new, and not saved
// in DB.
for (AgentControllerIdentityImplementation agentIdentity : attachedAgentMap.values()) {
AgentInfo agentInfo = agentManagerRepository.findByIpAndHostName(
agentIdentity.getIp(),
agentIdentity.getName());
if (agentInfo == null) {
agentInfo = new AgentInfo();
newAgents.add(fillUp(agentInfo, agentIdentity));
} else {
updatedAgents.add(fillUp(agentInfo, agentIdentity));
}
if (!isCurrentRegion(agentIdentity)) {
agentInfo.setState(WRONG_REGION);
agentInfo.setApproved(false);
}
}
cachedLocalAgentService.updateAgents(newAgents, updatedAgents, stateUpdatedAgents, null);
if (!newAgents.isEmpty() || !updatedAgents.isEmpty()) {
expireLocalCache();
}
}
|
diff --git a/android/src/com/stfalcon/mtpclient/Parser.java b/android/src/com/stfalcon/mtpclient/Parser.java
index 168a377..c8f7bb7 100644
--- a/android/src/com/stfalcon/mtpclient/Parser.java
+++ b/android/src/com/stfalcon/mtpclient/Parser.java
@@ -1,181 +1,188 @@
package com.stfalcon.mtpclient;
import android.util.Log;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
/**
* Created by user on 7/22/13.
*/
public class Parser {
public static final String TYPE = "type";
public static final String AUTH = "auth_key";
public static final String MESSAGE_ID = "message_id";
public static final String MESSAGE_LENGTH = "message_length";
public static final String RES_PQ = "res_pq";
public static final String NONCE = "nonce";
public static final String SERVER_NONCE = "server_nonce";
public static final String NEW_NONCE_HASH1 = "new_nonce_hash1";
public static final String PQ = "pq";
public static final String P = "p";
public static final String Q = "q";
public static final String VECTOR_LONG = "vector_long";
public static final String COUNT = "count";
public static final String FINGER_PRINTS = "finger_prints";
public static final String ENC_ANSWER = "encrypted_answer";
public static final int TYPE_RES_PQ = 1663309317;
public static final int TYPE_RES_DH = 1544022224;
public static final int TYPE_DH_GEN_OK = 888654651;
public static HashMap<String, Object> parseReqPqResponse(byte[] response) {
try {
HashMap<String, Object> result = new HashMap<String, Object>();
ByteBuffer buffer = ByteBuffer.wrap(response, 0, 4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int header_message_length = buffer.getInt();
byte[] message = new byte[header_message_length];
ByteBuffer.wrap(response, 0, header_message_length).get(message);
int header_pack_id = ByteBuffer.wrap(message, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
Log.v("PARSER", "HEADER: " + header_message_length + " " + header_pack_id);
long auth_key = ByteBuffer.wrap(message, 8, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
long message_id = ByteBuffer.wrap(message, 16, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
int message_length = ByteBuffer.wrap(message, 24, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
long res_pq = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
- int number_res_pq = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
+ int number_res_pq1 = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
+ int number_res_pq2 = ByteBuffer.wrap(message, 0, 4).order(ByteOrder.BIG_ENDIAN).getInt();
+ int type = 0;
+ if (number_res_pq1 == TYPE_RES_PQ || number_res_pq1 == TYPE_RES_DH) {
+ type = number_res_pq1;
+ } else {
+ type = number_res_pq2;
+ }
- switch (number_res_pq) {
+ switch (type) {
case TYPE_RES_PQ:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
byte[] pq = new byte[12];
ByteBuffer.wrap(response, 64, pq.length).get(pq);
result.put(Parser.TYPE, TYPE_RES_PQ);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.PQ, pq);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "PQ: " + Utils.byteArrayToHex(pq));
long vector_long = ByteBuffer.wrap(message, 76, 4).order(ByteOrder.BIG_ENDIAN).getInt();
long count = ByteBuffer.wrap(message, 80, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
byte[] finger_prints = new byte[8];
ByteBuffer.wrap(response, 84, finger_prints.length).get(finger_prints);
byte[] PQ = new byte[8];
ByteBuffer.wrap(response, 65, pq.length).get(PQ);
BigInteger bigInteger = new BigInteger(PQ);
BigIntegerMath bigIntegerMath = new BigIntegerMath();
bigIntegerMath.factor(bigInteger);
BigInteger[] pq_result = bigIntegerMath.getfactors();
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byte[] p_arr = byteBuffer.putInt(pq_result[0].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
- byteBuffer.put((byte)0x04);
+ byteBuffer.put((byte) 0x04);
byteBuffer.put(p_arr);
- byteBuffer.put(new byte[]{0x00,0x00,0x00});
+ byteBuffer.put(new byte[]{0x00, 0x00, 0x00});
p_arr = byteBuffer.array();
byteBuffer = ByteBuffer.allocate(4);
byte[] q_arr = byteBuffer.putInt(pq_result[1].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
- byteBuffer.put((byte)0x04);
+ byteBuffer.put((byte) 0x04);
byteBuffer.put(q_arr);
- byteBuffer.put(new byte[]{0x00,0x00,0x00});
+ byteBuffer.put(new byte[]{0x00, 0x00, 0x00});
q_arr = byteBuffer.array();
result.put(Parser.P, p_arr);
result.put(Parser.Q, q_arr);
result.put(Parser.VECTOR_LONG, vector_long);
result.put(Parser.COUNT, count);
result.put(Parser.FINGER_PRINTS, finger_prints);
Log.v("PARSER", "P: " + pq_result[0]);
Log.v("PARSER", "Q: " + pq_result[1]);
Log.v("PARSER", "VECTOR_LONG: " + vector_long);
Log.v("PARSER", "COUNT: " + count);
Log.v("PARSER", "finger_prints: " + Utils.byteArrayToHex(finger_prints));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_RES_DH:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
byte[] enc_ansver = new byte[596];
ByteBuffer.wrap(response, 64, enc_ansver.length).get(enc_ansver);
result.put(Parser.ENC_ANSWER, enc_ansver);
Log.v("PARSER", "encrypted_answer: " + Utils.byteArrayToHex(enc_ansver));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_DH_GEN_OK:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 4, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 20, server_nonce.length).get(server_nonce);
byte[] new_nonce_hash1 = new byte[4];
ByteBuffer.wrap(response, 36, new_nonce_hash1.length).get(new_nonce_hash1);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.NEW_NONCE_HASH1, new_nonce_hash1);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "New_nonce_hash1: " + Utils.byteArrayToHex(server_nonce));
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void parseResponse() {
}
}
| false | true | public static HashMap<String, Object> parseReqPqResponse(byte[] response) {
try {
HashMap<String, Object> result = new HashMap<String, Object>();
ByteBuffer buffer = ByteBuffer.wrap(response, 0, 4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int header_message_length = buffer.getInt();
byte[] message = new byte[header_message_length];
ByteBuffer.wrap(response, 0, header_message_length).get(message);
int header_pack_id = ByteBuffer.wrap(message, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
Log.v("PARSER", "HEADER: " + header_message_length + " " + header_pack_id);
long auth_key = ByteBuffer.wrap(message, 8, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
long message_id = ByteBuffer.wrap(message, 16, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
int message_length = ByteBuffer.wrap(message, 24, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
long res_pq = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
int number_res_pq = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
switch (number_res_pq) {
case TYPE_RES_PQ:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
byte[] pq = new byte[12];
ByteBuffer.wrap(response, 64, pq.length).get(pq);
result.put(Parser.TYPE, TYPE_RES_PQ);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.PQ, pq);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "PQ: " + Utils.byteArrayToHex(pq));
long vector_long = ByteBuffer.wrap(message, 76, 4).order(ByteOrder.BIG_ENDIAN).getInt();
long count = ByteBuffer.wrap(message, 80, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
byte[] finger_prints = new byte[8];
ByteBuffer.wrap(response, 84, finger_prints.length).get(finger_prints);
byte[] PQ = new byte[8];
ByteBuffer.wrap(response, 65, pq.length).get(PQ);
BigInteger bigInteger = new BigInteger(PQ);
BigIntegerMath bigIntegerMath = new BigIntegerMath();
bigIntegerMath.factor(bigInteger);
BigInteger[] pq_result = bigIntegerMath.getfactors();
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byte[] p_arr = byteBuffer.putInt(pq_result[0].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
byteBuffer.put((byte)0x04);
byteBuffer.put(p_arr);
byteBuffer.put(new byte[]{0x00,0x00,0x00});
p_arr = byteBuffer.array();
byteBuffer = ByteBuffer.allocate(4);
byte[] q_arr = byteBuffer.putInt(pq_result[1].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
byteBuffer.put((byte)0x04);
byteBuffer.put(q_arr);
byteBuffer.put(new byte[]{0x00,0x00,0x00});
q_arr = byteBuffer.array();
result.put(Parser.P, p_arr);
result.put(Parser.Q, q_arr);
result.put(Parser.VECTOR_LONG, vector_long);
result.put(Parser.COUNT, count);
result.put(Parser.FINGER_PRINTS, finger_prints);
Log.v("PARSER", "P: " + pq_result[0]);
Log.v("PARSER", "Q: " + pq_result[1]);
Log.v("PARSER", "VECTOR_LONG: " + vector_long);
Log.v("PARSER", "COUNT: " + count);
Log.v("PARSER", "finger_prints: " + Utils.byteArrayToHex(finger_prints));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_RES_DH:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
byte[] enc_ansver = new byte[596];
ByteBuffer.wrap(response, 64, enc_ansver.length).get(enc_ansver);
result.put(Parser.ENC_ANSWER, enc_ansver);
Log.v("PARSER", "encrypted_answer: " + Utils.byteArrayToHex(enc_ansver));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_DH_GEN_OK:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 4, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 20, server_nonce.length).get(server_nonce);
byte[] new_nonce_hash1 = new byte[4];
ByteBuffer.wrap(response, 36, new_nonce_hash1.length).get(new_nonce_hash1);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.NEW_NONCE_HASH1, new_nonce_hash1);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "New_nonce_hash1: " + Utils.byteArrayToHex(server_nonce));
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
| public static HashMap<String, Object> parseReqPqResponse(byte[] response) {
try {
HashMap<String, Object> result = new HashMap<String, Object>();
ByteBuffer buffer = ByteBuffer.wrap(response, 0, 4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int header_message_length = buffer.getInt();
byte[] message = new byte[header_message_length];
ByteBuffer.wrap(response, 0, header_message_length).get(message);
int header_pack_id = ByteBuffer.wrap(message, 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
Log.v("PARSER", "HEADER: " + header_message_length + " " + header_pack_id);
long auth_key = ByteBuffer.wrap(message, 8, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
long message_id = ByteBuffer.wrap(message, 16, 8).order(ByteOrder.LITTLE_ENDIAN).getLong();
int message_length = ByteBuffer.wrap(message, 24, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
long res_pq = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
int number_res_pq1 = ByteBuffer.wrap(message, 28, 4).order(ByteOrder.BIG_ENDIAN).getInt();
int number_res_pq2 = ByteBuffer.wrap(message, 0, 4).order(ByteOrder.BIG_ENDIAN).getInt();
int type = 0;
if (number_res_pq1 == TYPE_RES_PQ || number_res_pq1 == TYPE_RES_DH) {
type = number_res_pq1;
} else {
type = number_res_pq2;
}
switch (type) {
case TYPE_RES_PQ:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
byte[] pq = new byte[12];
ByteBuffer.wrap(response, 64, pq.length).get(pq);
result.put(Parser.TYPE, TYPE_RES_PQ);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.PQ, pq);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "PQ: " + Utils.byteArrayToHex(pq));
long vector_long = ByteBuffer.wrap(message, 76, 4).order(ByteOrder.BIG_ENDIAN).getInt();
long count = ByteBuffer.wrap(message, 80, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
byte[] finger_prints = new byte[8];
ByteBuffer.wrap(response, 84, finger_prints.length).get(finger_prints);
byte[] PQ = new byte[8];
ByteBuffer.wrap(response, 65, pq.length).get(PQ);
BigInteger bigInteger = new BigInteger(PQ);
BigIntegerMath bigIntegerMath = new BigIntegerMath();
bigIntegerMath.factor(bigInteger);
BigInteger[] pq_result = bigIntegerMath.getfactors();
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
byte[] p_arr = byteBuffer.putInt(pq_result[0].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
byteBuffer.put((byte) 0x04);
byteBuffer.put(p_arr);
byteBuffer.put(new byte[]{0x00, 0x00, 0x00});
p_arr = byteBuffer.array();
byteBuffer = ByteBuffer.allocate(4);
byte[] q_arr = byteBuffer.putInt(pq_result[1].intValue()).array();
byteBuffer = ByteBuffer.allocate(8);
byteBuffer.put((byte) 0x04);
byteBuffer.put(q_arr);
byteBuffer.put(new byte[]{0x00, 0x00, 0x00});
q_arr = byteBuffer.array();
result.put(Parser.P, p_arr);
result.put(Parser.Q, q_arr);
result.put(Parser.VECTOR_LONG, vector_long);
result.put(Parser.COUNT, count);
result.put(Parser.FINGER_PRINTS, finger_prints);
Log.v("PARSER", "P: " + pq_result[0]);
Log.v("PARSER", "Q: " + pq_result[1]);
Log.v("PARSER", "VECTOR_LONG: " + vector_long);
Log.v("PARSER", "COUNT: " + count);
Log.v("PARSER", "finger_prints: " + Utils.byteArrayToHex(finger_prints));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_RES_DH:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 32, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 48, server_nonce.length).get(server_nonce);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.AUTH, auth_key);
result.put(Parser.MESSAGE_ID, message_id);
result.put(Parser.MESSAGE_LENGTH, message_length);
result.put(Parser.RES_PQ, res_pq);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
Log.v("PARSER", "AUTH: " + auth_key);
Log.v("PARSER", "Message ID: " + message_id);
Log.v("PARSER", "message_length: " + message_length);
Log.v("PARSER", "RES_PQ: " + res_pq);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
byte[] enc_ansver = new byte[596];
ByteBuffer.wrap(response, 64, enc_ansver.length).get(enc_ansver);
result.put(Parser.ENC_ANSWER, enc_ansver);
Log.v("PARSER", "encrypted_answer: " + Utils.byteArrayToHex(enc_ansver));
} catch (Exception e) {
e.printStackTrace();
}
break;
case TYPE_DH_GEN_OK:
try {
byte[] nonce = new byte[16];
ByteBuffer.wrap(response, 4, 16).get(nonce);
byte[] server_nonce = new byte[16];
ByteBuffer.wrap(response, 20, server_nonce.length).get(server_nonce);
byte[] new_nonce_hash1 = new byte[4];
ByteBuffer.wrap(response, 36, new_nonce_hash1.length).get(new_nonce_hash1);
result.put(Parser.TYPE, TYPE_RES_DH);
result.put(Parser.NONCE, nonce);
result.put(Parser.SERVER_NONCE, server_nonce);
result.put(Parser.NEW_NONCE_HASH1, new_nonce_hash1);
Log.v("PARSER", "NONCE: " + Utils.byteArrayToHex(nonce));
Log.v("PARSER", "Server_NONCE: " + Utils.byteArrayToHex(server_nonce));
Log.v("PARSER", "New_nonce_hash1: " + Utils.byteArrayToHex(server_nonce));
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
break;
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
|
diff --git a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java
index bf4b91508..aa5e4a4ab 100644
--- a/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java
+++ b/astrid/src/com/todoroo/astrid/service/abtesting/ABTestEventReportingService.java
@@ -1,140 +1,139 @@
package com.todoroo.astrid.service.abtesting;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Order;
import com.todoroo.andlib.sql.Query;
import com.todoroo.astrid.dao.ABTestEventDao;
import com.todoroo.astrid.data.ABTestEvent;
import com.todoroo.astrid.service.StatisticsService;
/**
* Service to manage the reporting of launch events for AB testing.
* On startup, queries the ABTestEvent database for unreported data
* points, merges them into the expected JSONArray format, and
* pushes them to the server.
* @author Sam
*
*/
@SuppressWarnings("nls")
public final class ABTestEventReportingService {
private static final String KEY_TEST = "test";
private static final String KEY_VARIANT = "variant";
private static final String KEY_NEW_USER = "new";
private static final String KEY_ACTIVE_USER = "activated";
private static final String KEY_DAYS = "days";
private static final String KEY_DATE = "date";
@Autowired
private ABTestEventDao abTestEventDao;
@Autowired
private ABTestInvoker abTestInvoker;
public ABTestEventReportingService() {
DependencyInjectionService.getInstance().inject(this);
}
/**
* Called on startup from TaskListActivity. Creates any +n days
* launch events that need to be recorded, and pushes all unreported
* data to the server.
*/
public void trackUserRetention() {
new Thread(new Runnable() {
@Override
public void run() {
abTestEventDao.createRelativeDateEvents();
pushAllUnreportedABTestEvents();
}
}).start();
}
private void pushAllUnreportedABTestEvents() {
if (StatisticsService.dontCollectStatistics())
return;
final TodorooCursor<ABTestEvent> unreported = abTestEventDao.query(Query.select(ABTestEvent.PROPERTIES)
.where(ABTestEvent.REPORTED.eq(0))
- .orderBy(Order.asc(ABTestEvent.TEST_NAME))
- .orderBy(Order.asc(ABTestEvent.TIME_INTERVAL)));
+ .orderBy(Order.asc(ABTestEvent.TEST_NAME), Order.asc(ABTestEvent.TIME_INTERVAL)));
if (unreported.getCount() > 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
JSONArray payload = jsonArrayFromABTestEvents(unreported);
abTestInvoker.post(payload);
ABTestEvent model = new ABTestEvent();
for (unreported.moveToFirst(); !unreported.isAfterLast(); unreported.moveToNext()) {
model.readFromCursor(unreported);
model.setValue(ABTestEvent.REPORTED, 1);
abTestEventDao.saveExisting(model);
}
} catch (JSONException e) {
handleException(e);
} catch (IOException e) {
handleException(e);
} finally {
unreported.close();
}
}
}).start();
}
}
private void handleException(Exception e) {
Log.e("analytics", "analytics-error", e);
}
private static JSONObject jsonFromABTestEvent(ABTestEvent model) throws JSONException {
JSONObject payload = new JSONObject();
payload.put(KEY_TEST, model.getValue(ABTestEvent.TEST_NAME));
payload.put(KEY_VARIANT, model.getValue(ABTestEvent.TEST_VARIANT));
payload.put(KEY_NEW_USER, model.getValue(ABTestEvent.NEW_USER) > 0 ? true : false);
payload.put(KEY_ACTIVE_USER, model.getValue(ABTestEvent.ACTIVATED_USER) > 0 ? true : false);
payload.put(KEY_DAYS, new JSONArray().put(model.getValue(ABTestEvent.TIME_INTERVAL)));
long date = model.getValue(ABTestEvent.DATE_RECORDED) / 1000L;
payload.put(KEY_DATE, date);
return payload;
}
private static JSONArray jsonArrayFromABTestEvents(TodorooCursor<ABTestEvent> events) throws JSONException {
JSONArray result = new JSONArray();
String lastTestKey = "";
JSONObject testAcc = null;
ABTestEvent model = new ABTestEvent();
for (events.moveToFirst(); !events.isAfterLast(); events.moveToNext()) {
model.readFromCursor(events);
if (!model.getValue(ABTestEvent.TEST_NAME).equals(lastTestKey)) {
if (testAcc != null)
result.put(testAcc);
testAcc = jsonFromABTestEvent(model);
lastTestKey = model.getValue(ABTestEvent.TEST_NAME);
} else {
int interval = model.getValue(ABTestEvent.TIME_INTERVAL);
if (testAcc != null) { // this should never happen, just stopping the compiler from complaining
JSONArray daysArray = testAcc.getJSONArray(KEY_DAYS);
daysArray.put(interval);
}
}
}
if (testAcc != null)
result.put(testAcc);
return result;
}
}
| true | true | private void pushAllUnreportedABTestEvents() {
if (StatisticsService.dontCollectStatistics())
return;
final TodorooCursor<ABTestEvent> unreported = abTestEventDao.query(Query.select(ABTestEvent.PROPERTIES)
.where(ABTestEvent.REPORTED.eq(0))
.orderBy(Order.asc(ABTestEvent.TEST_NAME))
.orderBy(Order.asc(ABTestEvent.TIME_INTERVAL)));
if (unreported.getCount() > 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
JSONArray payload = jsonArrayFromABTestEvents(unreported);
abTestInvoker.post(payload);
ABTestEvent model = new ABTestEvent();
for (unreported.moveToFirst(); !unreported.isAfterLast(); unreported.moveToNext()) {
model.readFromCursor(unreported);
model.setValue(ABTestEvent.REPORTED, 1);
abTestEventDao.saveExisting(model);
}
} catch (JSONException e) {
handleException(e);
} catch (IOException e) {
handleException(e);
} finally {
unreported.close();
}
}
}).start();
}
}
| private void pushAllUnreportedABTestEvents() {
if (StatisticsService.dontCollectStatistics())
return;
final TodorooCursor<ABTestEvent> unreported = abTestEventDao.query(Query.select(ABTestEvent.PROPERTIES)
.where(ABTestEvent.REPORTED.eq(0))
.orderBy(Order.asc(ABTestEvent.TEST_NAME), Order.asc(ABTestEvent.TIME_INTERVAL)));
if (unreported.getCount() > 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
JSONArray payload = jsonArrayFromABTestEvents(unreported);
abTestInvoker.post(payload);
ABTestEvent model = new ABTestEvent();
for (unreported.moveToFirst(); !unreported.isAfterLast(); unreported.moveToNext()) {
model.readFromCursor(unreported);
model.setValue(ABTestEvent.REPORTED, 1);
abTestEventDao.saveExisting(model);
}
} catch (JSONException e) {
handleException(e);
} catch (IOException e) {
handleException(e);
} finally {
unreported.close();
}
}
}).start();
}
}
|
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/documents/UpdateKeyword.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/documents/UpdateKeyword.java
index 2e2bb3f31..47cf8ca68 100644
--- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/documents/UpdateKeyword.java
+++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/documents/UpdateKeyword.java
@@ -1,122 +1,123 @@
package net.cyklotron.cms.modules.actions.documents;
import org.jcontainer.dna.Logger;
import org.objectledge.context.Context;
import org.objectledge.coral.entity.EntityDoesNotExistException;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.forms.FormsService;
import org.objectledge.parameters.Parameters;
import org.objectledge.pipeline.ProcessingException;
import org.objectledge.templating.TemplatingContext;
import org.objectledge.web.HttpContext;
import org.objectledge.web.mvc.MVCContext;
import net.cyklotron.cms.CmsDataFactory;
import net.cyklotron.cms.category.CategoryResource;
import net.cyklotron.cms.category.CategoryResourceImpl;
import net.cyklotron.cms.documents.DocumentService;
import net.cyklotron.cms.documents.keywords.KeywordResource;
import net.cyklotron.cms.documents.keywords.KeywordResourceImpl;
import net.cyklotron.cms.structure.NavigationNodeResource;
import net.cyklotron.cms.structure.StructureService;
import net.cyklotron.cms.style.StyleService;
/**
* @author <a href="mailto:[email protected]">Damian Gajda</a>
* @version $Id: UpdateFooter.java,v 1.1 2006-05-08 12:29:37 pablo Exp $
*/
public class UpdateKeyword
extends BaseDocumentAction
{
public UpdateKeyword(Logger logger, StructureService structureService,
CmsDataFactory cmsDataFactory, StyleService styleService, FormsService formsService,
DocumentService documentService)
{
super(logger, structureService, cmsDataFactory, styleService, formsService, documentService);
}
public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
try
{
long keywordId = parameters.getLong("keywordId");
KeywordResource keyword = KeywordResourceImpl.getKeywordResource(coralSession,
keywordId);
String pattern = parameters.get("pattern", "");
if(pattern.length() == 0)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_keyword_pattern");
return;
}
String title = parameters.get("title", "");
boolean regExp = parameters.getBoolean("reg_exp", false);
boolean newWindow = parameters.getBoolean("new_window", false);
String linkClass = parameters.get("link_class", "");
String hrefExternal = parameters.get("href_external", "");
String hrefInternal = parameters.get("href_internal", "");
boolean external = "external".equals(parameters.get("link_type", "external")) ? true
: false;
keyword.setTitle(title);
+ keyword.setExternal(external);
if(external)
{
if(!(hrefExternal.startsWith("http://") || hrefExternal.startsWith("https://")))
{
hrefExternal = "http://" + hrefExternal;
}
keyword.setHrefExternal(hrefExternal);
}
else
{
String relativePath = parameters.get("relative_path", "");
Resource[] section = coralSession.getStore().getResourceByPath(
relativePath + hrefInternal);
if(section.length != 1 || !(section[0] instanceof NavigationNodeResource))
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_target");
return;
}
keyword.setHrefInternal((NavigationNodeResource)section[0]);
}
long category_id = parameters.getLong("category_id", -1L);
CategoryResource category = null;
try
{
if(category_id != -1L)
{
category = CategoryResourceImpl.getCategoryResource(coralSession, category_id);
}
keyword.setCategory(category);
}
catch(EntityDoesNotExistException e)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword", "invalid_category");
}
keyword.setNewWindow(newWindow);
keyword.setRegexp(regExp);
keyword.setPattern(pattern);
keyword.setLinkClass(linkClass);
keyword.update();
}
catch(Exception e)
{
throw new ProcessingException("failed to update keyword", e);
}
}
public boolean checkAccessRights(Context context)
throws ProcessingException
{
CoralSession coralSession = (CoralSession)context.getAttribute(CoralSession.class);
return coralSession.getUserSubject().hasRole(getSite(context).getAdministrator());
}
}
| true | true | public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
try
{
long keywordId = parameters.getLong("keywordId");
KeywordResource keyword = KeywordResourceImpl.getKeywordResource(coralSession,
keywordId);
String pattern = parameters.get("pattern", "");
if(pattern.length() == 0)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_keyword_pattern");
return;
}
String title = parameters.get("title", "");
boolean regExp = parameters.getBoolean("reg_exp", false);
boolean newWindow = parameters.getBoolean("new_window", false);
String linkClass = parameters.get("link_class", "");
String hrefExternal = parameters.get("href_external", "");
String hrefInternal = parameters.get("href_internal", "");
boolean external = "external".equals(parameters.get("link_type", "external")) ? true
: false;
keyword.setTitle(title);
if(external)
{
if(!(hrefExternal.startsWith("http://") || hrefExternal.startsWith("https://")))
{
hrefExternal = "http://" + hrefExternal;
}
keyword.setHrefExternal(hrefExternal);
}
else
{
String relativePath = parameters.get("relative_path", "");
Resource[] section = coralSession.getStore().getResourceByPath(
relativePath + hrefInternal);
if(section.length != 1 || !(section[0] instanceof NavigationNodeResource))
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_target");
return;
}
keyword.setHrefInternal((NavigationNodeResource)section[0]);
}
long category_id = parameters.getLong("category_id", -1L);
CategoryResource category = null;
try
{
if(category_id != -1L)
{
category = CategoryResourceImpl.getCategoryResource(coralSession, category_id);
}
keyword.setCategory(category);
}
catch(EntityDoesNotExistException e)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword", "invalid_category");
}
keyword.setNewWindow(newWindow);
keyword.setRegexp(regExp);
keyword.setPattern(pattern);
keyword.setLinkClass(linkClass);
keyword.update();
}
catch(Exception e)
{
throw new ProcessingException("failed to update keyword", e);
}
}
| public void execute(Context context, Parameters parameters, MVCContext mvcContext,
TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession)
throws ProcessingException
{
try
{
long keywordId = parameters.getLong("keywordId");
KeywordResource keyword = KeywordResourceImpl.getKeywordResource(coralSession,
keywordId);
String pattern = parameters.get("pattern", "");
if(pattern.length() == 0)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_keyword_pattern");
return;
}
String title = parameters.get("title", "");
boolean regExp = parameters.getBoolean("reg_exp", false);
boolean newWindow = parameters.getBoolean("new_window", false);
String linkClass = parameters.get("link_class", "");
String hrefExternal = parameters.get("href_external", "");
String hrefInternal = parameters.get("href_internal", "");
boolean external = "external".equals(parameters.get("link_type", "external")) ? true
: false;
keyword.setTitle(title);
keyword.setExternal(external);
if(external)
{
if(!(hrefExternal.startsWith("http://") || hrefExternal.startsWith("https://")))
{
hrefExternal = "http://" + hrefExternal;
}
keyword.setHrefExternal(hrefExternal);
}
else
{
String relativePath = parameters.get("relative_path", "");
Resource[] section = coralSession.getStore().getResourceByPath(
relativePath + hrefInternal);
if(section.length != 1 || !(section[0] instanceof NavigationNodeResource))
{
route(mvcContext, templatingContext, "documents.UpdateKeyword",
"invalid_target");
return;
}
keyword.setHrefInternal((NavigationNodeResource)section[0]);
}
long category_id = parameters.getLong("category_id", -1L);
CategoryResource category = null;
try
{
if(category_id != -1L)
{
category = CategoryResourceImpl.getCategoryResource(coralSession, category_id);
}
keyword.setCategory(category);
}
catch(EntityDoesNotExistException e)
{
route(mvcContext, templatingContext, "documents.UpdateKeyword", "invalid_category");
}
keyword.setNewWindow(newWindow);
keyword.setRegexp(regExp);
keyword.setPattern(pattern);
keyword.setLinkClass(linkClass);
keyword.update();
}
catch(Exception e)
{
throw new ProcessingException("failed to update keyword", e);
}
}
|
diff --git a/src/java/gui/CellDialog.java b/src/java/gui/CellDialog.java
index 9b0bdef..c823100 100644
--- a/src/java/gui/CellDialog.java
+++ b/src/java/gui/CellDialog.java
@@ -1,486 +1,487 @@
package com.dickimawbooks.datatooltk.gui;
import java.util.regex.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.undo.*;
import javax.swing.text.*;
import com.dickimawbooks.datatooltk.*;
public class CellDialog extends JDialog
implements ActionListener
{
public CellDialog(DatatoolGUI gui)
{
super(gui, DatatoolTk.getLabel("celledit.title"), true);
this.gui = gui;
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
cancel();
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
ScrollToolBar toolBar = new ScrollToolBar(SwingConstants.HORIZONTAL);
getContentPane().add(toolBar, BorderLayout.NORTH);
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel, BorderLayout.CENTER);
undoManager = new UndoManager();
JMenu editM = DatatoolGuiResources.createJMenu("edit");
mbar.add(editM);
undoItem = DatatoolGuiResources.createJMenuItem(
"edit", "undo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK),
toolBar);
editM.add(undoItem);
redoItem = DatatoolGuiResources.createJMenuItem(
"edit", "redo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK),
toolBar);
editM.add(redoItem);
editM.addSeparator();
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "select_all", this,
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK),
toolBar));
cutItem = DatatoolGuiResources.createJMenuItem(
"edit", "cut", this,
KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
toolBar);
editM.add(cutItem);
copyItem = DatatoolGuiResources.createJMenuItem(
"edit", "copy", this,
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
toolBar);
editM.add(copyItem);
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "paste", this,
KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
toolBar));
JMenu searchM = DatatoolGuiResources.createJMenu("search");
mbar.add(searchM);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "find", this,
KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK),
toolBar));
findAgainItem = DatatoolGuiResources.createJMenuItem(
"search", "find_again", this,
KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK),
toolBar);
searchM.add(findAgainItem);
findAgainItem.setEnabled(false);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "replace", this,
KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK),
toolBar));
document = new CellDocument(this,
gui.getSettings());
textPane = new JTextPane(document);
textPane.setFont(gui.getCellFont());
FontMetrics fm = getFontMetrics(textPane.getFont());
textPane.setPreferredSize(new Dimension
(gui.getSettings().getCellEditorWidth()*fm.getMaxAdvance(),
gui.getSettings().getCellEditorHeight()*fm.getHeight()));
textPane.setEditable(true);
document.addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
modified = true;
}
public void insertUpdate(DocumentEvent e)
{
modified = true;
}
public void removeUpdate(DocumentEvent e)
{
modified = true;
}
});
textPane.addCaretListener(new CaretListener()
{
public void caretUpdate(CaretEvent evt)
{
updateEditButtons();
}
});
updateEditButtons();
findDialog = new FindDialog(this, textPane);
+ textPane.setMinimumSize(new Dimension(0,0));
mainPanel.add(new JScrollPane(textPane), BorderLayout.CENTER);
mainPanel.add(
DatatoolGuiResources.createOkayCancelHelpPanel(this, gui, "celleditor"),
BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
public boolean requestEdit(int row, int col,
DatatoolDbPanel panel)
{
this.panel = panel;
this.db = panel.db;
this.row = row;
this.col = col;
textPane.setFont(gui.getCellFont());
try
{
document.setText(
db.getRow(row).get(col).replaceAll("\\\\DTLpar *", "\n\n"));
}
catch (BadLocationException e)
{
DatatoolGuiResources.error(this, e);
}
undoManager.discardAllEdits();
undoItem.setEnabled(false);
redoItem.setEnabled(false);
revalidate();
modified = false;
textPane.requestFocusInWindow();
textPane.setCaretPosition(0);
setVisible(true);
return modified;
}
public void actionPerformed(ActionEvent evt)
{
String action = evt.getActionCommand();
if (action == null) return;
if (action.equals("okay"))
{
okay();
}
else if (action.equals("cancel"))
{
cancel();
}
else if (action.equals("undo"))
{
try
{
undoManager.undo();
}
catch (CannotUndoException e)
{
DatatoolTk.debug(e);
}
undoItem.setEnabled(undoManager.canUndo());
redoItem.setEnabled(undoManager.canRedo());
}
else if (action.equals("redo"))
{
try
{
undoManager.redo();
}
catch (CannotRedoException e)
{
DatatoolTk.debug(e);
}
undoItem.setEnabled(undoManager.canUndo());
redoItem.setEnabled(undoManager.canRedo());
}
else if (action.equals("select_all"))
{
textPane.selectAll();
}
else if (action.equals("copy"))
{
textPane.copy();
}
else if (action.equals("cut"))
{
textPane.cut();
}
else if (action.equals("paste"))
{
textPane.paste();
}
else if (action.equals("find"))
{
String selectedText = textPane.getSelectedText();
if (selectedText != null)
{
findDialog.setSearchText(selectedText);
}
findDialog.display(false);
}
else if (action.equals("find_again"))
{
findDialog.find();
}
else if (action.equals("replace"))
{
String selectedText = textPane.getSelectedText();
if (selectedText != null)
{
findDialog.setSearchText(selectedText);
}
findDialog.display(true);
}
}
public void okay()
{
panel.updateCell(row, col,
textPane.getText().replaceAll("\n *\n+", "\\\\DTLpar "));
setVisible(false);
}
public void cancel()
{
if (modified)
{
if (JOptionPane.showConfirmDialog(this,
DatatoolTk.getLabel("message.discard_edit_query"),
DatatoolTk.getLabel("message.confirm_discard"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE)
!= JOptionPane.YES_OPTION)
{
return;
}
modified = false;
}
setVisible(false);
}
private void updateEditButtons()
{
String selected = (textPane == null ? null : textPane.getSelectedText());
if (selected == null || selected.isEmpty())
{
copyItem.setEnabled(false);
cutItem.setEnabled(false);
}
else
{
copyItem.setEnabled(true);
cutItem.setEnabled(true);
}
findAgainItem.setEnabled(findDialog == null ? false :
!findDialog.getSearchText().isEmpty());
}
public void addEdit(UndoableEdit edit)
{
undoManager.addEdit(edit);
undoItem.setEnabled(true);
}
private JTextPane textPane;
private CellDocument document;
private JMenuItem undoItem, redoItem, copyItem, cutItem,
findAgainItem;
private DatatoolDbPanel panel;
private DatatoolDb db;
private int row, col;
private DatatoolGUI gui;
private boolean modified;
private FindDialog findDialog;
private UndoManager undoManager;
}
class CellDocument extends DefaultStyledDocument
{
public CellDocument(CellDialog dialog, DatatoolSettings settings)
{
super();
this.cellDialog = dialog;
this.highlightOn = settings.isSyntaxHighlightingOn();
StyleContext context = StyleContext.getDefaultStyleContext();
attrPlain = context.addAttribute(context.getEmptySet(),
StyleConstants.Foreground, Color.BLACK);
attrControlSequence = context.addAttribute(context.getEmptySet(),
StyleConstants.Foreground, settings.getControlSequenceHighlight());
attrComment = new SimpleAttributeSet();
StyleConstants.setItalic(attrComment, true);
StyleConstants.setForeground(attrComment,
settings.getCommentHighlight());
addUndoableEditListener(
new UndoableEditListener()
{
public void undoableEditHappened(UndoableEditEvent event)
{
if (compoundEdit == null)
{
cellDialog.addEdit(event.getEdit());
}
else
{
compoundEdit.addEdit(event.getEdit());
}
}
});
}
public void remove(int offset, int length)
throws BadLocationException
{
super.remove(offset, length);
updateHighlight();
}
public void insertString(int offset, String str, AttributeSet at)
throws BadLocationException
{
super.insertString(offset, str, at);
updateHighlight();
}
private void updateHighlight()
throws BadLocationException
{
if (!highlightOn) return;
String text = getText(0, getLength());
setCharacterAttributes(0, getLength(),
attrPlain, true);
Matcher matcher = PATTERN_CS.matcher(text);
while (matcher.find())
{
int newOffset = matcher.start();
int len = matcher.end() - newOffset;
String group = matcher.group();
if (group.startsWith("%"))
{
setCharacterAttributes(newOffset, len, attrComment, true);
}
else
{
setCharacterAttributes(newOffset, len, attrControlSequence, false);
}
}
}
public void replace(int offset, int length, String text,
AttributeSet attrs)
throws BadLocationException
{
compoundEdit = new CompoundEdit();
try
{
super.replace(offset, length, text, attrs);
compoundEdit.end();
cellDialog.addEdit(compoundEdit);
}
finally
{
compoundEdit = null;
}
updateHighlight();
}
// This method is for initialising so bypass the undo/redo
// stuff
public void setText(String text)
throws BadLocationException
{
super.remove(0, getLength());
super.insertString(0, text, null);
updateHighlight();
}
private CellDialog cellDialog;
private boolean highlightOn;
private CompoundEdit compoundEdit;
private AttributeSet attrPlain;
private AttributeSet attrControlSequence;
private SimpleAttributeSet attrComment;
private static final Pattern PATTERN_CS = Pattern.compile(
"((?:\\\\[^a-zA-Z]{1})|(?:\\\\[a-zA-Z]+)|(?:[#~\\{\\}\\^\\$_])|(?:%.*))");
}
| true | true | public CellDialog(DatatoolGUI gui)
{
super(gui, DatatoolTk.getLabel("celledit.title"), true);
this.gui = gui;
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
cancel();
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
ScrollToolBar toolBar = new ScrollToolBar(SwingConstants.HORIZONTAL);
getContentPane().add(toolBar, BorderLayout.NORTH);
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel, BorderLayout.CENTER);
undoManager = new UndoManager();
JMenu editM = DatatoolGuiResources.createJMenu("edit");
mbar.add(editM);
undoItem = DatatoolGuiResources.createJMenuItem(
"edit", "undo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK),
toolBar);
editM.add(undoItem);
redoItem = DatatoolGuiResources.createJMenuItem(
"edit", "redo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK),
toolBar);
editM.add(redoItem);
editM.addSeparator();
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "select_all", this,
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK),
toolBar));
cutItem = DatatoolGuiResources.createJMenuItem(
"edit", "cut", this,
KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
toolBar);
editM.add(cutItem);
copyItem = DatatoolGuiResources.createJMenuItem(
"edit", "copy", this,
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
toolBar);
editM.add(copyItem);
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "paste", this,
KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
toolBar));
JMenu searchM = DatatoolGuiResources.createJMenu("search");
mbar.add(searchM);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "find", this,
KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK),
toolBar));
findAgainItem = DatatoolGuiResources.createJMenuItem(
"search", "find_again", this,
KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK),
toolBar);
searchM.add(findAgainItem);
findAgainItem.setEnabled(false);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "replace", this,
KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK),
toolBar));
document = new CellDocument(this,
gui.getSettings());
textPane = new JTextPane(document);
textPane.setFont(gui.getCellFont());
FontMetrics fm = getFontMetrics(textPane.getFont());
textPane.setPreferredSize(new Dimension
(gui.getSettings().getCellEditorWidth()*fm.getMaxAdvance(),
gui.getSettings().getCellEditorHeight()*fm.getHeight()));
textPane.setEditable(true);
document.addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
modified = true;
}
public void insertUpdate(DocumentEvent e)
{
modified = true;
}
public void removeUpdate(DocumentEvent e)
{
modified = true;
}
});
textPane.addCaretListener(new CaretListener()
{
public void caretUpdate(CaretEvent evt)
{
updateEditButtons();
}
});
updateEditButtons();
findDialog = new FindDialog(this, textPane);
mainPanel.add(new JScrollPane(textPane), BorderLayout.CENTER);
mainPanel.add(
DatatoolGuiResources.createOkayCancelHelpPanel(this, gui, "celleditor"),
BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
| public CellDialog(DatatoolGUI gui)
{
super(gui, DatatoolTk.getLabel("celledit.title"), true);
this.gui = gui;
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
cancel();
}
});
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
ScrollToolBar toolBar = new ScrollToolBar(SwingConstants.HORIZONTAL);
getContentPane().add(toolBar, BorderLayout.NORTH);
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel, BorderLayout.CENTER);
undoManager = new UndoManager();
JMenu editM = DatatoolGuiResources.createJMenu("edit");
mbar.add(editM);
undoItem = DatatoolGuiResources.createJMenuItem(
"edit", "undo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK),
toolBar);
editM.add(undoItem);
redoItem = DatatoolGuiResources.createJMenuItem(
"edit", "redo", this,
KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK),
toolBar);
editM.add(redoItem);
editM.addSeparator();
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "select_all", this,
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK),
toolBar));
cutItem = DatatoolGuiResources.createJMenuItem(
"edit", "cut", this,
KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
toolBar);
editM.add(cutItem);
copyItem = DatatoolGuiResources.createJMenuItem(
"edit", "copy", this,
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
toolBar);
editM.add(copyItem);
editM.add(DatatoolGuiResources.createJMenuItem(
"edit", "paste", this,
KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
toolBar));
JMenu searchM = DatatoolGuiResources.createJMenu("search");
mbar.add(searchM);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "find", this,
KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_MASK),
toolBar));
findAgainItem = DatatoolGuiResources.createJMenuItem(
"search", "find_again", this,
KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK),
toolBar);
searchM.add(findAgainItem);
findAgainItem.setEnabled(false);
searchM.add(DatatoolGuiResources.createJMenuItem(
"search", "replace", this,
KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK),
toolBar));
document = new CellDocument(this,
gui.getSettings());
textPane = new JTextPane(document);
textPane.setFont(gui.getCellFont());
FontMetrics fm = getFontMetrics(textPane.getFont());
textPane.setPreferredSize(new Dimension
(gui.getSettings().getCellEditorWidth()*fm.getMaxAdvance(),
gui.getSettings().getCellEditorHeight()*fm.getHeight()));
textPane.setEditable(true);
document.addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent e)
{
modified = true;
}
public void insertUpdate(DocumentEvent e)
{
modified = true;
}
public void removeUpdate(DocumentEvent e)
{
modified = true;
}
});
textPane.addCaretListener(new CaretListener()
{
public void caretUpdate(CaretEvent evt)
{
updateEditButtons();
}
});
updateEditButtons();
findDialog = new FindDialog(this, textPane);
textPane.setMinimumSize(new Dimension(0,0));
mainPanel.add(new JScrollPane(textPane), BorderLayout.CENTER);
mainPanel.add(
DatatoolGuiResources.createOkayCancelHelpPanel(this, gui, "celleditor"),
BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
}
|
diff --git a/common/net/minecraftforge/oredict/OreDictionary.java b/common/net/minecraftforge/oredict/OreDictionary.java
index 538d699f9..fb97cea2f 100644
--- a/common/net/minecraftforge/oredict/OreDictionary.java
+++ b/common/net/minecraftforge/oredict/OreDictionary.java
@@ -1,311 +1,311 @@
package net.minecraftforge.oredict;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.Event;
public class OreDictionary
{
private static boolean hasInit = false;
private static int maxID = 0;
private static HashMap<String, Integer> oreIDs = new HashMap<String, Integer>();
private static HashMap<Integer, ArrayList<ItemStack>> oreStacks = new HashMap<Integer, ArrayList<ItemStack>>();
/**
* Minecraft changed from -1 to Short.MAX_VALUE in 1.5 release for the "block wildcard". Use this in case it
* changes again.
*/
public static final int WILDCARD_VALUE = Short.MAX_VALUE;
static {
initVanillaEntries();
}
public static void initVanillaEntries()
{
if (!hasInit)
{
registerOre("logWood", new ItemStack(Block.wood, 1, WILDCARD_VALUE));
registerOre("plankWood", new ItemStack(Block.planks, 1, WILDCARD_VALUE));
registerOre("slabWood", new ItemStack(Block.woodSingleSlab, 1, WILDCARD_VALUE));
registerOre("stairWood", Block.stairCompactPlanks);
registerOre("stairWood", Block.stairsWoodBirch);
registerOre("stairWood", Block.stairsWoodJungle);
registerOre("stairWood", Block.stairsWoodSpruce);
registerOre("stickWood", Item.stick);
registerOre("treeSapling", new ItemStack(Block.sapling, 1, WILDCARD_VALUE));
registerOre("treeLeaves", new ItemStack(Block.leaves, 1, WILDCARD_VALUE));
}
// Build our list of items to replace with ore tags
Map<ItemStack, String> replacements = new HashMap<ItemStack, String>();
- replacements.put(new ItemStack(Block.planks, 1, -1), "plankWood");
+ replacements.put(new ItemStack(Block.planks, 1, WILDCARD_VALUE), "plankWood");
replacements.put(new ItemStack(Item.stick), "stickWood");
// Register dyes
String[] dyes =
{
"dyeBlack",
"dyeRed",
"dyeGreen",
"dyeBrown",
"dyeBlue",
"dyePurple",
"dyeCyan",
"dyeLightGray",
"dyeGray",
"dyePink",
"dyeLime",
"dyeYellow",
"dyeLightBlue",
"dyeMagenta",
"dyeOrange",
"dyeWhite"
};
for(int i = 0; i < 16; i++)
{
ItemStack dye = new ItemStack(Item.dyePowder, 1, i);
if (!hasInit)
{
registerOre(dyes[i], dye);
}
replacements.put(dye, dyes[i]);
}
hasInit = true;
ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[replacements.keySet().size()]);
// Ignore recipes for the following items
ItemStack[] exclusions = new ItemStack[]
{
new ItemStack(Block.blockLapis),
new ItemStack(Item.cookie),
};
List recipes = CraftingManager.getInstance().getRecipeList();
List<IRecipe> recipesToRemove = new ArrayList<IRecipe>();
List<IRecipe> recipesToAdd = new ArrayList<IRecipe>();
// Search vanilla recipes for recipes to replace
for(Object obj : recipes)
{
if(obj instanceof ShapedRecipes)
{
ShapedRecipes recipe = (ShapedRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, recipe.recipeItems, replaceStacks))
{
recipesToRemove.add(recipe);
recipesToAdd.add(new ShapedOreRecipe(recipe, replacements));
}
}
else if(obj instanceof ShapelessRecipes)
{
ShapelessRecipes recipe = (ShapelessRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, (ItemStack[])recipe.recipeItems.toArray(new ItemStack[recipe.recipeItems.size()]), replaceStacks))
{
recipesToRemove.add((IRecipe)obj);
IRecipe newRecipe = new ShapelessOreRecipe(recipe, replacements);
recipesToAdd.add(newRecipe);
}
}
}
recipes.removeAll(recipesToRemove);
recipes.addAll(recipesToAdd);
if (recipesToRemove.size() > 0)
{
System.out.println("Replaced " + recipesToRemove.size() + " ore recipies");
}
}
/**
* Gets the integer ID for the specified ore name.
* If the name does not have a ID it assigns it a new one.
*
* @param name The unique name for this ore 'oreIron', 'ingotIron', etc..
* @return A number representing the ID for this ore type
*/
public static int getOreID(String name)
{
Integer val = oreIDs.get(name);
if (val == null)
{
val = maxID++;
oreIDs.put(name, val);
oreStacks.put(val, new ArrayList<ItemStack>());
}
return val;
}
/**
* Reverse of getOreID, will not create new entries.
*
* @param id The ID to translate to a string
* @return The String name, or "Unknown" if not found.
*/
public static String getOreName(int id)
{
for (Map.Entry<String, Integer> entry : oreIDs.entrySet())
{
if (id == entry.getValue())
{
return entry.getKey();
}
}
return "Unknown";
}
/**
* Gets the integer ID for the specified item stack.
* If the item stack is not linked to any ore, this will return -1 and no new entry will be created.
*
* @param itemStack The item stack of the ore.
* @return A number representing the ID for this ore type, or -1 if couldn't find it.
*/
public static int getOreID(ItemStack itemStack)
{
if (itemStack == null)
{
return -1;
}
for(Entry<Integer, ArrayList<ItemStack>> ore : oreStacks.entrySet())
{
for(ItemStack target : ore.getValue())
{
if(itemStack.itemID == target.itemID && (target.getItemDamage() == WILDCARD_VALUE || itemStack.getItemDamage() == target.getItemDamage()))
{
return ore.getKey();
}
}
}
return -1; // didn't find it.
}
/**
* Retrieves the ArrayList of items that are registered to this ore type.
* Creates the list as empty if it did not exist.
*
* @param name The ore name, directly calls getOreID
* @return An arrayList containing ItemStacks registered for this ore
*/
public static ArrayList<ItemStack> getOres(String name)
{
return getOres(getOreID(name));
}
/**
* Retrieves a list of all unique ore names that are already registered.
*
* @return All unique ore names that are currently registered.
*/
public static String[] getOreNames()
{
return oreIDs.keySet().toArray(new String[oreIDs.keySet().size()]);
}
/**
* Retrieves the ArrayList of items that are registered to this ore type.
* Creates the list as empty if it did not exist.
*
* @param id The ore ID, see getOreID
* @return An arrayList containing ItemStacks registered for this ore
*/
public static ArrayList<ItemStack> getOres(Integer id)
{
ArrayList<ItemStack> val = oreStacks.get(id);
if (val == null)
{
val = new ArrayList<ItemStack>();
oreStacks.put(id, val);
}
return val;
}
private static boolean containsMatch(boolean strict, ItemStack[] inputs, ItemStack... targets)
{
for (ItemStack input : inputs)
{
for (ItemStack target : targets)
{
if (itemMatches(target, input, strict))
{
return true;
}
}
}
return false;
}
public static boolean itemMatches(ItemStack target, ItemStack input, boolean strict)
{
if (input == null && target != null || input != null && target == null)
{
return false;
}
return (target.itemID == input.itemID && ((target.getItemDamage() == WILDCARD_VALUE && !strict) || target.getItemDamage() == input.getItemDamage()));
}
//Convenience functions that make for cleaner code mod side. They all drill down to registerOre(String, int, ItemStack)
public static void registerOre(String name, Item ore){ registerOre(name, new ItemStack(ore)); }
public static void registerOre(String name, Block ore){ registerOre(name, new ItemStack(ore)); }
public static void registerOre(String name, ItemStack ore){ registerOre(name, getOreID(name), ore); }
public static void registerOre(int id, Item ore){ registerOre(id, new ItemStack(ore)); }
public static void registerOre(int id, Block ore){ registerOre(id, new ItemStack(ore)); }
public static void registerOre(int id, ItemStack ore){ registerOre(getOreName(id), id, ore); }
/**
* Registers a ore item into the dictionary.
* Raises the registerOre function in all registered handlers.
*
* @param name The name of the ore
* @param id The ID of the ore
* @param ore The ore's ItemStack
*/
private static void registerOre(String name, int id, ItemStack ore)
{
ArrayList<ItemStack> ores = getOres(id);
ore = ore.copy();
ores.add(ore);
MinecraftForge.EVENT_BUS.post(new OreRegisterEvent(name, ore));
}
public static class OreRegisterEvent extends Event
{
public final String Name;
public final ItemStack Ore;
public OreRegisterEvent(String name, ItemStack ore)
{
this.Name = name;
this.Ore = ore;
}
}
}
| true | true | public static void initVanillaEntries()
{
if (!hasInit)
{
registerOre("logWood", new ItemStack(Block.wood, 1, WILDCARD_VALUE));
registerOre("plankWood", new ItemStack(Block.planks, 1, WILDCARD_VALUE));
registerOre("slabWood", new ItemStack(Block.woodSingleSlab, 1, WILDCARD_VALUE));
registerOre("stairWood", Block.stairCompactPlanks);
registerOre("stairWood", Block.stairsWoodBirch);
registerOre("stairWood", Block.stairsWoodJungle);
registerOre("stairWood", Block.stairsWoodSpruce);
registerOre("stickWood", Item.stick);
registerOre("treeSapling", new ItemStack(Block.sapling, 1, WILDCARD_VALUE));
registerOre("treeLeaves", new ItemStack(Block.leaves, 1, WILDCARD_VALUE));
}
// Build our list of items to replace with ore tags
Map<ItemStack, String> replacements = new HashMap<ItemStack, String>();
replacements.put(new ItemStack(Block.planks, 1, -1), "plankWood");
replacements.put(new ItemStack(Item.stick), "stickWood");
// Register dyes
String[] dyes =
{
"dyeBlack",
"dyeRed",
"dyeGreen",
"dyeBrown",
"dyeBlue",
"dyePurple",
"dyeCyan",
"dyeLightGray",
"dyeGray",
"dyePink",
"dyeLime",
"dyeYellow",
"dyeLightBlue",
"dyeMagenta",
"dyeOrange",
"dyeWhite"
};
for(int i = 0; i < 16; i++)
{
ItemStack dye = new ItemStack(Item.dyePowder, 1, i);
if (!hasInit)
{
registerOre(dyes[i], dye);
}
replacements.put(dye, dyes[i]);
}
hasInit = true;
ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[replacements.keySet().size()]);
// Ignore recipes for the following items
ItemStack[] exclusions = new ItemStack[]
{
new ItemStack(Block.blockLapis),
new ItemStack(Item.cookie),
};
List recipes = CraftingManager.getInstance().getRecipeList();
List<IRecipe> recipesToRemove = new ArrayList<IRecipe>();
List<IRecipe> recipesToAdd = new ArrayList<IRecipe>();
// Search vanilla recipes for recipes to replace
for(Object obj : recipes)
{
if(obj instanceof ShapedRecipes)
{
ShapedRecipes recipe = (ShapedRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, recipe.recipeItems, replaceStacks))
{
recipesToRemove.add(recipe);
recipesToAdd.add(new ShapedOreRecipe(recipe, replacements));
}
}
else if(obj instanceof ShapelessRecipes)
{
ShapelessRecipes recipe = (ShapelessRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, (ItemStack[])recipe.recipeItems.toArray(new ItemStack[recipe.recipeItems.size()]), replaceStacks))
{
recipesToRemove.add((IRecipe)obj);
IRecipe newRecipe = new ShapelessOreRecipe(recipe, replacements);
recipesToAdd.add(newRecipe);
}
}
}
recipes.removeAll(recipesToRemove);
recipes.addAll(recipesToAdd);
if (recipesToRemove.size() > 0)
{
System.out.println("Replaced " + recipesToRemove.size() + " ore recipies");
}
}
| public static void initVanillaEntries()
{
if (!hasInit)
{
registerOre("logWood", new ItemStack(Block.wood, 1, WILDCARD_VALUE));
registerOre("plankWood", new ItemStack(Block.planks, 1, WILDCARD_VALUE));
registerOre("slabWood", new ItemStack(Block.woodSingleSlab, 1, WILDCARD_VALUE));
registerOre("stairWood", Block.stairCompactPlanks);
registerOre("stairWood", Block.stairsWoodBirch);
registerOre("stairWood", Block.stairsWoodJungle);
registerOre("stairWood", Block.stairsWoodSpruce);
registerOre("stickWood", Item.stick);
registerOre("treeSapling", new ItemStack(Block.sapling, 1, WILDCARD_VALUE));
registerOre("treeLeaves", new ItemStack(Block.leaves, 1, WILDCARD_VALUE));
}
// Build our list of items to replace with ore tags
Map<ItemStack, String> replacements = new HashMap<ItemStack, String>();
replacements.put(new ItemStack(Block.planks, 1, WILDCARD_VALUE), "plankWood");
replacements.put(new ItemStack(Item.stick), "stickWood");
// Register dyes
String[] dyes =
{
"dyeBlack",
"dyeRed",
"dyeGreen",
"dyeBrown",
"dyeBlue",
"dyePurple",
"dyeCyan",
"dyeLightGray",
"dyeGray",
"dyePink",
"dyeLime",
"dyeYellow",
"dyeLightBlue",
"dyeMagenta",
"dyeOrange",
"dyeWhite"
};
for(int i = 0; i < 16; i++)
{
ItemStack dye = new ItemStack(Item.dyePowder, 1, i);
if (!hasInit)
{
registerOre(dyes[i], dye);
}
replacements.put(dye, dyes[i]);
}
hasInit = true;
ItemStack[] replaceStacks = replacements.keySet().toArray(new ItemStack[replacements.keySet().size()]);
// Ignore recipes for the following items
ItemStack[] exclusions = new ItemStack[]
{
new ItemStack(Block.blockLapis),
new ItemStack(Item.cookie),
};
List recipes = CraftingManager.getInstance().getRecipeList();
List<IRecipe> recipesToRemove = new ArrayList<IRecipe>();
List<IRecipe> recipesToAdd = new ArrayList<IRecipe>();
// Search vanilla recipes for recipes to replace
for(Object obj : recipes)
{
if(obj instanceof ShapedRecipes)
{
ShapedRecipes recipe = (ShapedRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, recipe.recipeItems, replaceStacks))
{
recipesToRemove.add(recipe);
recipesToAdd.add(new ShapedOreRecipe(recipe, replacements));
}
}
else if(obj instanceof ShapelessRecipes)
{
ShapelessRecipes recipe = (ShapelessRecipes)obj;
ItemStack output = recipe.getRecipeOutput();
if (output != null && containsMatch(false, exclusions, output))
{
continue;
}
if(containsMatch(true, (ItemStack[])recipe.recipeItems.toArray(new ItemStack[recipe.recipeItems.size()]), replaceStacks))
{
recipesToRemove.add((IRecipe)obj);
IRecipe newRecipe = new ShapelessOreRecipe(recipe, replacements);
recipesToAdd.add(newRecipe);
}
}
}
recipes.removeAll(recipesToRemove);
recipes.addAll(recipesToAdd);
if (recipesToRemove.size() > 0)
{
System.out.println("Replaced " + recipesToRemove.size() + " ore recipies");
}
}
|
diff --git a/project2/src/hmm/StateCollection.java b/project2/src/hmm/StateCollection.java
index 29a8e97..ed9d176 100644
--- a/project2/src/hmm/StateCollection.java
+++ b/project2/src/hmm/StateCollection.java
@@ -1,141 +1,142 @@
package hmm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class StateCollection {
HashMap<String, State> states;
HashSet<String> state_names;
public State startTag() {
return states.get("");
}
public StateCollection() {
states = new HashMap<String, State>();
state_names = new HashSet<String>();
}
public void addStateTansitionObservation(String word, String stateString,
String previousStateString) {
if (previousStateString != "")
state_names.add(previousStateString);
State previousState;
State state;
// load previous state
if (!states.containsKey(previousStateString)) {
previousState = new State(previousStateString);
states.put(previousStateString, previousState);
} else {
previousState = states.get(previousStateString);
}
// load current state
if (!states.containsKey(stateString)) {
state = new State(stateString);
states.put(stateString, state);
} else {
state = states.get(stateString);
}
state.addWordEmissionObservation(word);
previousState.addStateTransitionObservation(state.name);
}
public void addFinalStateTransitionObservation(String previousState) {
state_names.add(previousState);
states.get(previousState).addStateTransitionObservation(null);
}
/**
* Calculate the probability of a sentence and a tag sequence
* @param sentence word/tag pairs which make up the sentence
* @return
*/
public double calculateProbabilityofSentenceWithStates(
ArrayList<String> sentence) {
double probability = 1;
String old_tag = "";
for (String wordPair : sentence) {
String[] splitting = wordPair.split("/");
String word = splitting[0];
String tag = splitting[1];
// Multiply with tag-to-tag probability
probability *= states.get(old_tag).nextStateProbability(tag);
// Multiply with tag-to-word probability
probability *= states.get(tag).wordEmittingProbability(word);
old_tag = tag;
}
// Multiply with final-tag probability
probability *= states.get(old_tag).nextStateProbability(null);
return probability;
}
public ArrayList<String> calculateStatesofSentence(
ArrayList<String> sentence) {
ArrayList<String> result = new ArrayList<String>();
HashMap<String, Double> probabilities = new HashMap<String, Double>();
String[] splitting = sentence.get(0).split("/");
String first_word = splitting[0];
// Calculate starting probabilities
for (String state : state_names) {
double value = states.get("").nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(first_word);
probabilities.put(state, value);
}
result.add(getMaxState(probabilities));
// Calculate all other probabilities
HashMap<String, Double> new_probabilities = new HashMap<String, Double>();
for (int i=1; i<sentence.size(); i++) {
splitting = sentence.get(1).split("/");
String word = splitting[0];
for (String state : state_names) {
double max_value = 0;
for (String previous_state : state_names) {
double value = probabilities.get(previous_state);
value *= states.get(previous_state).nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(word);
if (value > max_value)
max_value = value;
}
new_probabilities.put(state, max_value);
}
result.add(getMaxState(new_probabilities));
probabilities = new_probabilities;
+ new_probabilities = new HashMap<String, Double>();
}
return result;
}
private static String getMaxState(HashMap<String, Double> probabilities) {
String max_string = "";
double max_probability = 0;
for (String key : probabilities.keySet()) {
double new_probability = probabilities.get(key);
if (new_probability > max_probability) {
max_probability = new_probability;
max_string = key;
}
}
return max_string;
}
}
| true | true | public ArrayList<String> calculateStatesofSentence(
ArrayList<String> sentence) {
ArrayList<String> result = new ArrayList<String>();
HashMap<String, Double> probabilities = new HashMap<String, Double>();
String[] splitting = sentence.get(0).split("/");
String first_word = splitting[0];
// Calculate starting probabilities
for (String state : state_names) {
double value = states.get("").nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(first_word);
probabilities.put(state, value);
}
result.add(getMaxState(probabilities));
// Calculate all other probabilities
HashMap<String, Double> new_probabilities = new HashMap<String, Double>();
for (int i=1; i<sentence.size(); i++) {
splitting = sentence.get(1).split("/");
String word = splitting[0];
for (String state : state_names) {
double max_value = 0;
for (String previous_state : state_names) {
double value = probabilities.get(previous_state);
value *= states.get(previous_state).nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(word);
if (value > max_value)
max_value = value;
}
new_probabilities.put(state, max_value);
}
result.add(getMaxState(new_probabilities));
probabilities = new_probabilities;
}
return result;
}
| public ArrayList<String> calculateStatesofSentence(
ArrayList<String> sentence) {
ArrayList<String> result = new ArrayList<String>();
HashMap<String, Double> probabilities = new HashMap<String, Double>();
String[] splitting = sentence.get(0).split("/");
String first_word = splitting[0];
// Calculate starting probabilities
for (String state : state_names) {
double value = states.get("").nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(first_word);
probabilities.put(state, value);
}
result.add(getMaxState(probabilities));
// Calculate all other probabilities
HashMap<String, Double> new_probabilities = new HashMap<String, Double>();
for (int i=1; i<sentence.size(); i++) {
splitting = sentence.get(1).split("/");
String word = splitting[0];
for (String state : state_names) {
double max_value = 0;
for (String previous_state : state_names) {
double value = probabilities.get(previous_state);
value *= states.get(previous_state).nextStateProbability(state);
value *= states.get(state).wordEmittingProbability(word);
if (value > max_value)
max_value = value;
}
new_probabilities.put(state, max_value);
}
result.add(getMaxState(new_probabilities));
probabilities = new_probabilities;
new_probabilities = new HashMap<String, Double>();
}
return result;
}
|
diff --git a/src/de/htwg/mgse/formular/model/Input.java b/src/de/htwg/mgse/formular/model/Input.java
index 73f71c0..afada78 100644
--- a/src/de/htwg/mgse/formular/model/Input.java
+++ b/src/de/htwg/mgse/formular/model/Input.java
@@ -1,41 +1,41 @@
package de.htwg.mgse.formular.model;
public class Input extends Element {
private InputType type;
private String defaultValue;
public Input(String id) {
this.id = id;
}
public InputType getType() {
return type;
}
public String getDefaultValue() {
return defaultValue;
}
public void setType(InputType type) {
this.type = type;
}
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
public String toHtml() {
String prefix = "\t" + label + ":<br />\n";
- String intCheck = "onkeypress=\"return (function(e){var c = (e.which) ? e.which : event.keyCode; return !(c != 46 && c > 31 && (c < 48 || c > 57)); })(event)\"";
+ String intCheck = "onkeypress=\"return (function(e){var c = (e.which) ? e.which : event.keyCode; return !(c != 0 && c != 47 && c != 37 && c != 39 && c > 31 && (c < 48 || c > 57)); })(event)\"";
switch (type) {
case PASSWORD:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"password\" /><br />\n";
case INT:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" " + intCheck + " /><br />\n";
default:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" /><br />\n";
}
}
}
| true | true | public String toHtml() {
String prefix = "\t" + label + ":<br />\n";
String intCheck = "onkeypress=\"return (function(e){var c = (e.which) ? e.which : event.keyCode; return !(c != 46 && c > 31 && (c < 48 || c > 57)); })(event)\"";
switch (type) {
case PASSWORD:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"password\" /><br />\n";
case INT:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" " + intCheck + " /><br />\n";
default:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" /><br />\n";
}
}
| public String toHtml() {
String prefix = "\t" + label + ":<br />\n";
String intCheck = "onkeypress=\"return (function(e){var c = (e.which) ? e.which : event.keyCode; return !(c != 0 && c != 47 && c != 37 && c != 39 && c > 31 && (c < 48 || c > 57)); })(event)\"";
switch (type) {
case PASSWORD:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"password\" /><br />\n";
case INT:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" " + intCheck + " /><br />\n";
default:
return prefix + "\t<input name=\"" + id + "\" value=\"" + defaultValue + "\" type=\"text\" /><br />\n";
}
}
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/db/DB2SingleDbJDBCConnection.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/db/DB2SingleDbJDBCConnection.java
index 95f60d397..a6f2cde84 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/db/DB2SingleDbJDBCConnection.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/jdbc/db/DB2SingleDbJDBCConnection.java
@@ -1,80 +1,80 @@
/*
* Copyright (C) 2003-2010 eXo Platform SAS.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
*/
package org.exoplatform.services.jcr.impl.storage.jdbc.db;
import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
import org.exoplatform.services.jcr.storage.value.ValueStoragePluginProvider;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Created by The eXo Platform SAS.
*
* Date: 8 02 2011
*
* @author <a href="mailto:[email protected]">Anatoliy Bazko</a>
* @version $Id: MSSQLSingleDbJDBCConnection.java 34360 2010-11-11 11:11:11Z tolusha $
*/
public class DB2SingleDbJDBCConnection extends SingleDbJDBCConnection
{
/**
* Sybase Singledatabase JDBC Connection constructor.
*
* @param dbConnection
* JDBC connection, should be opened before
* @param readOnly
* boolean if true the dbConnection was marked as READ-ONLY.
* @param containerName
* Workspace Storage Container name (see configuration)
* @param valueStorageProvider
* External Value Storages provider
* @param maxBufferSize
* Maximum buffer size (see configuration)
* @param swapDirectory
* Swap directory File (see configuration)
* @param swapCleaner
* Swap cleaner (internal FileCleaner).
* @throws SQLException
*
* @see org.exoplatform.services.jcr.impl.util.io.FileCleaner
*/
public DB2SingleDbJDBCConnection(Connection dbConnection, boolean readOnly, String containerName,
ValueStoragePluginProvider valueStorageProvider, int maxBufferSize, File swapDirectory, FileCleaner swapCleaner)
throws SQLException
{
super(dbConnection, readOnly, containerName, valueStorageProvider, maxBufferSize, swapDirectory, swapCleaner);
}
/**
* {@inheritDoc}
*/
@Override
protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
- + " from JCR_SITEM I where I.CONTAINER_NAME='?' and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ + " from JCR_SITEM I where I.CONTAINER_NAME=? and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
- + " where P.I_CLASS=2 and P.CONTAINER_NAME='?' and V.PROPERTY_ID=P.ID order by J.ID";
+ + " where P.I_CLASS=2 and P.CONTAINER_NAME=? and V.PROPERTY_ID=P.ID order by J.ID";
}
}
| false | true | protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
+ " from JCR_SITEM I where I.CONTAINER_NAME='?' and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
+ " where P.I_CLASS=2 and P.CONTAINER_NAME='?' and V.PROPERTY_ID=P.ID order by J.ID";
}
| protected void prepareQueries() throws SQLException
{
super.prepareQueries();
FIND_NODES_AND_PROPERTIES =
"select J.*, P.ID AS P_ID, P.NAME AS P_NAME, P.VERSION AS P_VERSION, P.P_TYPE, P.P_MULTIVALUED,"
+ " V.DATA, V.ORDER_NUM, V.STORAGE_DESC from JCR_SVALUE V, JCR_SITEM P"
+ " join (select A.* from"
+ " (select Row_Number() over (order by I.ID) as r__, I.ID, I.PARENT_ID, I.NAME, I.VERSION, I.I_INDEX, I.N_ORDER_NUM"
+ " from JCR_SITEM I where I.CONTAINER_NAME=? and I.I_CLASS=1) as A where A.r__ <= ? and A.r__ > ?"
+ ") J on P.PARENT_ID = J.ID"
+ " where P.I_CLASS=2 and P.CONTAINER_NAME=? and V.PROPERTY_ID=P.ID order by J.ID";
}
|
diff --git a/ij/plugin/ClassChecker.java b/ij/plugin/ClassChecker.java
index cd6693f7..22d19b40 100644
--- a/ij/plugin/ClassChecker.java
+++ b/ij/plugin/ClassChecker.java
@@ -1,117 +1,123 @@
package ij.plugin;
import ij.*;
import ij.util.*;
import java.io.*;
import java.util.*;
/** Checks for duplicate class files in the plugins directory and deletes older duplicates. */
public class ClassChecker implements PlugIn {
char separatorChar = Prefs.separator.charAt(0);
public void run(String arg) {
deleteDuplicates();
}
void deleteDuplicates() {
String[] paths = getClassFiles();
if (paths==null)
return;
String name;
File file1, file2;
long date1, date2;
for (int i=0; i<paths.length; i++) {
name = getName(paths[i]);
if (name.endsWith("classx"))
continue;
for (int j=i+1; j<paths.length; j++) {
if (paths[j].endsWith(name)) {
file1 = new File(paths[i]);
file2 = new File(paths[j]);
if (file1==null || file2==null)
continue;
+ try {
+ if (file1.getCanonicalPath().equals(file2.getCanonicalPath()))
+ continue;
+ } catch(Exception e) {
+ continue;
+ }
date1 = file1.lastModified();
date2 = file2.lastModified();
if (date1<date2) {
write(paths[i]);
file1.delete();
break;
} else if (date2<date1) {
write(paths[j]);
paths[j] += "x";
file2.delete();
} else {
if (paths[i].endsWith("plugins"+name)) {
write(paths[i]);
file1.delete();
break;
} else if (paths[j].endsWith("plugins"+name)) {
write(paths[j]);
paths[j] += "x";
file2.delete();
}
}
}
}
}
}
void write(String path) {
IJ.log("Deleting duplicate class: "+path);
}
public String getName(String path) {
int index = path.lastIndexOf(separatorChar);
return (index < 0) ? path : path.substring(index);
}
/** Returns a list of all the class files in the plugins
folder and subfolders of the plugins folder. */
String[] getClassFiles() {
String path = Menus.getPlugInsPath();
if (path==null)
return null;
File f = new File(path);
String[] list = f.list();
if (list==null) return null;
Vector v = new Vector();
for (int i=0; i<list.length; i++) {
String name = list[i];
boolean isClassFile = name.endsWith(".class");
if (isClassFile) {
//className = className.substring(0, className.length()-6);
v.addElement(path+name);
} else {
if (!isClassFile)
getSubdirectoryClassFiles(path, name, v);
}
}
list = new String[v.size()];
v.copyInto((String[])list);
return list;
}
/** Looks for class files in a subfolders of the plugins folder. */
void getSubdirectoryClassFiles(String path, String dir, Vector v) {
//IJ.write("getSubdirectoryClassFiles: "+path+dir);
if (dir.endsWith(".java"))
return;
File f = new File(path, dir);
if (!f.isDirectory())
return;
String[] list = f.list();
if (list==null)
return;
dir += Prefs.separator;
for (int i=0; i<list.length; i++) {
String name = list[i];
if (name.endsWith(".class")) {
//name = name.substring(0, name.length()-6); // remove ".class"
v.addElement(path+dir+name);
//IJ.write("File: "+f+"/"+name);
}
}
}
}
| true | true | void deleteDuplicates() {
String[] paths = getClassFiles();
if (paths==null)
return;
String name;
File file1, file2;
long date1, date2;
for (int i=0; i<paths.length; i++) {
name = getName(paths[i]);
if (name.endsWith("classx"))
continue;
for (int j=i+1; j<paths.length; j++) {
if (paths[j].endsWith(name)) {
file1 = new File(paths[i]);
file2 = new File(paths[j]);
if (file1==null || file2==null)
continue;
date1 = file1.lastModified();
date2 = file2.lastModified();
if (date1<date2) {
write(paths[i]);
file1.delete();
break;
} else if (date2<date1) {
write(paths[j]);
paths[j] += "x";
file2.delete();
} else {
if (paths[i].endsWith("plugins"+name)) {
write(paths[i]);
file1.delete();
break;
} else if (paths[j].endsWith("plugins"+name)) {
write(paths[j]);
paths[j] += "x";
file2.delete();
}
}
}
}
}
}
| void deleteDuplicates() {
String[] paths = getClassFiles();
if (paths==null)
return;
String name;
File file1, file2;
long date1, date2;
for (int i=0; i<paths.length; i++) {
name = getName(paths[i]);
if (name.endsWith("classx"))
continue;
for (int j=i+1; j<paths.length; j++) {
if (paths[j].endsWith(name)) {
file1 = new File(paths[i]);
file2 = new File(paths[j]);
if (file1==null || file2==null)
continue;
try {
if (file1.getCanonicalPath().equals(file2.getCanonicalPath()))
continue;
} catch(Exception e) {
continue;
}
date1 = file1.lastModified();
date2 = file2.lastModified();
if (date1<date2) {
write(paths[i]);
file1.delete();
break;
} else if (date2<date1) {
write(paths[j]);
paths[j] += "x";
file2.delete();
} else {
if (paths[i].endsWith("plugins"+name)) {
write(paths[i]);
file1.delete();
break;
} else if (paths[j].endsWith("plugins"+name)) {
write(paths[j]);
paths[j] += "x";
file2.delete();
}
}
}
}
}
}
|
diff --git a/source/core/src/main/java/org/marketcetera/spring/JMSFIXMessageConverter.java b/source/core/src/main/java/org/marketcetera/spring/JMSFIXMessageConverter.java
index f5eb880df..06665e019 100755
--- a/source/core/src/main/java/org/marketcetera/spring/JMSFIXMessageConverter.java
+++ b/source/core/src/main/java/org/marketcetera/spring/JMSFIXMessageConverter.java
@@ -1,84 +1,88 @@
package org.marketcetera.spring;
import java.io.Serializable;
import javax.jms.BytesMessage;
import javax.jms.ObjectMessage;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.marketcetera.core.LoggerAdapter;
import org.marketcetera.core.MessageKey;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import quickfix.InvalidMessage;
public class JMSFIXMessageConverter implements MessageConverter {
private static final String FIX_PREAMBLE = "8=FIX";
boolean serializeToString = true;
public static final String BYTES_MESSAGE_CHARSET = "UTF-16";
public JMSFIXMessageConverter() {
}
public boolean isSerializeToString() {
return serializeToString;
}
public void setSerializeToString(boolean serializeToString) {
this.serializeToString = serializeToString;
}
public Object fromMessage(Message message) throws JMSException, MessageConversionException {
quickfix.Message qfMessage = null;
if(message instanceof TextMessage) {
if(LoggerAdapter.isDebugEnabled(this)) {
LoggerAdapter.debug("Received JMS msg: "+message, this);
}
// todo: handle validation when creating quickfix message
try {
qfMessage = new quickfix.Message(((TextMessage)message).getText());
- } catch (InvalidMessage e) {
- throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), e);
+ } catch (InvalidMessage e) {
+ // bug #501 - want to log here
+ LoggerAdapter.error(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage()+": "+e.getMessage(), this);
+ throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), e);
}
} else if (message instanceof BytesMessage){
LoggerAdapter.debug("Received JMS msg: "+message, this);
try {
BytesMessage bytesMessage = ((BytesMessage)message);
int length = (int)bytesMessage.getBodyLength();
byte [] buf = new byte[length];
bytesMessage.readBytes(buf);
String possibleString = new String(buf, BYTES_MESSAGE_CHARSET);
if (possibleString.startsWith(FIX_PREAMBLE)){
qfMessage = new quickfix.Message(possibleString);
}
} catch (Exception ex){
+ // bug #501 - want to log here
+ LoggerAdapter.error(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage()+": "+ex.getMessage(), this);
throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), ex);
}
} else if (message instanceof ObjectMessage) {
return (quickfix.Message)((ObjectMessage)message).getObject();
}
return qfMessage;
}
/** Converts from the OMS to the JMS queue format - ie from a FIX Message -> JMS message */
public Message toMessage(Object message, Session session) throws JMSException, MessageConversionException {
javax.jms.Message jmsMessage = null;
if (serializeToString){
jmsMessage = session.createTextMessage(message.toString());
} else if (message instanceof Serializable) {
Serializable serializable = (Serializable) message;
jmsMessage = session.createObjectMessage(serializable);
}
return jmsMessage;
}
}
| false | true | public Object fromMessage(Message message) throws JMSException, MessageConversionException {
quickfix.Message qfMessage = null;
if(message instanceof TextMessage) {
if(LoggerAdapter.isDebugEnabled(this)) {
LoggerAdapter.debug("Received JMS msg: "+message, this);
}
// todo: handle validation when creating quickfix message
try {
qfMessage = new quickfix.Message(((TextMessage)message).getText());
} catch (InvalidMessage e) {
throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), e);
}
} else if (message instanceof BytesMessage){
LoggerAdapter.debug("Received JMS msg: "+message, this);
try {
BytesMessage bytesMessage = ((BytesMessage)message);
int length = (int)bytesMessage.getBodyLength();
byte [] buf = new byte[length];
bytesMessage.readBytes(buf);
String possibleString = new String(buf, BYTES_MESSAGE_CHARSET);
if (possibleString.startsWith(FIX_PREAMBLE)){
qfMessage = new quickfix.Message(possibleString);
}
} catch (Exception ex){
throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), ex);
}
} else if (message instanceof ObjectMessage) {
return (quickfix.Message)((ObjectMessage)message).getObject();
}
return qfMessage;
}
| public Object fromMessage(Message message) throws JMSException, MessageConversionException {
quickfix.Message qfMessage = null;
if(message instanceof TextMessage) {
if(LoggerAdapter.isDebugEnabled(this)) {
LoggerAdapter.debug("Received JMS msg: "+message, this);
}
// todo: handle validation when creating quickfix message
try {
qfMessage = new quickfix.Message(((TextMessage)message).getText());
} catch (InvalidMessage e) {
// bug #501 - want to log here
LoggerAdapter.error(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage()+": "+e.getMessage(), this);
throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), e);
}
} else if (message instanceof BytesMessage){
LoggerAdapter.debug("Received JMS msg: "+message, this);
try {
BytesMessage bytesMessage = ((BytesMessage)message);
int length = (int)bytesMessage.getBodyLength();
byte [] buf = new byte[length];
bytesMessage.readBytes(buf);
String possibleString = new String(buf, BYTES_MESSAGE_CHARSET);
if (possibleString.startsWith(FIX_PREAMBLE)){
qfMessage = new quickfix.Message(possibleString);
}
} catch (Exception ex){
// bug #501 - want to log here
LoggerAdapter.error(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage()+": "+ex.getMessage(), this);
throw new MessageConversionException(MessageKey.ERR0R_JMS_MESSAGE_CONVERSION.getLocalizedMessage(), ex);
}
} else if (message instanceof ObjectMessage) {
return (quickfix.Message)((ObjectMessage)message).getObject();
}
return qfMessage;
}
|
diff --git a/platform/com.subgraph.vega.ui.http/src/com/subgraph/vega/ui/http/preferencepage/HTTPPreferenceInitializer.java b/platform/com.subgraph.vega.ui.http/src/com/subgraph/vega/ui/http/preferencepage/HTTPPreferenceInitializer.java
index 19dcdf97..6b35a530 100644
--- a/platform/com.subgraph.vega.ui.http/src/com/subgraph/vega/ui/http/preferencepage/HTTPPreferenceInitializer.java
+++ b/platform/com.subgraph.vega.ui.http/src/com/subgraph/vega/ui/http/preferencepage/HTTPPreferenceInitializer.java
@@ -1,23 +1,23 @@
package com.subgraph.vega.ui.http.preferencepage;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.subgraph.vega.ui.http.Activator;
public class HTTPPreferenceInitializer extends AbstractPreferenceInitializer {
public HTTPPreferenceInitializer() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_PROXY_PORT, 8888);
- store.setDefault(PreferenceConstants.P_USER_AGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Vega/1.0");
+ store.setDefault(PreferenceConstants.P_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Vega/1.0");
store.setDefault(PreferenceConstants.P_USER_AGENT_OVERRIDE, false);
store.setDefault(PreferenceConstants.P_DISABLE_BROWSER_CACHE, false);
store.setDefault(PreferenceConstants.P_DISABLE_PROXY_CACHE, false);
}
@Override
public void initializeDefaultPreferences() {
}
}
| true | true | public HTTPPreferenceInitializer() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_PROXY_PORT, 8888);
store.setDefault(PreferenceConstants.P_USER_AGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Vega/1.0");
store.setDefault(PreferenceConstants.P_USER_AGENT_OVERRIDE, false);
store.setDefault(PreferenceConstants.P_DISABLE_BROWSER_CACHE, false);
store.setDefault(PreferenceConstants.P_DISABLE_PROXY_CACHE, false);
}
| public HTTPPreferenceInitializer() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_PROXY_PORT, 8888);
store.setDefault(PreferenceConstants.P_USER_AGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; Vega/1.0");
store.setDefault(PreferenceConstants.P_USER_AGENT_OVERRIDE, false);
store.setDefault(PreferenceConstants.P_DISABLE_BROWSER_CACHE, false);
store.setDefault(PreferenceConstants.P_DISABLE_PROXY_CACHE, false);
}
|
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
index 43a8d051..8cc26aee 100644
--- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
+++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/VermessungRissEditor.java
@@ -1,2706 +1,2706 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
package de.cismet.cids.custom.objecteditors.wunda_blau;
import Sirius.navigator.connection.SessionManager;
import Sirius.navigator.ui.ComponentRegistry;
import Sirius.navigator.ui.RequestsFullSizeComponent;
import Sirius.server.middleware.types.MetaObject;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import org.apache.log4j.Logger;
import org.openide.util.NbBundle;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.swing.DefaultListModel;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import de.cismet.cids.client.tools.DevelopmentTools;
import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport;
import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils;
import de.cismet.cids.custom.utils.alkis.AlkisConstants;
import de.cismet.cids.dynamics.CidsBean;
import de.cismet.cids.dynamics.DisposableCidsBeanStore;
import de.cismet.cids.editors.DefaultBindableReferenceCombo;
import de.cismet.cids.editors.DefaultCustomObjectEditor;
import de.cismet.cids.editors.EditorClosedEvent;
import de.cismet.cids.editors.EditorSaveListener;
import de.cismet.cids.editors.converters.SqlDateToStringConverter;
import de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor;
import de.cismet.cismap.commons.Crs;
import de.cismet.cismap.commons.CrsTransformer;
import de.cismet.cismap.commons.XBoundingBox;
import de.cismet.cismap.commons.gui.measuring.MeasuringComponent;
import de.cismet.security.WebAccessManager;
import de.cismet.tools.CismetThreadPool;
import de.cismet.tools.gui.BorderProvider;
import de.cismet.tools.gui.FooterComponentProvider;
import de.cismet.tools.gui.MultiPagePictureReader;
import de.cismet.tools.gui.StaticSwingTools;
import de.cismet.tools.gui.TitleComponentProvider;
import de.cismet.tools.gui.downloadmanager.DownloadManager;
import de.cismet.tools.gui.downloadmanager.DownloadManagerDialog;
import de.cismet.tools.gui.downloadmanager.HttpDownload;
/**
* DOCUMENT ME!
*
* @author jweintraut
* @version $Revision$, $Date$
*/
public class VermessungRissEditor extends javax.swing.JPanel implements DisposableCidsBeanStore,
TitleComponentProvider,
FooterComponentProvider,
BorderProvider,
RequestsFullSizeComponent,
EditorSaveListener {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(VermessungRissEditor.class);
public static final String[] SUFFIXES = new String[] { "tif", "jpg", "tiff", "jpeg", "TIF", "JPG", "TIFF", "JPEG" };
protected static final int DOCUMENT_BILD = 0;
protected static final int DOCUMENT_GRENZNIEDERSCHRIFT = 1;
protected static final int NO_SELECTION = -1;
protected static final ListModel MODEL_LOAD = new DefaultListModel() {
{
add(0, "Wird geladen...");
}
};
protected static XBoundingBox INITIAL_BOUNDINGBOX = new XBoundingBox(
2583621.251964098d,
5682507.032498134d,
2584022.9413952776d,
5682742.852810634d,
AlkisConstants.COMMONS.SRS_SERVICE,
true);
protected static Crs CRS = new Crs(
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
AlkisConstants.COMMONS.SRS_SERVICE,
true,
true);
protected static final GeometryFactory GEOMETRY_FACTORY = new GeometryFactory(new PrecisionModel(
PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(AlkisConstants.COMMONS.SRS_SERVICE));
protected static final Map<Integer, Color> COLORS_GEOMETRIE_STATUS = new HashMap<Integer, Color>();
static {
COLORS_GEOMETRIE_STATUS.put(new Integer(1), Color.green);
COLORS_GEOMETRIE_STATUS.put(new Integer(2), Color.yellow);
COLORS_GEOMETRIE_STATUS.put(new Integer(3), Color.yellow);
COLORS_GEOMETRIE_STATUS.put(new Integer(4), Color.red);
COLORS_GEOMETRIE_STATUS.put(new Integer(5), Color.red);
}
//~ Instance fields --------------------------------------------------------
protected CidsBean cidsBean;
protected boolean readOnly;
// When Wupp decides to publish the correspoding files on a WebDAV server, switch documentURLs' type to URL[].
protected URL[] documentURLs;
protected JToggleButton[] documentButtons;
protected JToggleButton currentSelectedButton;
protected PictureSelectWorker currentPictureSelectWorker = null;
protected MultiPagePictureReader pictureReader;
protected VermessungFlurstueckSelectionDialog flurstueckDialog;
protected volatile int currentDocument = NO_SELECTION;
protected volatile int currentPage = NO_SELECTION;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup bgrControls;
private javax.swing.ButtonGroup bgrDocument;
private javax.swing.JButton btnAddLandparcel;
private javax.swing.JButton btnCombineGeometries;
private javax.swing.JButton btnHome;
private javax.swing.JButton btnOpen;
private javax.swing.JButton btnRemoveLandparcel;
private javax.swing.JComboBox cmbFormat;
private javax.swing.JComboBox cmbGemarkung;
private javax.swing.JComboBox cmbGeometrie;
private javax.swing.JComboBox cmbGeometrieStatus;
private javax.swing.JComboBox cmbSchluessel;
private javax.swing.Box.Filler gluGapControls;
private javax.swing.Box.Filler gluGeneralInformationGap;
private javax.swing.JLabel lblBlatt;
private javax.swing.JLabel lblErrorWhileLoadingBild;
private javax.swing.JLabel lblErrorWhileLoadingGrenzniederschrift;
private javax.swing.JLabel lblFlur;
private javax.swing.JLabel lblFormat;
private javax.swing.JLabel lblGemarkung;
private javax.swing.JLabel lblGeneralInformation;
private javax.swing.JLabel lblGeometrie;
private javax.swing.JLabel lblGeometrieStatus;
private javax.swing.JLabel lblHeaderControls;
private javax.swing.JLabel lblHeaderDocument;
private javax.swing.JLabel lblHeaderDocuments;
private javax.swing.JLabel lblHeaderLandparcels;
private javax.swing.JLabel lblHeaderPages;
private javax.swing.JLabel lblJahr;
private javax.swing.JLabel lblKennziffer;
private javax.swing.JLabel lblLetzteAenderungDatum;
private javax.swing.JLabel lblLetzteAenderungName;
private javax.swing.JLabel lblMissingDocuments;
private javax.swing.JLabel lblSchluessel;
private javax.swing.JLabel lblTitle;
private javax.swing.JList lstLandparcels;
private javax.swing.JList lstPages;
private de.cismet.cismap.commons.gui.measuring.MeasuringComponent measuringComponent;
private javax.swing.JPanel pnlContainer;
private de.cismet.tools.gui.RoundedPanel pnlControls;
private de.cismet.tools.gui.RoundedPanel pnlDocument;
private de.cismet.tools.gui.RoundedPanel pnlDocuments;
private de.cismet.tools.gui.RoundedPanel pnlGeneralInformation;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderControls;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderDocument;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderDocuments;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderGeneralInformation;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderLandparcels;
private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderPages;
private de.cismet.tools.gui.RoundedPanel pnlLandparcels;
private de.cismet.tools.gui.RoundedPanel pnlPages;
private javax.swing.JPanel pnlTitle;
private javax.swing.JScrollPane scpLandparcels;
private javax.swing.JScrollPane scpPages;
private javax.swing.Box.Filler strFooter;
private javax.swing.JToggleButton togBild;
private javax.swing.JToggleButton togGrenzniederschrift;
private javax.swing.JToggleButton togPan;
private javax.swing.JToggleButton togZoom;
private javax.swing.JTextField txtBlatt;
private javax.swing.JTextField txtFlur;
private javax.swing.JTextField txtJahr;
private javax.swing.JTextField txtKennziffer;
private javax.swing.JTextField txtLetzteaenderungDatum;
private javax.swing.JTextField txtLetzteaenderungName;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration//GEN-END:variables
//~ Constructors -----------------------------------------------------------
/**
* Creates a new VermessungRissEditor object.
*/
public VermessungRissEditor() {
this(false);
}
/**
* Creates new form VermessungRissEditor.
*
* @param readOnly DOCUMENT ME!
*/
public VermessungRissEditor(final boolean readOnly) {
this.readOnly = readOnly;
documentURLs = new URL[2];
documentButtons = new JToggleButton[documentURLs.length];
initComponents();
documentButtons[DOCUMENT_BILD] = togBild;
documentButtons[DOCUMENT_GRENZNIEDERSCHRIFT] = togGrenzniederschrift;
if (readOnly) {
lblSchluessel.setVisible(false);
cmbSchluessel.setVisible(false);
lblGemarkung.setVisible(false);
cmbGemarkung.setVisible(false);
lblFlur.setVisible(false);
txtFlur.setVisible(false);
lblBlatt.setVisible(false);
txtBlatt.setVisible(false);
txtJahr.setEditable(false);
txtKennziffer.setEditable(false);
cmbFormat.setEditable(false);
cmbFormat.setEnabled(false);
cmbGeometrieStatus.setEditable(false);
cmbGeometrieStatus.setEnabled(false);
lblGeometrie.setVisible(false);
btnAddLandparcel.setVisible(false);
btnRemoveLandparcel.setVisible(false);
btnCombineGeometries.setVisible(false);
} else {
flurstueckDialog = new VermessungFlurstueckSelectionDialog();
flurstueckDialog.pack();
flurstueckDialog.setLocationRelativeTo(this);
flurstueckDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
flurstueckDialog.addWindowListener(new EnableCombineGeometriesButton());
if (txtBlatt.getDocument() instanceof AbstractDocument) {
((AbstractDocument)txtBlatt.getDocument()).setDocumentFilter(new DocumentSizeFilter());
}
if (txtFlur.getDocument() instanceof AbstractDocument) {
((AbstractDocument)txtFlur.getDocument()).setDocumentFilter(new DocumentSizeFilter());
}
}
}
//~ Methods ----------------------------------------------------------------
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblKennziffer = new javax.swing.JLabel();
txtKennziffer = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblKennziffer.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblKennziffer.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblKennziffer, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kennziffer}"),
txtKennziffer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtKennziffer, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
- togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(120, 32));
- togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(120, 32));
- togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(120, 32));
+ togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(150, 32));
+ togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(150, 32));
+ togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togPanActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togPanActionPerformed
measuringComponent.actionPan();
} //GEN-LAST:event_togPanActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togZoomActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togZoomActionPerformed
measuringComponent.actionZoom();
} //GEN-LAST:event_togZoomActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnHomeActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnHomeActionPerformed
measuringComponent.actionOverview();
} //GEN-LAST:event_btnHomeActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnOpenActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnOpenActionPerformed
if (currentDocument != NO_SELECTION) {
CismetThreadPool.execute(new Runnable() {
@Override
public void run() {
if (DownloadManagerDialog.showAskingForUserTitle(VermessungRissEditor.this)) {
final String url = documentURLs[currentDocument].toExternalForm();
final String filename = url.substring(url.lastIndexOf("/") + 1);
DownloadManager.instance()
.add(
new HttpDownload(
documentURLs[currentDocument],
"",
DownloadManagerDialog.getJobname(),
(currentDocument == DOCUMENT_BILD) ? "Vermessungsriss"
: "Grenzniederschrift",
filename.substring(0, filename.lastIndexOf(".")),
filename.substring(filename.lastIndexOf("."))));
}
}
});
}
} //GEN-LAST:event_btnOpenActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstLandparcelsMouseClicked(final java.awt.event.MouseEvent evt) { //GEN-FIRST:event_lstLandparcelsMouseClicked
if (evt.getClickCount() <= 1) {
return;
}
final Object selectedObj = lstLandparcels.getSelectedValue();
if (selectedObj instanceof CidsBean) {
final CidsBean selectedBean = (CidsBean)selectedObj;
if ((selectedBean.getProperty("flurstueck") instanceof CidsBean)
&& (selectedBean.getProperty("flurstueck.flurstueck") instanceof CidsBean)) {
final MetaObject selMO = ((CidsBean)selectedBean.getProperty("flurstueck.flurstueck")).getMetaObject();
ComponentRegistry.getRegistry().getDescriptionPane().gotoMetaObject(selMO, "");
}
}
} //GEN-LAST:event_lstLandparcelsMouseClicked
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstPagesValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstPagesValueChanged
if (!evt.getValueIsAdjusting()) {
final Object page = lstPages.getSelectedValue();
if (page instanceof Integer) {
loadPage(((Integer)page) - 1);
}
}
} //GEN-LAST:event_lstPagesValueChanged
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togBildActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togBildActionPerformed
loadBild();
} //GEN-LAST:event_togBildActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void togGrenzniederschriftActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_togGrenzniederschriftActionPerformed
loadGrenzniederschrift();
} //GEN-LAST:event_togGrenzniederschriftActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnAddLandparcelActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddLandparcelActionPerformed
flurstueckDialog.setCurrentListToAdd(CidsBeanSupport.getBeanCollectionFromProperty(
cidsBean,
"flurstuecksvermessung"));
flurstueckDialog.setVisible(true);
} //GEN-LAST:event_btnAddLandparcelActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnRemoveLandparcelActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveLandparcelActionPerformed
final Object[] selection = lstLandparcels.getSelectedValues();
if ((selection != null) && (selection.length > 0)) {
final int answer = JOptionPane.showConfirmDialog(
this,
"Soll das Flurstück wirklich gelöscht werden?",
"Flurstück entfernen",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
final Collection flurstuecke = CidsBeanSupport.getBeanCollectionFromProperty(
cidsBean,
"flurstuecksvermessung");
if (flurstuecke != null) {
for (final Object flurstueckToRemove : selection) {
try {
flurstuecke.remove(flurstueckToRemove);
} catch (Exception e) {
ObjectRendererUtils.showExceptionWindowToUser("Fehler beim Löschen", e, this);
} finally {
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
}
}
}
}
} //GEN-LAST:event_btnRemoveLandparcelActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void lstLandparcelsValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstLandparcelsValueChanged
if (!evt.getValueIsAdjusting()) {
btnRemoveLandparcel.setEnabled(!readOnly && (lstLandparcels.getSelectedIndex() > -1));
}
} //GEN-LAST:event_lstLandparcelsValueChanged
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void btnCombineGeometriesActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnCombineGeometriesActionPerformed
if (cidsBean == null) {
return;
}
Geometry union = null;
final Collection<CidsBean> flurstuecksvermessungen = cidsBean.getBeanCollectionProperty(
"flurstuecksvermessung");
for (final CidsBean flurstuecksvermessung : flurstuecksvermessungen) {
if (flurstuecksvermessung.getProperty("flurstueck.flurstueck.umschreibendes_rechteck.geo_field")
instanceof Geometry) {
final Geometry geometry = (Geometry)flurstuecksvermessung.getProperty(
"flurstueck.flurstueck.umschreibendes_rechteck.geo_field");
final Geometry transformedGeometry = CrsTransformer.transformToGivenCrs(
geometry,
AlkisConstants.COMMONS.SRS_SERVICE);
if (union == null) {
union = transformedGeometry;
} else {
union = union.union(transformedGeometry);
}
}
}
if (union == null) {
LOG.warn("Could not find geometries on given landparcels. Did not attach a new geometry.");
JOptionPane.showMessageDialog(
this,
"Keines der betroffenen Flurstücke weist eine Geometrie auf.",
"Keine Geometrie erstellt",
JOptionPane.WARNING_MESSAGE);
return;
}
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put("geo_field", union);
try {
final CidsBean geomBean = CidsBeanSupport.createNewCidsBeanFromTableName("geom", properties);
geomBean.persist();
cidsBean.setProperty("geometrie", geomBean);
} catch (Exception ex) {
// TODO: Tell user about error.
LOG.error("Could set new geometry: '" + union.toText() + "'.", ex);
}
} //GEN-LAST:event_btnCombineGeometriesActionPerformed
/**
* DOCUMENT ME!
*
* @param evt DOCUMENT ME!
*/
private void cmbGeometrieStatusActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_cmbGeometrieStatusActionPerformed
if (cmbGeometrieStatus.getSelectedItem() instanceof CidsBean) {
final CidsBean geometrieStatus = (CidsBean)cmbGeometrieStatus.getSelectedItem();
if (geometrieStatus.getProperty("id") instanceof Integer) {
cmbGeometrieStatus.setBackground(COLORS_GEOMETRIE_STATUS.get(
(Integer)geometrieStatus.getProperty("id")));
}
}
} //GEN-LAST:event_cmbGeometrieStatusActionPerformed
@Override
public CidsBean getCidsBean() {
return cidsBean;
}
@Override
public void setCidsBean(final CidsBean cidsBean) {
bindingGroup.unbind();
if (cidsBean != null) {
this.cidsBean = cidsBean;
DefaultCustomObjectEditor.setMetaClassInformationToMetaClassStoreComponentsInBindingGroup(
bindingGroup,
this.cidsBean);
bindingGroup.bind();
lblTitle.setText(generateTitle());
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
if ((cidsBean.getProperty("geometrie_status") instanceof CidsBean)
&& (cidsBean.getProperty("geometrie_status.id") instanceof Integer)) {
cmbGeometrieStatus.setBackground(COLORS_GEOMETRIE_STATUS.get(
(Integer)cidsBean.getProperty("geometrie_status.id")));
}
// TODO: Add a propertyChangeListener to CidsBean which reacts on changes to 'bild' or 'grenzniederschrift'?
}
setCurrentDocumentNull();
// CismetThreadPool.execute(new RefreshDocumentWorker());
EventQueue.invokeLater(new RefreshDocumentWorker());
}
@Override
public void dispose() {
bindingGroup.unbind();
// dispose panels here if necessary
measuringComponent.dispose();
if (flurstueckDialog != null) {
flurstueckDialog.dispose();
}
if (!readOnly) {
((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).dispose();
}
}
@Override
public JComponent getTitleComponent() {
return pnlTitle;
}
@Override
public JComponent getFooterComponent() {
return strFooter;
}
@Override
public Border getTitleBorder() {
return new EmptyBorder(10, 10, 10, 10);
}
@Override
public Border getFooterBorder() {
return new EmptyBorder(5, 5, 5, 5);
}
@Override
public Border getCenterrBorder() {
return new EmptyBorder(0, 5, 0, 5);
}
@Override
public void editorClosed(final EditorClosedEvent event) {
}
@Override
public boolean prepareForSave() {
boolean save = true;
final StringBuilder errorMessage = new StringBuilder();
if (cmbSchluessel.getSelectedItem() == null) {
LOG.warn("No 'schluessel' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noSchluessel"));
}
if (cmbGemarkung.getSelectedItem() == null) {
LOG.warn("No 'gemarkung' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noGemarkung"));
}
if ((txtFlur.getText() == null) || txtFlur.getText().trim().isEmpty()) {
LOG.warn("No 'flur' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noFlur"));
} else if (txtFlur.getText().length() > 31) {
LOG.warn("Property 'flur' is too long. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().tooLongFlur"));
}
if ((txtBlatt.getText() == null) || txtBlatt.getText().trim().isEmpty()) {
LOG.warn("No 'blatt' specified. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().noBlatt"));
} else if (txtBlatt.getText().length() > 31) {
LOG.warn("Property 'blatt' is too long. Skip persisting.");
errorMessage.append(NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().tooLongBlatt"));
}
if (errorMessage.length() > 0) {
save = false;
JOptionPane.showMessageDialog(
this,
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.message.prefix")
+ errorMessage.toString()
+ NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.message.suffix"),
NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.prepareForSave().JOptionPane.title"),
JOptionPane.WARNING_MESSAGE);
}
try {
cidsBean.setProperty("letzteaenderung_datum", new Date(System.currentTimeMillis()));
cidsBean.setProperty("letzteaenderung_name", SessionManager.getSession().getUser().getName());
} catch (Exception ex) {
// TODO: Tell user?
LOG.warn("Could not save date and user of last change.", ex);
}
return save;
}
/**
* DOCUMENT ME!
*
* @param host prefix DOCUMENT ME!
* @param gemarkung DOCUMENT ME!
* @param flur DOCUMENT ME!
* @param schluessel DOCUMENT ME!
* @param blatt DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public static Collection<URL> getCorrespondingURLs(final String host,
final Integer gemarkung,
final String flur,
final String schluessel,
final String blatt) {
final Collection<URL> validURLs = new LinkedList<URL>();
final String urlString;
try {
urlString = MessageFormat.format(host, schluessel, gemarkung, flur, new Integer(Integer.parseInt(blatt)))
+ '.';
} catch (final Exception ex) {
LOG.warn("Can't build a valid URL for current measurement sketch.", ex);
return validURLs;
}
for (final String suffix : SUFFIXES) {
URL urlToTry = null;
try {
urlToTry = new URL(urlString + suffix);
} catch (MalformedURLException ex) {
LOG.warn("The URL '" + urlString.toString() + suffix
+ "' is malformed. Can't load the corresponding picture.",
ex);
}
if (urlToTry != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Valid URL: " + urlToTry.toExternalForm());
}
validURLs.add(urlToTry);
}
}
return validURLs;
}
/**
* DOCUMENT ME!
*
* @param property host DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
// public static Collection<File> getCorrespondingFiles(final String host, final String path) {
// final Collection<File> validFiles = new LinkedList<File>();
//
// final StringBuilder urlBuilder = new StringBuilder(host);
// urlBuilder.append('/');
// urlBuilder.append(path);
// urlBuilder.append('.');
//
// for (final String suffix : SUFFIXES) {
// final URL fileURL;
// final File testFile;
// try {
// fileURL = new URL(urlBuilder.toString() + suffix);
// testFile = new File(fileURL.toURI());
//
// if (testFile.isFile()) {
// if (LOG.isDebugEnabled()) {
// LOG.debug("Found picture in file: " + testFile.getAbsolutePath());
// }
//
// validFiles.add(testFile);
// }
// } catch (MalformedURLException ex) {
// LOG.warn("Could not create URL object for '" + urlBuilder.toString() + suffix + "'.", ex);
// } catch (URISyntaxException ex) {
// LOG.warn("Could not create File object for '" + urlBuilder.toString() + suffix + "'.", ex);
// }
// }
//
// return validFiles;
// }
/**
* DOCUMENT ME!
*
* @param property DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String getSimplePropertyOfCurrentCidsBean(final String property) {
String result = "";
if (cidsBean != null) {
if (cidsBean.getProperty(property) != null) {
result = (String)cidsBean.getProperty(property).toString();
}
}
return result;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected String generateTitle() {
if (cidsBean == null) {
return "Bitte wählen Sie einen Vermessungsriss.";
}
final StringBuilder result = new StringBuilder();
final Object schluessel = cidsBean.getProperty("schluessel");
final Object flur = cidsBean.getProperty("flur");
final Object blatt = cidsBean.getProperty("blatt");
result.append("Schlüssel ");
if ((schluessel instanceof String) && (((String)schluessel).trim().length() > 0)) {
result.append(schluessel);
} else {
result.append("unbekannt");
}
result.append(" - ");
result.append("Gemarkung ");
String gemarkung = "unbekannt";
if ((cidsBean.getProperty("gemarkung") instanceof CidsBean)
&& (cidsBean.getProperty("gemarkung.name") instanceof String)) {
final String gemarkungFromBean = (String)cidsBean.getProperty("gemarkung.name");
if (gemarkungFromBean.trim().length() > 0) {
gemarkung = gemarkungFromBean;
}
}
result.append(gemarkung);
result.append(" - ");
result.append("Flur ");
if ((flur instanceof String) && (((String)flur).trim().length() > 0)) {
result.append(flur);
} else {
result.append("unbekannt");
}
result.append(" - ");
result.append("Blatt ");
if ((blatt instanceof String) && (((String)blatt).trim().length() > 0)) {
result.append(blatt);
} else {
result.append("unbekannt");
}
return result.toString();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
protected Integer getGemarkungOfCurrentCidsBean() {
Integer result = Integer.valueOf(-1);
if (cidsBean != null) {
if (cidsBean.getProperty("gemarkung") != null) {
final Object gemarkung = cidsBean.getProperty("gemarkung.id");
if (gemarkung instanceof Integer) {
result = (Integer)gemarkung;
}
}
}
return result;
}
/**
* DOCUMENT ME!
*/
protected void loadBild() {
currentSelectedButton = togBild;
lblHeaderDocument.setText("Bild");
currentDocument = DOCUMENT_BILD;
CismetThreadPool.execute(new PictureReaderWorker(documentURLs[currentDocument]));
}
/**
* DOCUMENT ME!
*/
protected void loadGrenzniederschrift() {
currentSelectedButton = togGrenzniederschrift;
lblHeaderDocument.setText("Grenzniederschrift");
currentDocument = DOCUMENT_GRENZNIEDERSCHRIFT;
// CismetThreadPool.execute(new PictureReaderWorker(documentURLs[currentDocument]));
EventQueue.invokeLater(new PictureReaderWorker(documentURLs[currentDocument]));
}
/**
* DOCUMENT ME!
*
* @param page DOCUMENT ME!
*/
protected void loadPage(final int page) {
final PictureSelectWorker oldWorkerTest = currentPictureSelectWorker;
if (oldWorkerTest != null) {
oldWorkerTest.cancel(true);
}
currentPictureSelectWorker = new PictureSelectWorker(page);
// CismetThreadPool.execute(currentPictureSelectWorker);
EventQueue.invokeLater(currentPictureSelectWorker);
}
/**
* DOCUMENT ME!
*/
protected void setCurrentDocumentNull() {
currentDocument = NO_SELECTION;
setCurrentPageNull();
}
/**
* DOCUMENT ME!
*/
protected void setCurrentPageNull() {
currentPage = NO_SELECTION;
}
/**
* DOCUMENT ME!
*
* @param enabled DOCUMENT ME!
*/
protected void setDocumentControlsEnabled(final boolean enabled) {
for (int i = 0; i < documentURLs.length; i++) {
final JToggleButton current = documentButtons[i];
current.setEnabled((documentURLs[i] != null) && enabled);
}
}
/**
* DOCUMENT ME!
*
* @param errorOccurred DOCUMENT ME!
*/
protected void displayErrorOrEnableControls(final boolean errorOccurred) {
measuringComponent.setVisible(!errorOccurred);
btnHome.setEnabled(!errorOccurred);
btnOpen.setEnabled(!errorOccurred);
togPan.setEnabled(!errorOccurred);
togZoom.setEnabled(!errorOccurred);
lstPages.setEnabled(!errorOccurred);
lblMissingDocuments.setVisible(false);
lblErrorWhileLoadingBild.setVisible(false);
lblErrorWhileLoadingGrenzniederschrift.setVisible(false);
if (errorOccurred) {
lstPages.setModel(new DefaultListModel());
if (currentDocument == DOCUMENT_BILD) {
lblErrorWhileLoadingBild.setVisible(true);
} else if (currentDocument == DOCUMENT_GRENZNIEDERSCHRIFT) {
lblErrorWhileLoadingGrenzniederschrift.setVisible(true);
} else {
lblMissingDocuments.setVisible(true);
}
}
}
/**
* DOCUMENT ME!
*/
protected void closeReader() {
if (pictureReader != null) {
pictureReader.close();
pictureReader = null;
}
}
/**
* DOCUMENT ME!
*
* @param args DOCUMENT ME!
*
* @throws Exception DOCUMENT ME!
*/
public static void main(final String[] args) throws Exception {
// final CidsBean riss = DevelopmentTools.createCidsBeanFromRMIConnectionOnLocalhost(
// "WUNDA_BLAU",
// "Administratoren",
// "admin",
// "sb",
// "vermessung_riss",
//// 27
// 26);
//
// final Collection<CidsBean> geometryBeans = new LinkedList<CidsBean>();
// final Collection<CidsBean> flurstuecksvermessungen = riss.getBeanCollectionProperty("flurstuecksvermessung");
// for (final CidsBean flurstuecksvermessung : flurstuecksvermessungen) {
// System.out.println("Has Flurstuecksvermessung '" + flurstuecksvermessung.getProperty("id").toString()
// + "' a geometry? "
// + (flurstuecksvermessung.getProperty("flurstueck.flurstueck.umschreibendes_rechteck.geo_field")
// instanceof Geometry));
// }
DevelopmentTools.createEditorInFrameFromRMIConnectionOnLocalhost(
"WUNDA_BLAU",
"Administratoren",
"admin",
"sb",
"vermessung_riss",
// 27,
// 26,
4,
// 985,
// 6833,
1024,
768);
// DevelopmentTools.createRendererInFrameFromRMIConnectionOnLocalhost(
// "WUNDA_BLAU",
// "Administratoren",
// "admin",
// "sb",
// "nivellement_punkt",
// 4349,
// "Renderer",
// 1024,
// 768);
}
//~ Inner Classes ----------------------------------------------------------
//J-
//When Wupp decides to publish the correspoding files on a WebDAV server, use following three classes.
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class PictureReaderWorker extends SwingWorker<ListModel, Void> {
//~ Instance fields ----------------------------------------------------
private final URL url;
//~ Constructors -------------------------------------------------------
/**
* Creates a new PictureReaderWorker object.
*
* @param url DOCUMENT ME!
*/
public PictureReaderWorker(final URL url) {
this.url = url;
if (LOG.isDebugEnabled()) {
LOG.debug("Preparing picture reader for file " + this.url.toExternalForm());
}
lstPages.setModel(MODEL_LOAD);
measuringComponent.removeAllFeatures();
setDocumentControlsEnabled(false);
}
//~ Methods ------------------------------------------------------------
@Override
protected ListModel doInBackground() throws Exception {
final DefaultListModel model = new DefaultListModel();
closeReader();
try {
pictureReader = new MultiPagePictureReader(url);
} catch (Exception e) {
LOG.error("Could not create a MultiPagePictureReader for URL '" + url.toExternalForm() + "'.", e);
return model;
}
final int numberOfPages = pictureReader.getNumberOfPages();
for (int i = 0; i < numberOfPages; ++i) {
model.addElement(i + 1);
}
return model;
}
@Override
protected void done() {
boolean enableControls = true;
try {
final ListModel model = get();
lstPages.setModel(model);
if (model.getSize() > 0) {
lstPages.setSelectedIndex(0);
enableControls = false;
} else {
lstPages.setModel(new DefaultListModel());
}
} catch (InterruptedException ex) {
setCurrentDocumentNull();
displayErrorOrEnableControls(true);
closeReader();
LOG.warn("Reading found pictures was interrupted.", ex);
} catch (ExecutionException ex) {
setCurrentDocumentNull();
displayErrorOrEnableControls(true);
closeReader();
LOG.error("Could not read found pictures.", ex);
} finally {
// We don't want to enable the controls if we set the selected index in lstPages. Calling
// lstPages.setSelectedIndex(0)
// invokes a PictureSelectWorker and thus disables the controls.
if (enableControls) {
setDocumentControlsEnabled(true);
}
}
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class PictureSelectWorker extends SwingWorker<BufferedImage, Void> {
//~ Instance fields ----------------------------------------------------
private final int pageNumber;
//~ Constructors -------------------------------------------------------
/**
* Creates a new PictureSelectWorker object.
*
* @param pageNumber DOCUMENT ME!
*/
public PictureSelectWorker(final int pageNumber) {
this.pageNumber = pageNumber;
setCurrentPageNull();
setDocumentControlsEnabled(false);
measuringComponent.reset();
btnHome.setEnabled(false);
btnOpen.setEnabled(false);
togPan.setEnabled(false);
togZoom.setEnabled(false);
lstPages.setEnabled(false);
}
//~ Methods ------------------------------------------------------------
@Override
protected BufferedImage doInBackground() throws Exception {
if (pictureReader != null) {
return pictureReader.loadPage(pageNumber);
}
throw new IllegalStateException("PictureReader is null!");
}
@Override
protected void done() {
try {
if (!isCancelled()) {
currentPage = pageNumber;
measuringComponent.addImage(get());
togPan.setSelected(true);
measuringComponent.zoomToFeatureCollection();
displayErrorOrEnableControls(false);
}
} catch (InterruptedException ex) {
setCurrentPageNull();
displayErrorOrEnableControls(true);
LOG.warn("Was interrupted while setting new image.", ex);
} catch (Exception ex) {
setCurrentPageNull();
displayErrorOrEnableControls(true);
LOG.error("Could not set new image.", ex);
} finally {
setDocumentControlsEnabled(true);
currentPictureSelectWorker = null;
}
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected final class RefreshDocumentWorker extends SwingWorker<Void, Object> {
//~ Constructors -------------------------------------------------------
/**
* Creates a new RefreshDocumentWorker object.
*/
public RefreshDocumentWorker() {
lblMissingDocuments.setVisible(false);
lblErrorWhileLoadingBild.setVisible(false);
lblErrorWhileLoadingGrenzniederschrift.setVisible(false);
togBild.setEnabled(false);
togGrenzniederschrift.setEnabled(false);
lstPages.setModel(MODEL_LOAD);
btnHome.setEnabled(false);
btnOpen.setEnabled(false);
togPan.setEnabled(false);
togZoom.setEnabled(false);
setCurrentDocumentNull();
}
//~ Methods ------------------------------------------------------------
@Override
protected Void doInBackground() throws Exception {
documentURLs[DOCUMENT_BILD] = null;
documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] = null;
final CidsBean cidsBean = getCidsBean();
if (cidsBean == null) {
return null;
}
final Collection<URL> validBildURLs = getCorrespondingURLs(
AlkisConstants.COMMONS.VERMESSUNG_HOST_BILDER,
getGemarkungOfCurrentCidsBean(),
getSimplePropertyOfCurrentCidsBean("flur"),
getSimplePropertyOfCurrentCidsBean("schluessel"),
getSimplePropertyOfCurrentCidsBean("blatt"));
final Collection<URL> validGrenzniederschriftURLs = getCorrespondingURLs(
AlkisConstants.COMMONS.VERMESSUNG_HOST_GRENZNIEDERSCHRIFTEN,
getGemarkungOfCurrentCidsBean(),
getSimplePropertyOfCurrentCidsBean("flur"),
getSimplePropertyOfCurrentCidsBean("schluessel"),
getSimplePropertyOfCurrentCidsBean("blatt"));
InputStream streamToReadFrom = null;
for (final URL url : validBildURLs) {
try {
streamToReadFrom = WebAccessManager.getInstance().doRequest(url);
documentURLs[DOCUMENT_BILD] = url;
break;
} catch (Exception ex) {
LOG.warn("An exception occurred while opening URL '" + url.toExternalForm()
+ "'. Skipping this url.",
ex);
} finally {
if (streamToReadFrom != null) {
streamToReadFrom.close();
}
}
}
streamToReadFrom = null;
for (final URL url : validGrenzniederschriftURLs) {
try {
streamToReadFrom = WebAccessManager.getInstance().doRequest(url);
documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] = url;
break;
} catch (Exception ex) {
LOG.warn("An exception occurred while opening URL '" + url.toExternalForm()
+ "'. Skipping this url.",
ex);
} finally {
if (streamToReadFrom != null) {
streamToReadFrom.close();
}
}
}
return null;
}
@Override
protected void done() {
try {
if (!isCancelled()) {
get();
}
} catch (InterruptedException ex) {
LOG.warn("Was interrupted while refreshing document.", ex);
} catch (ExecutionException ex) {
LOG.warn("There was an exception while refreshing document.", ex);
}
if ((documentURLs[DOCUMENT_BILD] == null) && (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] == null)) {
measuringComponent.setVisible(false);
lblMissingDocuments.setVisible(true);
lstPages.setModel(new DefaultListModel());
lstPages.setEnabled(false);
} else {
if (documentURLs[DOCUMENT_BILD] != null) {
togBild.setEnabled(true);
togBild.setSelected(true);
currentSelectedButton = togBild;
currentDocument = DOCUMENT_BILD;
}
if (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] != null) {
togGrenzniederschrift.setEnabled(true);
if (currentDocument == NO_SELECTION) {
togGrenzniederschrift.setSelected(true);
currentSelectedButton = togGrenzniederschrift;
currentDocument = DOCUMENT_GRENZNIEDERSCHRIFT;
}
}
// CismetThreadPool.execute(new PictureReaderWorker(documentURLs[currentDocument]));
EventQueue.invokeLater(new PictureReaderWorker(documentURLs[currentDocument]));
}
}
}
//J+
//J-
// final class RefreshDocumentWorker extends SwingWorker<Collection[], Void> {
//
// //~ Constructors -------------------------------------------------------
// /**
// * Creates a new FileSearchWorker object.
// */
// public RefreshDocumentWorker() {
// lblMissingDocuments.setVisible(false);
// lblErrorWhileLoadingBild.setVisible(false);
// lblErrorWhileLoadingGrenzniederschrift.setVisible(false);
// togBild.setEnabled(false);
// togGrenzniederschrift.setEnabled(false);
// lstPages.setModel(MODEL_LOAD);
// btnHome.setEnabled(false);
// btnOpen.setEnabled(false);
// togPan.setEnabled(false);
// togZoom.setEnabled(false);
// setCurrentDocumentNull();
//
//// measureComponent.reset();
// }
//
// //~ Methods ------------------------------------------------------------
// @Override
// protected Collection[] doInBackground() throws Exception {
// final Collection[] result = new Collection[2];
//
// final Object bild = getCidsBean().getProperty("bild");
// final Object grenzniederschrift = getCidsBean().getProperty("grenzniederschrift");
// LOG.info("Found bild property " + bild);
// LOG.info("Found grenzniederschrift property " + grenzniederschrift);
//
// if (bild != null) {
// result[DOCUMENT_BILD] = getCorrespondingFiles(AlkisConstants.COMMONS.VERMESSUNG_HOST_BILDER, bild.toString().replaceAll("\\\\", "/"));
// }
// if (grenzniederschrift != null) {
// result[DOCUMENT_GRENZNIEDERSCHRIFT] = getCorrespondingFiles(AlkisConstants.COMMONS.VERMESSUNG_HOST_GRENZNIEDERSCHRIFTEN, grenzniederschrift.toString().replaceAll("\\\\", "/"));
// }
//
// return result;
// }
//
// @Override
// protected void done() {
// try {
// final Collection[] result = get();
// final StringBuffer collisionLists = new StringBuffer();
// for (int i = 0; i < result.length; ++i) {
// //cast!
// final Collection<File> current = result[i];
// if (current != null) {
// if (current.size() > 0) {
// if (current.size() > 1) {
// if (collisionLists.length() > 0) {
// collisionLists.append(",\n");
// }
// collisionLists.append(current);
// }
// documentURLs[i] = current.iterator().next();
// }
// }
// }
// if (collisionLists.length() > 0) {
// final String collisionWarning =
// "Achtung: im Zielverzeichnis sind mehrere Dateien mit"
// + " demselben Namen in unterschiedlichen Dateiformaten "
// + "vorhanden.\n\nBitte löschen Sie die ungültigen Formate "
// + "und setzen Sie die Bearbeitung in WuNDa anschließend fort."
// + "\n\nDateien:\n"
// + collisionLists
// + "\n";
// EventQueue.invokeLater(new Runnable() {
// @Override
// public void run() {
// JOptionPane.showMessageDialog(
// VermessungRissEditor.this,
// collisionWarning,
// "Unterschiedliche Dateiformate",
// JOptionPane.WARNING_MESSAGE);
// }
// });
// LOG.info(collisionWarning);
// }
// } catch (InterruptedException ex) {
// LOG.warn("Was interrupted while refreshing document.", ex);
// } catch (ExecutionException ex) {
// LOG.warn("There was an exception while refreshing document.", ex);
// } finally {
// if ((documentURLs[DOCUMENT_BILD] == null) && (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] == null)) {
// measuringComponent.setVisible(false);
// lblMissingDocuments.setVisible(true);
// lstPages.setModel(new DefaultListModel());
// lstPages.setEnabled(false);
// } else {
// if (documentURLs[DOCUMENT_BILD] != null) {
// togBild.setEnabled(true);
// togBild.setSelected(true);
// currentSelectedButton = togBild;
// currentDocument = DOCUMENT_BILD;
// }
// if (documentURLs[DOCUMENT_GRENZNIEDERSCHRIFT] != null) {
// togGrenzniederschrift.setEnabled(true);
//
// if (currentDocument == NO_SELECTION) {
// togGrenzniederschrift.setSelected(true);
// currentSelectedButton = togGrenzniederschrift;
// currentDocument = DOCUMENT_GRENZNIEDERSCHRIFT;
// }
// }
//
//// CismetThreadPool.execute(new PictureReaderWorker(documentURLs[currentDocument]));
// EventQueue.invokeLater(new PictureReaderWorker(documentURLs[currentDocument]));
// }
// }
// }
// }
// //J+
//
// /**
// * DOCUMENT ME!
// *
// * @version $Revision$, $Date$
// */
// final class PictureReaderWorker extends SwingWorker<ListModel, Void> {
//
// //~ Instance fields ----------------------------------------------------
//
// private final File pictureFile;
//
// //~ Constructors -------------------------------------------------------
//
// /**
// * Creates a new PictureReaderWorker object.
// *
// * @param pictureFile DOCUMENT ME!
// */
// public PictureReaderWorker(final File pictureFile) {
// this.pictureFile = pictureFile;
// if (LOG.isDebugEnabled()) {
// LOG.debug("prepare picture reader for file " + this.pictureFile);
// }
//
// lstPages.setModel(MODEL_LOAD);
// measuringComponent.removeAllFeatures();
// setDocumentControlsEnabled(false);
// }
//
// //~ Methods ------------------------------------------------------------
//
// @Override
// protected ListModel doInBackground() throws Exception {
// final DefaultListModel model = new DefaultListModel();
//
// closeReader();
//
// pictureReader = new MultiPagePictureReader(pictureFile);
//
// final int numberOfPages = pictureReader.getNumberOfPages();
// for (int i = 0; i < numberOfPages; ++i) {
// model.addElement(i + 1);
// }
//
// return model;
// }
//
// @Override
// protected void done() {
// boolean enableControls = true;
// try {
// final ListModel model = get();
// lstPages.setModel(model);
//
// if (model.getSize() > 0) {
// lstPages.setSelectedIndex(0);
// enableControls = false;
// } else {
// lstPages.setModel(new DefaultListModel());
// }
// } catch (InterruptedException ex) {
// setCurrentDocumentNull();
// displayErrorOrEnableControls(true);
// closeReader();
// LOG.warn("Reading found pictures was interrupted.", ex);
// } catch (ExecutionException ex) {
// setCurrentDocumentNull();
// displayErrorOrEnableControls(true);
// closeReader();
// LOG.error("Could not read found pictures.", ex);
// } finally {
// // We don't want to enable the controls if we set the selected index in lstPages. Calling
// // lstPages.setSelectedIndex(0)
// // invokes a PictureSelectWorker and thus disables the controls.
// if (enableControls) {
// setDocumentControlsEnabled(true);
// }
// }
// }
// }
//
// /**
// * DOCUMENT ME!
// *
// * @version $Revision$, $Date$
// */
// final class PictureSelectWorker extends SwingWorker<BufferedImage, Void> {
//
// //~ Instance fields ----------------------------------------------------
//
// private final int pageNumber;
//
// //~ Constructors -------------------------------------------------------
//
// /**
// * Creates a new PictureSelectWorker object.
// *
// * @param pageNumber DOCUMENT ME!
// */
// public PictureSelectWorker(final int pageNumber) {
// this.pageNumber = pageNumber;
// setCurrentPageNull();
// setDocumentControlsEnabled(false);
// measuringComponent.reset();
// btnHome.setEnabled(false);
// btnOpen.setEnabled(false);
// togPan.setEnabled(false);
// togZoom.setEnabled(false);
// lstPages.setEnabled(false);
// }
//
// //~ Methods ------------------------------------------------------------
//
// @Override
// protected BufferedImage doInBackground() throws Exception {
// if (pictureReader != null) {
// return pictureReader.loadPage(pageNumber);
// }
// throw new IllegalStateException("PictureReader is null!!");
// }
//
// @Override
// protected void done() {
// try {
// if (!isCancelled()) {
// currentPage = pageNumber;
// measuringComponent.addImage(get());
// togPan.setSelected(true);
// measuringComponent.zoomToFeatureCollection();
// displayErrorOrEnableControls(false);
// }
// } catch (InterruptedException ex) {
// setCurrentPageNull();
// displayErrorOrEnableControls(true);
// LOG.warn("Was interrupted while setting new image.", ex);
// } catch (Exception ex) {
// setCurrentPageNull();
// displayErrorOrEnableControls(true);
// LOG.error("Could not set new image.", ex);
// } finally {
// setDocumentControlsEnabled(true);
// currentPictureSelectWorker = null;
// }
// }
// }
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class EnableCombineGeometriesButton extends WindowAdapter {
//~ Methods ------------------------------------------------------------
@Override
public void windowDeactivated(final WindowEvent e) {
super.windowDeactivated(e);
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
@Override
public void windowClosed(final WindowEvent e) {
super.windowClosed(e);
btnCombineGeometries.setEnabled(lstLandparcels.getModel().getSize() > 0);
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class HighlightReferencingFlurstueckeCellRenderer extends JLabel implements ListCellRenderer {
//~ Methods ------------------------------------------------------------
@Override
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
setOpaque(true);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
final String errorWhileLoading = "Fehler beim Laden des Flurstücks";
final StringBuilder result = new StringBuilder();
if (value instanceof CidsBean) {
final CidsBean vermessung = (CidsBean)value;
if (vermessung.getProperty("flurstueck") instanceof CidsBean) {
final CidsBean flurstueck = (CidsBean)vermessung.getProperty("flurstueck");
if (flurstueck.getProperty("gemarkung") != null) {
final Object gemarkung = flurstueck.getProperty("gemarkung.name");
if ((gemarkung instanceof String) && (((String)gemarkung).trim().length() > 0)) {
result.append(gemarkung);
} else {
result.append(flurstueck.getProperty("gemarkung.id"));
}
} else {
result.append("Unbekannte Gemarkung");
}
result.append("-");
result.append(flurstueck.getProperty("flur"));
result.append("-");
result.append(flurstueck.getProperty("zaehler"));
final Object nenner = flurstueck.getProperty("nenner");
result.append('/');
if (nenner != null) {
result.append(nenner);
} else {
result.append('0');
}
if (flurstueck.getProperty("flurstueck") instanceof CidsBean) {
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(Color.blue);
}
}
} else {
result.append(errorWhileLoading);
}
if (vermessung.getProperty("veraenderungsart") != null) {
result.append(" (");
final Object vermessungsart = vermessung.getProperty("veraenderungsart.name");
if ((vermessungsart instanceof String) && (((String)vermessungsart).trim().length() > 0)) {
result.append(vermessungsart);
} else {
result.append(vermessung.getProperty("veraenderungsart.code"));
}
result.append(')');
}
} else {
result.append(errorWhileLoading);
}
setText(result.toString());
return this;
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
protected class GeometrieStatusRenderer implements ListCellRenderer {
//~ Instance fields ----------------------------------------------------
private ListCellRenderer originalRenderer;
//~ Constructors -------------------------------------------------------
/**
* Creates a new GeometrieStatusRenderer object.
*
* @param originalRenderer DOCUMENT ME!
*/
public GeometrieStatusRenderer(final ListCellRenderer originalRenderer) {
this.originalRenderer = originalRenderer;
}
//~ Methods ------------------------------------------------------------
@Override
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index,
final boolean isSelected,
final boolean cellHasFocus) {
final Component result = originalRenderer.getListCellRendererComponent(
list,
value,
index,
isSelected,
cellHasFocus);
if (isSelected) {
result.setBackground(list.getSelectionBackground());
result.setForeground(list.getSelectionForeground());
} else {
result.setBackground(list.getBackground());
result.setForeground(list.getForeground());
if (value instanceof CidsBean) {
final CidsBean geometrieStatus = (CidsBean)value;
if (geometrieStatus.getProperty("id") instanceof Integer) {
result.setBackground(COLORS_GEOMETRIE_STATUS.get((Integer)geometrieStatus.getProperty("id")));
}
}
}
return result;
}
}
//J-
private final class DocumentSizeFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
if ((fb.getDocument().getLength() + string.length()) <= 31) {
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
if ((fb.getDocument().getLength() + text.length() - length) <= 31) {
super.replace(fb, offset, length, text, attrs);
}
}
}
//J+
}
| true | true | private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblKennziffer = new javax.swing.JLabel();
txtKennziffer = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblKennziffer.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblKennziffer.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblKennziffer, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kennziffer}"),
txtKennziffer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtKennziffer, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(120, 32));
togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(120, 32));
togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(120, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
| private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
strFooter = new javax.swing.Box.Filler(new java.awt.Dimension(0, 22),
new java.awt.Dimension(0, 22),
new java.awt.Dimension(32767, 22));
pnlTitle = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
bgrControls = new javax.swing.ButtonGroup();
bgrDocument = new javax.swing.ButtonGroup();
pnlContainer = new javax.swing.JPanel();
pnlGeneralInformation = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderGeneralInformation = new de.cismet.tools.gui.SemiRoundedPanel();
lblGeneralInformation = new javax.swing.JLabel();
lblJahr = new javax.swing.JLabel();
txtJahr = new javax.swing.JTextField();
lblKennziffer = new javax.swing.JLabel();
txtKennziffer = new javax.swing.JTextField();
lblFormat = new javax.swing.JLabel();
cmbFormat = new DefaultBindableReferenceCombo();
lblLetzteAenderungName = new javax.swing.JLabel();
txtLetzteaenderungName = new javax.swing.JTextField();
lblLetzteAenderungDatum = new javax.swing.JLabel();
txtLetzteaenderungDatum = new javax.swing.JTextField();
lblGeometrie = new javax.swing.JLabel();
if (!readOnly) {
cmbGeometrie = new DefaultCismapGeometryComboBoxEditor();
}
btnCombineGeometries = new javax.swing.JButton();
gluGeneralInformationGap = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
lblGeometrieStatus = new javax.swing.JLabel();
cmbGeometrieStatus = new DefaultBindableReferenceCombo();
lblSchluessel = new javax.swing.JLabel();
cmbSchluessel = new javax.swing.JComboBox();
lblGemarkung = new javax.swing.JLabel();
cmbGemarkung = new DefaultBindableReferenceCombo();
lblFlur = new javax.swing.JLabel();
txtFlur = new javax.swing.JTextField();
lblBlatt = new javax.swing.JLabel();
txtBlatt = new javax.swing.JTextField();
pnlLandparcels = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderLandparcels = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderLandparcels = new javax.swing.JLabel();
scpLandparcels = new javax.swing.JScrollPane();
lstLandparcels = new javax.swing.JList();
btnAddLandparcel = new javax.swing.JButton();
btnRemoveLandparcel = new javax.swing.JButton();
pnlControls = new de.cismet.tools.gui.RoundedPanel();
togPan = new javax.swing.JToggleButton();
togZoom = new javax.swing.JToggleButton();
btnHome = new javax.swing.JButton();
pnlHeaderControls = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderControls = new javax.swing.JLabel();
btnOpen = new javax.swing.JButton();
pnlDocuments = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocuments = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocuments = new javax.swing.JLabel();
togBild = new javax.swing.JToggleButton();
togGrenzniederschrift = new javax.swing.JToggleButton();
pnlPages = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderPages = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderPages = new javax.swing.JLabel();
scpPages = new javax.swing.JScrollPane();
lstPages = new javax.swing.JList();
pnlDocument = new de.cismet.tools.gui.RoundedPanel();
pnlHeaderDocument = new de.cismet.tools.gui.SemiRoundedPanel();
lblHeaderDocument = new javax.swing.JLabel();
measuringComponent = new MeasuringComponent(INITIAL_BOUNDINGBOX, CRS);
lblErrorWhileLoadingBild = new javax.swing.JLabel();
lblErrorWhileLoadingGrenzniederschrift = new javax.swing.JLabel();
lblMissingDocuments = new javax.swing.JLabel();
gluGapControls = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 0),
new java.awt.Dimension(0, 32767));
pnlTitle.setOpaque(false);
pnlTitle.setLayout(new java.awt.GridBagLayout());
lblTitle.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
lblTitle.setForeground(java.awt.Color.white);
lblTitle.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblTitle.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlTitle.add(lblTitle, gridBagConstraints);
setLayout(new java.awt.GridBagLayout());
pnlContainer.setOpaque(false);
pnlContainer.setLayout(new java.awt.GridBagLayout());
pnlGeneralInformation.setLayout(new java.awt.GridBagLayout());
pnlHeaderGeneralInformation.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderGeneralInformation.setLayout(new java.awt.FlowLayout());
lblGeneralInformation.setForeground(new java.awt.Color(255, 255, 255));
lblGeneralInformation.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeneralInformation.text")); // NOI18N
pnlHeaderGeneralInformation.add(lblGeneralInformation);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlGeneralInformation.add(pnlHeaderGeneralInformation, gridBagConstraints);
lblJahr.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblJahr.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblJahr, gridBagConstraints);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.jahr}"),
txtJahr,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtJahr, gridBagConstraints);
lblKennziffer.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblKennziffer.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblKennziffer, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.kennziffer}"),
txtKennziffer,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(txtKennziffer, gridBagConstraints);
lblFormat.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFormat.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFormat, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.format}"),
cmbFormat,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7);
pnlGeneralInformation.add(cmbFormat, gridBagConstraints);
lblLetzteAenderungName.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungName.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungName, gridBagConstraints);
txtLetzteaenderungName.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_name}"),
txtLetzteaenderungName,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungName, gridBagConstraints);
lblLetzteAenderungDatum.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblLetzteAenderungDatum.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5);
pnlGeneralInformation.add(lblLetzteAenderungDatum, gridBagConstraints);
txtLetzteaenderungDatum.setEditable(false);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.letzteaenderung_datum}"),
txtLetzteaenderungDatum,
org.jdesktop.beansbinding.BeanProperty.create("text"));
binding.setConverter(new SqlDateToStringConverter());
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtLetzteaenderungDatum, gridBagConstraints);
lblGeometrie.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrie.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrie, gridBagConstraints);
if (!readOnly) {
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie}"),
cmbGeometrie,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cmbGeometrie).getConverter());
bindingGroup.addBinding(binding);
}
if (!readOnly) {
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 6;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrie, gridBagConstraints);
}
btnCombineGeometries.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/wizard.png"))); // NOI18N
btnCombineGeometries.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.text")); // NOI18N
btnCombineGeometries.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnCombineGeometries.toolTipText")); // NOI18N
btnCombineGeometries.setEnabled(false);
btnCombineGeometries.setFocusPainted(false);
btnCombineGeometries.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnCombineGeometriesActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 7;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 10, 10);
pnlGeneralInformation.add(btnCombineGeometries, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 8;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlGeneralInformation.add(gluGeneralInformationGap, gridBagConstraints);
lblGeometrieStatus.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGeometrieStatus.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblGeometrieStatus, gridBagConstraints);
cmbGeometrieStatus.setRenderer(new GeometrieStatusRenderer(cmbGeometrieStatus.getRenderer()));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.geometrie_status}"),
cmbGeometrieStatus,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
cmbGeometrieStatus.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
cmbGeometrieStatusActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(cmbGeometrieStatus, gridBagConstraints);
lblSchluessel.setLabelFor(cmbSchluessel);
lblSchluessel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblSchluessel.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5);
pnlGeneralInformation.add(lblSchluessel, gridBagConstraints);
cmbSchluessel.setModel(new javax.swing.DefaultComboBoxModel(
new String[] { "501", "502", "503", "504", "505", "506", "507", "508", "600", "605" }));
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.schluessel}"),
cmbSchluessel,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(cmbSchluessel, gridBagConstraints);
lblGemarkung.setLabelFor(cmbGemarkung);
lblGemarkung.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblGemarkung.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 5);
pnlGeneralInformation.add(lblGemarkung, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.gemarkung}"),
cmbGemarkung,
org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10);
pnlGeneralInformation.add(cmbGemarkung, gridBagConstraints);
lblFlur.setLabelFor(txtFlur);
lblFlur.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblFlur.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5);
pnlGeneralInformation.add(lblFlur, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.flur}"),
txtFlur,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(txtFlur, gridBagConstraints);
lblBlatt.setLabelFor(txtBlatt);
lblBlatt.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblBlatt.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlGeneralInformation.add(lblBlatt, gridBagConstraints);
binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
org.jdesktop.beansbinding.ELProperty.create("${cidsBean.blatt}"),
txtBlatt,
org.jdesktop.beansbinding.BeanProperty.create("text"));
bindingGroup.addBinding(binding);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10);
pnlGeneralInformation.add(txtBlatt, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.75;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
pnlContainer.add(pnlGeneralInformation, gridBagConstraints);
pnlLandparcels.setLayout(new java.awt.GridBagLayout());
pnlHeaderLandparcels.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderLandparcels.setLayout(new java.awt.FlowLayout());
lblHeaderLandparcels.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderLandparcels.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderLandparcels.text")); // NOI18N
pnlHeaderLandparcels.add(lblHeaderLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlLandparcels.add(pnlHeaderLandparcels, gridBagConstraints);
scpLandparcels.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpLandparcels.setMinimumSize(new java.awt.Dimension(266, 138));
scpLandparcels.setOpaque(false);
lstLandparcels.setCellRenderer(new HighlightReferencingFlurstueckeCellRenderer());
final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create(
"${cidsBean.flurstuecksvermessung}");
final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings
.createJListBinding(
org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE,
this,
eLProperty,
lstLandparcels);
bindingGroup.addBinding(jListBinding);
lstLandparcels.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(final java.awt.event.MouseEvent evt) {
lstLandparcelsMouseClicked(evt);
}
});
lstLandparcels.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstLandparcelsValueChanged(evt);
}
});
scpLandparcels.setViewportView(lstLandparcels);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
pnlLandparcels.add(scpLandparcels, gridBagConstraints);
btnAddLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N
btnAddLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.text")); // NOI18N
btnAddLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnAddLandparcel.toolTipText")); // NOI18N
btnAddLandparcel.setFocusPainted(false);
btnAddLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnAddLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnAddLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_END;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 10, 2);
pnlLandparcels.add(btnAddLandparcel, gridBagConstraints);
btnRemoveLandparcel.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N
btnRemoveLandparcel.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.text")); // NOI18N
btnRemoveLandparcel.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnRemoveLandparcel.toolTipText")); // NOI18N
btnRemoveLandparcel.setEnabled(false);
btnRemoveLandparcel.setFocusPainted(false);
btnRemoveLandparcel.setMaximumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setMinimumSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.setPreferredSize(new java.awt.Dimension(43, 25));
btnRemoveLandparcel.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnRemoveLandparcelActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 2, 10, 10);
pnlLandparcels.add(btnRemoveLandparcel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.25;
gridBagConstraints.weighty = 0.1;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 0);
pnlContainer.add(pnlLandparcels, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weighty = 0.1;
add(pnlContainer, gridBagConstraints);
pnlControls.setLayout(new java.awt.GridBagLayout());
bgrControls.add(togPan);
togPan.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/pan.gif"))); // NOI18N
togPan.setSelected(true);
togPan.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.text")); // NOI18N
togPan.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togPan.toolTipText")); // NOI18N
togPan.setEnabled(false);
togPan.setFocusPainted(false);
togPan.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togPan.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togPanActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togPan, gridBagConstraints);
bgrControls.add(togZoom);
togZoom.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/zoom.gif"))); // NOI18N
togZoom.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.text")); // NOI18N
togZoom.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togZoom.toolTipText")); // NOI18N
togZoom.setEnabled(false);
togZoom.setFocusPainted(false);
togZoom.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
togZoom.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togZoomActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 3, 10);
pnlControls.add(togZoom, gridBagConstraints);
btnHome.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/home.gif"))); // NOI18N
btnHome.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.text")); // NOI18N
btnHome.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnHome.toolTipText")); // NOI18N
btnHome.setEnabled(false);
btnHome.setFocusPainted(false);
btnHome.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnHome.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnHomeActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 3, 10);
pnlControls.add(btnHome, gridBagConstraints);
pnlHeaderControls.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderControls.setLayout(new java.awt.FlowLayout());
lblHeaderControls.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderControls.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderControls.text")); // NOI18N
pnlHeaderControls.add(lblHeaderControls);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
pnlControls.add(pnlHeaderControls, gridBagConstraints);
btnOpen.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/wunda_blau/res/folder-image.png"))); // NOI18N
btnOpen.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.text")); // NOI18N
btnOpen.setToolTipText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.btnOpen.toolTipText")); // NOI18N
btnOpen.setEnabled(false);
btnOpen.setFocusPainted(false);
btnOpen.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
btnOpen.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
btnOpenActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 8, 10);
pnlControls.add(btnOpen, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
add(pnlControls, gridBagConstraints);
pnlDocuments.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocuments.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderDocuments.setLayout(new java.awt.FlowLayout());
lblHeaderDocuments.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocuments.text")); // NOI18N
pnlHeaderDocuments.add(lblHeaderDocuments);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 0.1;
pnlDocuments.add(pnlHeaderDocuments, gridBagConstraints);
bgrDocument.add(togBild);
togBild.setSelected(true);
togBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togBild.text")); // NOI18N
togBild.setEnabled(false);
togBild.setFocusPainted(false);
togBild.setMaximumSize(new java.awt.Dimension(49, 32));
togBild.setMinimumSize(new java.awt.Dimension(49, 32));
togBild.setPreferredSize(new java.awt.Dimension(49, 32));
togBild.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togBildActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(5, 10, 2, 10);
pnlDocuments.add(togBild, gridBagConstraints);
bgrDocument.add(togGrenzniederschrift);
togGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.togGrenzniederschrift.text")); // NOI18N
togGrenzniederschrift.setEnabled(false);
togGrenzniederschrift.setFocusPainted(false);
togGrenzniederschrift.setMaximumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setMinimumSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.setPreferredSize(new java.awt.Dimension(150, 32));
togGrenzniederschrift.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(final java.awt.event.ActionEvent evt) {
togGrenzniederschriftActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(2, 10, 10, 10);
pnlDocuments.add(togGrenzniederschrift, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(10, 0, 5, 5);
add(pnlDocuments, gridBagConstraints);
pnlHeaderPages.setBackground(new java.awt.Color(51, 51, 51));
pnlHeaderPages.setLayout(new java.awt.FlowLayout());
lblHeaderPages.setForeground(new java.awt.Color(255, 255, 255));
lblHeaderPages.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderPages.text")); // NOI18N
pnlHeaderPages.add(lblHeaderPages);
pnlPages.add(pnlHeaderPages, java.awt.BorderLayout.PAGE_START);
scpPages.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
scpPages.setMinimumSize(new java.awt.Dimension(31, 75));
scpPages.setOpaque(false);
scpPages.setPreferredSize(new java.awt.Dimension(85, 75));
lstPages.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
lstPages.setEnabled(false);
lstPages.setFixedCellWidth(75);
lstPages.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
@Override
public void valueChanged(final javax.swing.event.ListSelectionEvent evt) {
lstPagesValueChanged(evt);
}
});
scpPages.setViewportView(lstPages);
pnlPages.add(scpPages, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
add(pnlPages, gridBagConstraints);
pnlDocument.setLayout(new java.awt.GridBagLayout());
pnlHeaderDocument.setBackground(java.awt.Color.darkGray);
pnlHeaderDocument.setLayout(new java.awt.GridBagLayout());
lblHeaderDocument.setForeground(java.awt.Color.white);
lblHeaderDocument.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblHeaderDocument.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
pnlHeaderDocument.add(lblHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
pnlDocument.add(pnlHeaderDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(measuringComponent, gridBagConstraints);
lblErrorWhileLoadingBild.setBackground(java.awt.Color.white);
lblErrorWhileLoadingBild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingBild.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingBild.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingBild.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingBild, gridBagConstraints);
lblErrorWhileLoadingGrenzniederschrift.setBackground(java.awt.Color.white);
lblErrorWhileLoadingGrenzniederschrift.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblErrorWhileLoadingGrenzniederschrift.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblErrorWhileLoadingGrenzniederschrift.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblErrorWhileLoadingGrenzniederschrift.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblErrorWhileLoadingGrenzniederschrift, gridBagConstraints);
lblMissingDocuments.setBackground(java.awt.Color.white);
lblMissingDocuments.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblMissingDocuments.setIcon(new javax.swing.ImageIcon(
getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/missingRasterdocument.png"))); // NOI18N
lblMissingDocuments.setText(org.openide.util.NbBundle.getMessage(
VermessungRissEditor.class,
"VermessungRissEditor.lblMissingDocuments.text")); // NOI18N
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
pnlDocument.add(lblMissingDocuments, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridheight = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
gridBagConstraints.weightx = 0.1;
gridBagConstraints.insets = new java.awt.Insets(10, 5, 0, 0);
add(pnlDocument, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 0.1;
add(gluGapControls, gridBagConstraints);
bindingGroup.bind();
} // </editor-fold>//GEN-END:initComponents
|
diff --git a/src/test/java/org/freeeed/main/FreeEedSmallTest.java b/src/test/java/org/freeeed/main/FreeEedSmallTest.java
index aec5c88f..b423f98e 100644
--- a/src/test/java/org/freeeed/main/FreeEedSmallTest.java
+++ b/src/test/java/org/freeeed/main/FreeEedSmallTest.java
@@ -1,61 +1,67 @@
package org.freeeed.main;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.freeeed.main.PlatformUtil.PLATFORM;
import org.freeeed.services.Project;
import static org.junit.Assert.assertTrue;
import org.junit.*;
public class FreeEedSmallTest {
public FreeEedSmallTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
- String partFile = project.getResultsDir() + File.separator + "part-r-00000";
+ String metadataFile = project.getResultsDir() + File.separator;
+ if (PlatformUtil.getPlatform() == PlatformUtil.PLATFORM.WINDOWS) {
+ metadataFile += "metadata.txt";
+ } else {
+ metadataFile += "part-r-00000";
+ }
+ assertTrue(new File(metadataFile).exists());
try {
- int resultCount = Files.readLines(new File(partFile), Charset.defaultCharset()).size();
+ int resultCount = Files.readLines(new File(metadataFile), Charset.defaultCharset()).size();
System.out.println("resultCount = " + resultCount);
assertTrue(resultCount == 4);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
| false | true | public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
String partFile = project.getResultsDir() + File.separator + "part-r-00000";
try {
int resultCount = Files.readLines(new File(partFile), Charset.defaultCharset()).size();
System.out.println("resultCount = " + resultCount);
assertTrue(resultCount == 4);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
| public void testMain() {
System.out.println("testMain");
String[] args = new String[2];
args[0] = "-param_file";
args[1] = "small_test.project";
// delete output, so that the test should run
Project project = Project.loadFromFile(new File(args[1]));
try {
if (new File(project.getOutputDir()).exists()) {
Files.deleteRecursively(new File(project.getOutputDir()));
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
FreeEedMain.main(args);
// TODO - do more tests
String outputSuccess = project.getResultsDir() + "/_SUCCESS";
assertTrue(new File(outputSuccess).exists());
String metadataFile = project.getResultsDir() + File.separator;
if (PlatformUtil.getPlatform() == PlatformUtil.PLATFORM.WINDOWS) {
metadataFile += "metadata.txt";
} else {
metadataFile += "part-r-00000";
}
assertTrue(new File(metadataFile).exists());
try {
int resultCount = Files.readLines(new File(metadataFile), Charset.defaultCharset()).size();
System.out.println("resultCount = " + resultCount);
assertTrue(resultCount == 4);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
|
diff --git a/wilhelm/tests/native-media/src/com/example/nativemedia/NativeMedia.java b/wilhelm/tests/native-media/src/com/example/nativemedia/NativeMedia.java
index 01636d29..82d579df 100644
--- a/wilhelm/tests/native-media/src/com/example/nativemedia/NativeMedia.java
+++ b/wilhelm/tests/native-media/src/com/example/nativemedia/NativeMedia.java
@@ -1,396 +1,398 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.nativemedia;
import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import java.io.IOException;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer;
public class NativeMedia extends Activity {
static final String TAG = "NativeMedia";
String mSourceString = null;
String mSinkString = null;
// member variables for Java media player
MediaPlayer mMediaPlayer;
boolean mMediaPlayerIsPrepared = false;
SurfaceView mSurfaceView1;
SurfaceHolder mSurfaceHolder1;
// member variables for native media player
boolean mIsPlayingStreaming = false;
SurfaceView mSurfaceView2;
SurfaceHolder mSurfaceHolder2;
VideoSink mSelectedVideoSink;
VideoSink mJavaMediaPlayerVideoSink;
VideoSink mNativeMediaPlayerVideoSink;
SurfaceHolderVideoSink mSurfaceHolder1VideoSink, mSurfaceHolder2VideoSink;
GLViewVideoSink mGLView1VideoSink, mGLView2VideoSink;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1);
mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2);
//setContentView(mGLView);
//setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// initialize native media system
createEngine();
// set up the Surface 1 video sink
mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1);
mSurfaceHolder1 = mSurfaceView1.getHolder();
mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
- Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height);
+ Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" +
+ height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// set up the Surface 2 video sink
mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2);
mSurfaceHolder2 = mSurfaceView2.getHolder();
mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
- Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height);
+ Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" +
+ height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// create Java media player
mMediaPlayer = new MediaPlayer();
// set up Java media player listeners
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
int width = mediaPlayer.getVideoWidth();
int height = mediaPlayer.getVideoHeight();
Log.v(TAG, "onPrepared width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
mMediaPlayerIsPrepared = true;
mediaPlayer.start();
}
});
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
}
});
// initialize content source spinner
Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner);
ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sourceSpinner.setAdapter(sourceAdapter);
sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSourceString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSourceString);
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSourceString = null;
}
});
// initialize video sink spinner
Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner);
ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource(
this, R.array.sink_array, android.R.layout.simple_spinner_item);
sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sinkSpinner.setAdapter(sinkAdapter);
sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSinkString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSinkString);
if ("Surface 1".equals(mSinkString)) {
if (mSurfaceHolder1VideoSink == null) {
mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1);
}
mSelectedVideoSink = mSurfaceHolder1VideoSink;
} else if ("Surface 2".equals(mSinkString)) {
if (mSurfaceHolder2VideoSink == null) {
mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2);
}
mSelectedVideoSink = mSurfaceHolder2VideoSink;
} else if ("SurfaceTexture 1".equals(mSinkString)) {
if (mGLView1VideoSink == null) {
mGLView1VideoSink = new GLViewVideoSink(mGLView1);
}
mSelectedVideoSink = mGLView1VideoSink;
} else if ("SurfaceTexture 2".equals(mSinkString)) {
if (mGLView2VideoSink == null) {
mGLView2VideoSink = new GLViewVideoSink(mGLView2);
}
mSelectedVideoSink = mGLView2VideoSink;
}
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSinkString = null;
mSelectedVideoSink = null;
}
});
// initialize button click handlers
// Java MediaPlayer start/pause
((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mJavaMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForJava(mMediaPlayer);
mJavaMediaPlayerVideoSink = mSelectedVideoSink;
}
if (!mMediaPlayerIsPrepared) {
if (mSourceString != null) {
try {
mMediaPlayer.setDataSource(mSourceString);
} catch (IOException e) {
Log.e(TAG, "IOException " + e);
}
mMediaPlayer.prepareAsync();
}
} else if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
// native MediaPlayer start/pause
((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() {
boolean created = false;
public void onClick(View view) {
if (!created) {
if (mNativeMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForNative();
mNativeMediaPlayerVideoSink = mSelectedVideoSink;
}
if (mSourceString != null) {
created = createStreamingMediaPlayer(mSourceString);
}
}
if (created) {
mIsPlayingStreaming = !mIsPlayingStreaming;
setPlayingStreamingMediaPlayer(mIsPlayingStreaming);
}
}
});
// Java MediaPlayer rewind
((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mMediaPlayerIsPrepared) {
mMediaPlayer.seekTo(0);
}
}
});
// native MediaPlayer rewind
((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mNativeMediaPlayerVideoSink != null) {
rewindStreamingMediaPlayer();
}
}
});
}
/** Called when the activity is about to be paused. */
@Override
protected void onPause()
{
mIsPlayingStreaming = false;
setPlayingStreamingMediaPlayer(false);
mGLView1.onPause();
mGLView2.onPause();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView1.onResume();
mGLView2.onResume();
}
/** Called when the activity is about to be destroyed. */
@Override
protected void onDestroy()
{
shutdown();
super.onDestroy();
}
private MyGLSurfaceView mGLView1, mGLView2;
/** Native methods, implemented in jni folder */
public static native void createEngine();
public static native boolean createStreamingMediaPlayer(String filename);
public static native void setPlayingStreamingMediaPlayer(boolean isPlaying);
public static native void shutdown();
public static native void setSurface(Surface surface);
public static native void setSurfaceTexture(SurfaceTexture surfaceTexture);
public static native void rewindStreamingMediaPlayer();
/** Load jni .so on initialization */
static {
System.loadLibrary("native-media-jni");
}
// VideoSink abstracts out the difference between Surface and SurfaceTexture
// aka SurfaceHolder and GLSurfaceView
static abstract class VideoSink {
abstract void setFixedSize(int width, int height);
abstract void useAsSinkForJava(MediaPlayer mediaPlayer);
abstract void useAsSinkForNative();
}
static class SurfaceHolderVideoSink extends VideoSink {
private final SurfaceHolder mSurfaceHolder;
SurfaceHolderVideoSink(SurfaceHolder surfaceHolder) {
mSurfaceHolder = surfaceHolder;
}
void setFixedSize(int width, int height) {
mSurfaceHolder.setFixedSize(width, height);
}
void useAsSinkForJava(MediaPlayer mediaPlayer) {
mediaPlayer.setDisplay(mSurfaceHolder);
}
void useAsSinkForNative() {
setSurface(mSurfaceHolder.getSurface());
}
}
static class GLViewVideoSink extends VideoSink {
private final MyGLSurfaceView mMyGLSurfaceView;
GLViewVideoSink(MyGLSurfaceView myGLSurfaceView) {
mMyGLSurfaceView = myGLSurfaceView;
}
void setFixedSize(int width, int height) {
}
void useAsSinkForJava(MediaPlayer mediaPlayer) {
SurfaceTexture st = mMyGLSurfaceView.getSurfaceTexture();
Surface s = new Surface(st);
mediaPlayer.setSurface(s);
s.release();
}
void useAsSinkForNative() {
setSurfaceTexture(mMyGLSurfaceView.getSurfaceTexture());
}
}
}
| false | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1);
mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2);
//setContentView(mGLView);
//setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// initialize native media system
createEngine();
// set up the Surface 1 video sink
mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1);
mSurfaceHolder1 = mSurfaceView1.getHolder();
mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// set up the Surface 2 video sink
mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2);
mSurfaceHolder2 = mSurfaceView2.getHolder();
mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" + height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// create Java media player
mMediaPlayer = new MediaPlayer();
// set up Java media player listeners
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
int width = mediaPlayer.getVideoWidth();
int height = mediaPlayer.getVideoHeight();
Log.v(TAG, "onPrepared width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
mMediaPlayerIsPrepared = true;
mediaPlayer.start();
}
});
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
}
});
// initialize content source spinner
Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner);
ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sourceSpinner.setAdapter(sourceAdapter);
sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSourceString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSourceString);
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSourceString = null;
}
});
// initialize video sink spinner
Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner);
ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource(
this, R.array.sink_array, android.R.layout.simple_spinner_item);
sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sinkSpinner.setAdapter(sinkAdapter);
sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSinkString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSinkString);
if ("Surface 1".equals(mSinkString)) {
if (mSurfaceHolder1VideoSink == null) {
mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1);
}
mSelectedVideoSink = mSurfaceHolder1VideoSink;
} else if ("Surface 2".equals(mSinkString)) {
if (mSurfaceHolder2VideoSink == null) {
mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2);
}
mSelectedVideoSink = mSurfaceHolder2VideoSink;
} else if ("SurfaceTexture 1".equals(mSinkString)) {
if (mGLView1VideoSink == null) {
mGLView1VideoSink = new GLViewVideoSink(mGLView1);
}
mSelectedVideoSink = mGLView1VideoSink;
} else if ("SurfaceTexture 2".equals(mSinkString)) {
if (mGLView2VideoSink == null) {
mGLView2VideoSink = new GLViewVideoSink(mGLView2);
}
mSelectedVideoSink = mGLView2VideoSink;
}
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSinkString = null;
mSelectedVideoSink = null;
}
});
// initialize button click handlers
// Java MediaPlayer start/pause
((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mJavaMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForJava(mMediaPlayer);
mJavaMediaPlayerVideoSink = mSelectedVideoSink;
}
if (!mMediaPlayerIsPrepared) {
if (mSourceString != null) {
try {
mMediaPlayer.setDataSource(mSourceString);
} catch (IOException e) {
Log.e(TAG, "IOException " + e);
}
mMediaPlayer.prepareAsync();
}
} else if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
// native MediaPlayer start/pause
((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() {
boolean created = false;
public void onClick(View view) {
if (!created) {
if (mNativeMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForNative();
mNativeMediaPlayerVideoSink = mSelectedVideoSink;
}
if (mSourceString != null) {
created = createStreamingMediaPlayer(mSourceString);
}
}
if (created) {
mIsPlayingStreaming = !mIsPlayingStreaming;
setPlayingStreamingMediaPlayer(mIsPlayingStreaming);
}
}
});
// Java MediaPlayer rewind
((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mMediaPlayerIsPrepared) {
mMediaPlayer.seekTo(0);
}
}
});
// native MediaPlayer rewind
((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mNativeMediaPlayerVideoSink != null) {
rewindStreamingMediaPlayer();
}
}
});
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mGLView1 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview1);
mGLView2 = (MyGLSurfaceView) findViewById(R.id.glsurfaceview2);
//setContentView(mGLView);
//setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// initialize native media system
createEngine();
// set up the Surface 1 video sink
mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview1);
mSurfaceHolder1 = mSurfaceView1.getHolder();
mSurfaceHolder1.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" +
height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// set up the Surface 2 video sink
mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview2);
mSurfaceHolder2 = mSurfaceView2.getHolder();
mSurfaceHolder2.addCallback(new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.v(TAG, "surfaceChanged format=" + format + ", width=" + width + ", height=" +
height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated");
setSurface(holder.getSurface());
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v(TAG, "surfaceDestroyed");
}
});
// create Java media player
mMediaPlayer = new MediaPlayer();
// set up Java media player listeners
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
int width = mediaPlayer.getVideoWidth();
int height = mediaPlayer.getVideoHeight();
Log.v(TAG, "onPrepared width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
mMediaPlayerIsPrepared = true;
mediaPlayer.start();
}
});
mMediaPlayer.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
Log.v(TAG, "onVideoSizeChanged width=" + width + ", height=" + height);
if (width != 0 && height != 0 && mJavaMediaPlayerVideoSink != null) {
mJavaMediaPlayerVideoSink.setFixedSize(width, height);
}
}
});
// initialize content source spinner
Spinner sourceSpinner = (Spinner) findViewById(R.id.source_spinner);
ArrayAdapter<CharSequence> sourceAdapter = ArrayAdapter.createFromResource(
this, R.array.source_array, android.R.layout.simple_spinner_item);
sourceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sourceSpinner.setAdapter(sourceAdapter);
sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSourceString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSourceString);
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSourceString = null;
}
});
// initialize video sink spinner
Spinner sinkSpinner = (Spinner) findViewById(R.id.sink_spinner);
ArrayAdapter<CharSequence> sinkAdapter = ArrayAdapter.createFromResource(
this, R.array.sink_array, android.R.layout.simple_spinner_item);
sinkAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sinkSpinner.setAdapter(sinkAdapter);
sinkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
mSinkString = parent.getItemAtPosition(pos).toString();
Log.v(TAG, "onItemSelected " + mSinkString);
if ("Surface 1".equals(mSinkString)) {
if (mSurfaceHolder1VideoSink == null) {
mSurfaceHolder1VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder1);
}
mSelectedVideoSink = mSurfaceHolder1VideoSink;
} else if ("Surface 2".equals(mSinkString)) {
if (mSurfaceHolder2VideoSink == null) {
mSurfaceHolder2VideoSink = new SurfaceHolderVideoSink(mSurfaceHolder2);
}
mSelectedVideoSink = mSurfaceHolder2VideoSink;
} else if ("SurfaceTexture 1".equals(mSinkString)) {
if (mGLView1VideoSink == null) {
mGLView1VideoSink = new GLViewVideoSink(mGLView1);
}
mSelectedVideoSink = mGLView1VideoSink;
} else if ("SurfaceTexture 2".equals(mSinkString)) {
if (mGLView2VideoSink == null) {
mGLView2VideoSink = new GLViewVideoSink(mGLView2);
}
mSelectedVideoSink = mGLView2VideoSink;
}
}
public void onNothingSelected(AdapterView parent) {
Log.v(TAG, "onNothingSelected");
mSinkString = null;
mSelectedVideoSink = null;
}
});
// initialize button click handlers
// Java MediaPlayer start/pause
((Button) findViewById(R.id.start_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mJavaMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForJava(mMediaPlayer);
mJavaMediaPlayerVideoSink = mSelectedVideoSink;
}
if (!mMediaPlayerIsPrepared) {
if (mSourceString != null) {
try {
mMediaPlayer.setDataSource(mSourceString);
} catch (IOException e) {
Log.e(TAG, "IOException " + e);
}
mMediaPlayer.prepareAsync();
}
} else if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
} else {
mMediaPlayer.start();
}
}
});
// native MediaPlayer start/pause
((Button) findViewById(R.id.start_native)).setOnClickListener(new View.OnClickListener() {
boolean created = false;
public void onClick(View view) {
if (!created) {
if (mNativeMediaPlayerVideoSink == null) {
if (mSelectedVideoSink == null) {
return;
}
mSelectedVideoSink.useAsSinkForNative();
mNativeMediaPlayerVideoSink = mSelectedVideoSink;
}
if (mSourceString != null) {
created = createStreamingMediaPlayer(mSourceString);
}
}
if (created) {
mIsPlayingStreaming = !mIsPlayingStreaming;
setPlayingStreamingMediaPlayer(mIsPlayingStreaming);
}
}
});
// Java MediaPlayer rewind
((Button) findViewById(R.id.rewind_java)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mMediaPlayerIsPrepared) {
mMediaPlayer.seekTo(0);
}
}
});
// native MediaPlayer rewind
((Button) findViewById(R.id.rewind_native)).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mNativeMediaPlayerVideoSink != null) {
rewindStreamingMediaPlayer();
}
}
});
}
|
diff --git a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/presenter/SummaryTabPresenter.java b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/presenter/SummaryTabPresenter.java
index 27d053960..19706f064 100644
--- a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/presenter/SummaryTabPresenter.java
+++ b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/magma/presenter/SummaryTabPresenter.java
@@ -1,247 +1,248 @@
/*
* Copyright (c) 2013 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.obiba.opal.web.gwt.app.client.magma.presenter;
import org.obiba.opal.web.gwt.app.client.event.NotificationEvent;
import org.obiba.opal.web.gwt.app.client.magma.event.SummaryReceivedEvent;
import org.obiba.opal.web.gwt.app.client.magma.event.SummaryRequiredEvent;
import org.obiba.opal.web.gwt.app.client.magma.event.VariableRefreshEvent;
import org.obiba.opal.web.gwt.app.client.support.JSErrorNotificationEventBuilder;
import org.obiba.opal.web.gwt.rest.client.ResourceCallback;
import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilder;
import org.obiba.opal.web.gwt.rest.client.ResourceRequestBuilderFactory;
import org.obiba.opal.web.gwt.rest.client.ResponseCodeCallback;
import org.obiba.opal.web.gwt.rest.client.UriBuilder;
import org.obiba.opal.web.model.client.math.SummaryStatisticsDto;
import org.obiba.opal.web.model.client.ws.ClientErrorDto;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.Response;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
/**
*
*/
public class SummaryTabPresenter extends PresenterWidget<SummaryTabPresenter.Display> implements SummaryTabUiHandlers {
public final static int DEFAULT_LIMIT = 500;
private final static int MIN_LIMIT = 10;
private SummaryStatisticsDto summary;
private Request summaryRequest;
private ResourceRequestBuilder<SummaryStatisticsDto> resourceRequestBuilder;
private int limit = DEFAULT_LIMIT;
private int entitiesCount;
@Inject
public SummaryTabPresenter(EventBus eventBus, Display display) {
super(eventBus, display);
getView().setUiHandlers(this);
}
@Override
protected void onBind() {
registerHandler(getEventBus().addHandler(SummaryRequiredEvent.getType(), new DeferredSummaryRequestHandler()));
// Variable Script refreshed
addRegisteredHandler(VariableRefreshEvent.getType(), new VariableRefreshEvent.Handler() {
@Override
public void onVariableRefresh(VariableRefreshEvent event) {
requestSummary();
}
});
}
@Override
public void onReset() {
if(!hasSummaryOrPendingRequest()) {
requestSummary();
}
}
@Override
public void onFullSummary() {
getView().setLimit(entitiesCount);
cancelPendingSummaryRequest();
// Remove queries from the url
String uri = resourceRequestBuilder.getResource();
if(uri.indexOf("?") > 0) {
uri = uri.substring(0, uri.indexOf("?"));
}
// If transient variable, the method is POST
if(uri.contains("/_transient/")) {
resourceRequestBuilder.forResource(uri).post();
} else {
resourceRequestBuilder.forResource(uri).get();
}
limit = entitiesCount;
onReset();
}
@Override
public void onCancelSummary() {
cancelPendingSummaryRequest();
getView().renderCancelSummaryLimit(limit < entitiesCount ? limit : Math.min(DEFAULT_LIMIT, entitiesCount),
entitiesCount);
}
@Override
public void onRefreshSummary() {
cancelPendingSummaryRequest();
limit = getView().getLimit().intValue();
if(limit < Math.min(MIN_LIMIT, entitiesCount)) {
limit = Math.min(MIN_LIMIT, entitiesCount);
}
String uri = resourceRequestBuilder.getResource();
uri = uri.substring(0, uri.indexOf("?") > 0 ? uri.indexOf("?") : uri.length());
// If transient variable, the method is POST
if(uri.contains("/_transient/")) {
resourceRequestBuilder
.forResource(limit >= entitiesCount ? uri + "?resetCache=true" : uri + "?limit=" + limit + "&resetCache=true")
.post();
} else {
resourceRequestBuilder
.forResource(limit >= entitiesCount ? uri + "?resetCache=true" : uri + "?limit=" + limit + "&resetCache=true")
.get();
}
onReset();
}
public void forgetSummary() {
cancelPendingSummaryRequest();
summary = null;
}
public void hideSummaryPreview() {
getView().hideSummaryPreview();
}
public void setResourceUri(UriBuilder uri, int entitiesCount, String... args) {
cancelPendingSummaryRequest();
this.entitiesCount = entitiesCount;
if(limit < entitiesCount) {
uri.query("limit", String.valueOf(limit));
}
resourceRequestBuilder = ResourceRequestBuilderFactory.<SummaryStatisticsDto>newBuilder()
.forResource(uri.build(args)).get();
limit = Math.min(entitiesCount, limit);
}
public void setRequestBuilder(ResourceRequestBuilder<SummaryStatisticsDto> resourceRequestBuilder,
int entitiesCount) {
this.resourceRequestBuilder = resourceRequestBuilder;
this.entitiesCount = entitiesCount;
limit = Math.min(entitiesCount, limit);
}
private void requestSummary() {
+ if (resourceRequestBuilder == null) return;
getView().requestingSummary(limit, entitiesCount);
summaryRequest = resourceRequestBuilder //
.withCallback(new ResourceCallback<SummaryStatisticsDto>() {
@Override
public void onResource(Response response, SummaryStatisticsDto resource) {
summary = resource;
getView().renderSummary(resource);
getView().renderSummaryLimit(limit, entitiesCount);
getEventBus().fireEvent(new SummaryReceivedEvent(resourceRequestBuilder.getResource(), resource));
}
}) //
.withCallback(Response.SC_NOT_FOUND, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
getView().renderNoSummary();
}
}) //
.withCallback(Response.SC_BAD_REQUEST, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
NotificationEvent notificationEvent = new JSErrorNotificationEventBuilder()
.build((ClientErrorDto) JsonUtils.unsafeEval(response.getText()));
getEventBus().fireEvent(notificationEvent);
}
}) //
.send();
}
private void cancelPendingSummaryRequest() {
summary = null;
if(summaryRequest != null && summaryRequest.isPending()) {
summaryRequest.cancel();
summaryRequest = null;
}
}
private boolean hasSummaryOrPendingRequest() {
return summary != null || summaryRequest != null && summaryRequest.isPending();
}
public void setLimit(int limit) {
this.limit = limit;
getView().setLimit(limit);
}
public void init() {
// Reset limit to the default limit only if it was the full summary
if(limit == entitiesCount) {
limit = DEFAULT_LIMIT;
}
onReset();
}
@SuppressWarnings("ParameterHidesMemberVariable")
public interface Display extends View, HasUiHandlers<SummaryTabUiHandlers> {
void requestingSummary(int limit, int entitiesCount);
void renderSummary(SummaryStatisticsDto summary);
void renderNoSummary();
void renderSummaryLimit(int limit, int entitiesCount);
void renderCancelSummaryLimit(int limit, int entitiesCount);
Number getLimit();
void setLimit(int limit);
void hideSummaryPreview();
}
class DeferredSummaryRequestHandler implements SummaryRequiredEvent.Handler {
@Override
public void onSummaryRequest(SummaryRequiredEvent event) {
getView().setLimit(DEFAULT_LIMIT);
setResourceUri(event.getResourceUri(), event.getMax() == null ? DEFAULT_LIMIT : event.getMax(), event.getArgs());
requestSummary();
}
}
}
| true | true | private void requestSummary() {
getView().requestingSummary(limit, entitiesCount);
summaryRequest = resourceRequestBuilder //
.withCallback(new ResourceCallback<SummaryStatisticsDto>() {
@Override
public void onResource(Response response, SummaryStatisticsDto resource) {
summary = resource;
getView().renderSummary(resource);
getView().renderSummaryLimit(limit, entitiesCount);
getEventBus().fireEvent(new SummaryReceivedEvent(resourceRequestBuilder.getResource(), resource));
}
}) //
.withCallback(Response.SC_NOT_FOUND, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
getView().renderNoSummary();
}
}) //
.withCallback(Response.SC_BAD_REQUEST, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
NotificationEvent notificationEvent = new JSErrorNotificationEventBuilder()
.build((ClientErrorDto) JsonUtils.unsafeEval(response.getText()));
getEventBus().fireEvent(notificationEvent);
}
}) //
.send();
}
| private void requestSummary() {
if (resourceRequestBuilder == null) return;
getView().requestingSummary(limit, entitiesCount);
summaryRequest = resourceRequestBuilder //
.withCallback(new ResourceCallback<SummaryStatisticsDto>() {
@Override
public void onResource(Response response, SummaryStatisticsDto resource) {
summary = resource;
getView().renderSummary(resource);
getView().renderSummaryLimit(limit, entitiesCount);
getEventBus().fireEvent(new SummaryReceivedEvent(resourceRequestBuilder.getResource(), resource));
}
}) //
.withCallback(Response.SC_NOT_FOUND, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
getView().renderNoSummary();
}
}) //
.withCallback(Response.SC_BAD_REQUEST, new ResponseCodeCallback() {
@Override
public void onResponseCode(Request request, Response response) {
NotificationEvent notificationEvent = new JSErrorNotificationEventBuilder()
.build((ClientErrorDto) JsonUtils.unsafeEval(response.getText()));
getEventBus().fireEvent(notificationEvent);
}
}) //
.send();
}
|
diff --git a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
index 4cc454e92..45487bbcd 100644
--- a/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
+++ b/core-api/src/main/java/no/schibstedsok/searchportal/mode/command/NavigatableESPFastCommand.java
@@ -1,355 +1,355 @@
// Copyright (2007) Schibsted Søk AS
/*
* NavigatatableAdvancedFastSearchCommand.java
*
* Created on July 20, 2006, 11:57 AM
*
*/
package no.schibstedsok.searchportal.mode.command;
import com.fastsearch.esp.search.result.IModifier;
import com.fastsearch.esp.search.result.INavigator;
import com.fastsearch.esp.search.result.IQueryResult;
import no.schibstedsok.searchportal.mode.config.NavigatableEspFastCommandConfig;
import no.schibstedsok.searchportal.result.FastSearchResult;
import no.schibstedsok.searchportal.result.Modifier;
import no.schibstedsok.searchportal.result.Navigator;
import no.schibstedsok.searchportal.result.SearchResult;
import no.schibstedsok.searchportal.util.Channels;
import no.schibstedsok.searchportal.util.ModifierDateComparator;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* This class provies an advanced fast search command with navigation
* capabilities.
*
* @author maek
*/
public class NavigatableESPFastCommand extends ESPFastSearchCommand {
// Attributes ----------------------------------------------------
private final Map<String, Navigator> navigatedTo = new HashMap<String, Navigator>();
private final Map<String, String[]> navigatedValues = new HashMap<String, String[]>();
public NavigatableESPFastCommand(final Context cxt) {
super(cxt);
}
public Collection createNavigationFilterStrings() {
final Collection<String> filterStrings = new ArrayList<String>();
for (String field : navigatedValues.keySet()) {
final String modifiers[] = navigatedValues.get(field);
for (String modifier : modifiers) {
if (!field.equals("contentsource") || !modifier.equals("Norske nyheter"))
filterStrings.add("+" + field + ":\"" + modifier + "\"");
}
}
return filterStrings;
}
public SearchResult execute() {
if (getNavigators() != null) {
for (String navigatorKey : getNavigators().keySet()) {
addNavigatedTo(navigatorKey, getParameters().containsKey("nav_" + navigatorKey)
? getParameter("nav_" + navigatorKey)
: null);
}
}
final FastSearchResult searchResult = (FastSearchResult) super.execute();
if (getNavigators() != null) {
collectModifiers(getIQueryResult(), searchResult);
}
return searchResult;
}
public Map getOtherNavigators(final String navigatorKey) {
final Map<String, String> otherNavigators = new HashMap<String, String>();
for (String parameterName : getParameters().keySet()) {
if (parameterName.startsWith("nav_") && !parameterName.substring(parameterName.indexOf('_') + 1).equals(navigatorKey)) {
final String paramValue = getParameter(parameterName);
otherNavigators.put(parameterName.substring(parameterName.indexOf('_') + 1), paramValue);
}
}
return otherNavigators;
}
public void addNavigatedTo(final String navigatorKey, final String navigatorName) {
final Navigator navigator = getNavigators().get(navigatorKey);
if (navigatorName == null) {
navigatedTo.put(navigatorKey, navigator);
} else {
navigatedTo.put(navigatorKey, findChildNavigator(navigator, navigatorName));
}
}
public Navigator getNavigatedTo(final String navigatorKey) {
return navigatedTo.get(navigatorKey);
}
public Navigator getParentNavigator(final String navigatorKey) {
if (getParameters().containsKey("nav_" + navigatorKey)) {
final String navName = getParameter("nav_" + navigatorKey);
return findParentNavigator(getNavigators().get(navigatorKey), navName);
} else {
return null;
}
}
public Navigator getParentNavigator(final String navigatorKey, final String name) {
if (getParameters().containsKey("nav_" + navigatorKey)) {
return findParentNavigator(getNavigators().get(navigatorKey), name);
} else {
return null;
}
}
public Navigator findParentNavigator(final Navigator navigator, final String navigatorName) {
if (navigator.getChildNavigator() == null) {
return null;
} else if (navigator.getChildNavigator().getName().equals(navigatorName)) {
return navigator;
} else {
return findParentNavigator(navigator.getChildNavigator(), navigatorName);
}
}
public Map getNavigatedValues() {
return navigatedValues;
}
public String getNavigatedValue(final String fieldName) {
final String[] singleValue = navigatedValues.get(fieldName);
if (singleValue != null) {
return (singleValue[0]);
} else {
return null;
}
}
public boolean isTopLevelNavigator(final String navigatorKey) {
return !getParameters().containsKey("nav_" + navigatorKey);
}
public Map getNavigatedTo() {
return navigatedTo;
}
public String getNavigatorTitle(final String navigatorKey) {
final Navigator nav = getNavigatedTo(navigatorKey);
Navigator parent = findParentNavigator(getNavigators().get(navigatorKey), nav.getName());
String value = getNavigatedValue(nav.getField());
if (value == null && parent != null) {
value = getNavigatedValue(parent.getField());
if (value == null) {
parent = findParentNavigator(getNavigators().get(navigatorKey), parent.getName());
if (parent != null) {
value = getNavigatedValue(parent.getField());
}
return value;
} else {
return value;
}
}
if (value == null) {
return nav.getDisplayName();
} else {
return value;
}
}
public String getNavigatorTitle(final Navigator navigator) {
final String value = getNavigatedValue(navigator.getField());
if (value == null) {
return navigator.getDisplayName();
} else {
return value;
}
}
/**
* Assured associated search configuration will always be of this type. *
*/
public NavigatableEspFastCommandConfig getSearchConfiguration() {
return (NavigatableEspFastCommandConfig) super.getSearchConfiguration();
}
public List getNavigatorBackLinks(final String navigatorKey) {
final List backLinks = addNavigatorBackLinks(getSearchConfiguration().getNavigator(navigatorKey), new ArrayList<Navigator>(), navigatorKey);
if (backLinks.size() > 0) {
backLinks.remove(backLinks.size() - 1);
}
return backLinks;
}
public List<Navigator> addNavigatorBackLinks(final Navigator navigator, final List<Navigator> links, final String navigatorKey) {
final String a = getParameter(navigator.getField());
if (a != null) {
if (!(navigator.getName().equals("ywfylkesnavigator") && a.equals("Oslo"))) {
if (!(navigator.getName().equals("ywkommunenavigator") && a.equals("Oslo"))) {
links.add(navigator);
}
}
}
if (navigator.getChildNavigator() != null) {
final String n = getParameter("nav_" + navigatorKey);
if (n != null && navigator.getName().equals(n)) {
return links;
}
addNavigatorBackLinks(navigator.getChildNavigator(), links, navigatorKey);
}
return links;
}
protected Map<String, Navigator> getNavigators() {
return getSearchConfiguration().getNavigators();
}
private void collectModifiers(IQueryResult result, FastSearchResult searchResult) {
for (String navigatorKey : navigatedTo.keySet()) {
collectModifier(navigatorKey, result, searchResult);
}
}
private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
INavigator navigator = result.getNavigator(nav.getName());
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
- case YEAR_MONTH:
- Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
- break;
+// case YEAR_MONTH:
+// Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
+// break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
private Navigator findChildNavigator(Navigator nav, String nameToFind) {
if (getParameters().containsKey(nav.getField())) {
navigatedValues.put(nav.getField(), getParameters().get(nav.getField()) instanceof String[]
? (String[]) getParameters().get(nav.getField())
: new String[]{getParameter(nav.getField())});
}
if (nav.getName().equals(nameToFind)) {
if (nav.getChildNavigator() != null) {
return nav.getChildNavigator();
} else {
return nav;
}
}
if (nav.getChildNavigator() == null) {
throw new RuntimeException("Navigator " + nameToFind + " not found.");
}
return findChildNavigator(nav.getChildNavigator(), nameToFind);
}
protected String getAdditionalFilter() {
final Collection navStrings = createNavigationFilterStrings();
if (getNavigators() != null) {
return StringUtils.join(navStrings.iterator(), " ");
} else {
return null;
}
}
}
| true | true | private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
INavigator navigator = result.getNavigator(nav.getName());
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
case YEAR_MONTH:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
| private void collectModifier(String navigatorKey, IQueryResult result, FastSearchResult searchResult) {
final Navigator nav = navigatedTo.get(navigatorKey);
INavigator navigator = result.getNavigator(nav.getName());
if (navigator != null) {
Iterator modifers = navigator.modifiers();
while (modifers.hasNext()) {
IModifier modifier = (IModifier) modifers.next();
if (!navigatedValues.containsKey(nav.getField()) || modifier.getName().equals(navigatedValues.get(nav.getField())[0])) {
Modifier mod = new Modifier(modifier.getName(), modifier.getCount(), nav);
searchResult.addModifier(navigatorKey, mod);
}
}
if (searchResult.getModifiers(navigatorKey) != null) {
switch (nav.getSort()) {
case CHANNEL:
final Channels channels = (Channels) getParameters().get("channels");
Collections.sort(searchResult.getModifiers(navigatorKey), channels.getComparator());
break;
case DAY_MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR);
break;
case DAY_MONTH_YEAR_DESCENDING:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.DAY_MONTH_YEAR_DESCENDING);
break;
case YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR);
break;
case MONTH_YEAR:
Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.MONTH_YEAR);
break;
// case YEAR_MONTH:
// Collections.sort(searchResult.getModifiers(navigatorKey), ModifierDateComparator.YEAR_MONTH);
// break;
case NONE:
// Use the soting the index returns
break;
case COUNT:
/* Fall through */
default:
Collections.sort(searchResult.getModifiers(navigatorKey));
break;
}
}
} else if (nav.getChildNavigator() != null) {
navigatedTo.put(navigatorKey, nav.getChildNavigator());
collectModifier(navigatorKey, result, searchResult);
}
}
|
diff --git a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
index a109622a..9be57920 100644
--- a/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
+++ b/wiki-service/src/main/java/org/exoplatform/wiki/service/impl/WikiSearchServiceConnector.java
@@ -1,293 +1,293 @@
package org.exoplatform.wiki.service.impl;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.exoplatform.commons.api.search.SearchServiceConnector;
import org.exoplatform.commons.api.search.data.SearchContext;
import org.exoplatform.commons.api.search.data.SearchResult;
import org.exoplatform.commons.utils.PageList;
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.portal.config.model.PortalConfig;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.wiki.mow.api.Wiki;
import org.exoplatform.wiki.mow.api.WikiNodeType;
import org.exoplatform.wiki.mow.api.WikiType;
import org.exoplatform.wiki.mow.core.api.wiki.AttachmentImpl;
import org.exoplatform.wiki.mow.core.api.wiki.PageImpl;
import org.exoplatform.wiki.service.WikiService;
import org.exoplatform.wiki.service.search.WikiSearchData;
import org.exoplatform.wiki.utils.Utils;
/**
* The WikiSearchServiceConnector provide a connector service for the common unified search.
* It implements a direct search in the jcr based on several criteria
*
* @LevelAPI Experimental
*/
public class WikiSearchServiceConnector extends SearchServiceConnector {
private static final Log LOG = ExoLogger.getLogger("org.exoplatform.wiki.service.impl.WikiSearchServiceConnector");
/**
* URL of the icon used in the unified search to represent the results
*/
public static final String WIKI_PAGE_ICON = "/wiki/skin/images/unified-search/PageIcon.png";
/**
* Date format expected by the unified search
*/
public static String DATE_TIME_FORMAT = "EEEEE, MMMMMMMM d, yyyy K:mm a";
private WikiService wikiService;
/**
* Initialise the wiki service connector
*
* @param initParams Parameters
*/
public WikiSearchServiceConnector(InitParams initParams) {
super(initParams);
wikiService = (WikiService) ExoContainerContext.getCurrentContainer().getComponentInstanceOfType(WikiService.class);
}
/**
* The connectors must implement this search method, with the following parameters and return a collection of SearchResult
*
* @param context Search context
* @param query The user-input query to search for
* @param sites Search on these specified sites only (e.g acme, intranet...)
* @param offset Start offset of the result set
* @param limit Maximum size of the result set
* @param sort The field to sort the result set
* @param order Sort order (ASC, DESC)
* @return a collection of SearchResult
*/
@Override
public Collection<SearchResult> search(SearchContext context, String query, Collection<String> sites, int offset, int limit, String sort, String order) {
// When limit is 0 then return all search result
if (limit == 0) {
limit = Integer.MAX_VALUE;
}
// Prepare search data
WikiSearchData searchData = new WikiSearchData(query, query, null, null);
searchData.setOffset(offset);
searchData.setLimit(limit);
// Execute the search
List<SearchResult> searchResults = new ArrayList<SearchResult>();
try {
PageList<org.exoplatform.wiki.service.search.SearchResult> wikiSearchPageList = wikiService.search(searchData);
if (wikiSearchPageList != null) {
List<org.exoplatform.wiki.service.search.SearchResult> wikiSearchResults = wikiSearchPageList.getAll();
for (org.exoplatform.wiki.service.search.SearchResult wikiSearchResult : wikiSearchResults) {
SearchResult searchResult = buildResult(context, wikiSearchResult);
if (searchResult != null) {
searchResults.add(searchResult);
}
}
}
} catch (Exception e) {
LOG.info("Could not execute unified seach on wiki" , e) ;
}
// Sort search result
sortSearchResult(searchResults, sort, order);
// Return the result
return searchResults;
}
/**
* Sort the results based on the order and labels
*
* @param searchResults The list of results
* @param sort Can be orderred by title, relevancy or date
* @param order ASC or DESC
*/
private void sortSearchResult(List<SearchResult> searchResults, String sort, String order) {
if (StringUtils.isEmpty(sort)) {
return;
}
if (StringUtils.isEmpty(order)) {
order = "ASC";
}
final String orderValue = order;
if ("title".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
- o1.getTitle().compareTo(o2.getTitle());
+ return o1.getTitle().compareTo(o2.getTitle());
}
return o2.getTitle().compareTo(o1.getTitle());
}
});
} else if ("relevancy".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
- return (int) (o1.getRelevancy() - o2.getRelevancy());
+ return Long.valueOf(o1.getRelevancy()).compareTo(Long.valueOf(o2.getRelevancy()));
}
- return (int) (o2.getRelevancy() - o1.getRelevancy());
+ return Long.valueOf(o2.getRelevancy()).compareTo(Long.valueOf(o1.getRelevancy()));
}
});
} else if ("date".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
- return (int) (o1.getDate() - o2.getDate());
+ return Long.valueOf(o1.getDate()).compareTo(Long.valueOf(o2.getDate()));
}
- return (int) (o2.getDate() - o1.getDate());
+ return Long.valueOf(o2.getDate()).compareTo(Long.valueOf(o1.getDate()));
}
});
}
}
/**
* Get the icon for the wiki pages
*
* @param wikiSearchResult A simple result from the search
* @return The url of the icon
*/
private String getResultIcon(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
return WIKI_PAGE_ICON;
}
/**
* Get all the information of the page result
*
* @param result A simple result from the search
* @return The page
* @throws Exception
*/
private PageImpl getPage(org.exoplatform.wiki.service.search.SearchResult result) throws Exception {
PageImpl page = null;
if (WikiNodeType.WIKI_PAGE_CONTENT.equals(result.getType()) || WikiNodeType.WIKI_ATTACHMENT.equals(result.getType())) {
AttachmentImpl searchContent = (AttachmentImpl) org.exoplatform.wiki.utils.Utils.getObject(result.getPath(), WikiNodeType.WIKI_ATTACHMENT);
page = searchContent.getParentPage();
} else if (WikiNodeType.WIKI_PAGE.equals(result.getType()) || WikiNodeType.WIKI_HOME.equals(result.getType())) {
page = (PageImpl) org.exoplatform.wiki.utils.Utils.getObject(result.getPath(), WikiNodeType.WIKI_PAGE);
}
return page;
}
/**
* Return the detail of the page based on the result
*
* @param wikiSearchResult A simple result from the search
* @return The detail of the result
*/
private String getPageDetail(org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
StringBuffer pageDetail = new StringBuffer();
try {
// Get space name
PageImpl page = getPage(wikiSearchResult);
String spaceName = "";
Wiki wiki = page.getWiki();
if (wiki.getType().equals(PortalConfig.GROUP_TYPE)) {
String wikiOwner = wiki.getOwner();
if (wikiOwner.indexOf('/') == -1) {
spaceName = wikiService.getSpaceNameByGroupId("/spaces/" + wiki.getOwner());
} else {
spaceName = wikiService.getSpaceNameByGroupId(wiki.getOwner());
}
} else {
spaceName = wiki.getOwner();
}
// Get update date
Calendar updateDate = wikiSearchResult.getUpdatedDate();
SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT);
// Build page detail
pageDetail.append(spaceName);
pageDetail.append(" - ");
pageDetail.append(format.format(updateDate.getTime()));
} catch (Exception e) {
LOG.info("Can not get page detail ", e);
}
return pageDetail.toString();
}
/**
* Return the permalink of the result from the search
*
* @param context Not Used
* @param wikiSearchResult A simple result from the search
* @return The permalink of the result
*/
private String getPagePermalink(SearchContext context, org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
StringBuffer permalink = new StringBuffer();
try {
PageImpl page = getPage(wikiSearchResult);
if (page.getWiki().getType().equalsIgnoreCase(WikiType.GROUP.toString())) {
String portalContainerName = Utils.getPortalName();
String portalOwner = context.getSiteName();
String wikiWebappUri = wikiService.getWikiWebappUri();
String spaceGroupId = page.getWiki().getOwner();
permalink.append("/");
permalink.append(portalContainerName);
permalink.append("/");
permalink.append(portalOwner);
permalink.append("/");
permalink.append(wikiWebappUri);
permalink.append("/");
permalink.append(PortalConfig.GROUP_TYPE);
permalink.append(spaceGroupId);
permalink.append("/");
permalink.append(page.getName());
} else {
String portalContainerName = Utils.getPortalName();
String url = page.getURL();
if (url != null) {
url = url.substring(url.indexOf("/" + portalContainerName + "/"));
permalink.append(url);
}
}
} catch (Exception ex) {
LOG.info("Can not build the permalink for wiki page ", ex);
}
return permalink.toString();
}
/**
* Format the result as expected by the unified search
*
* @param context The context url
* @param wikiSearchResult A simple result from the search
* @return A result formated
*/
private SearchResult buildResult(SearchContext context, org.exoplatform.wiki.service.search.SearchResult wikiSearchResult) {
try {
String title = wikiSearchResult.getTitle();
String url = getPagePermalink(context, wikiSearchResult);
String excerpt = wikiSearchResult.getExcerpt();
String detail = getPageDetail(wikiSearchResult);
long relevancy = wikiSearchResult.getJcrScore();
long date = wikiSearchResult.getUpdatedDate().getTime().getTime();
String imageUrl = getResultIcon(wikiSearchResult);
return new SearchResult(url, title, excerpt, detail, imageUrl, date, relevancy);
} catch (Exception e) {
LOG.info("Error when getting property from node ", e);
return null;
}
}
}
| false | true | private void sortSearchResult(List<SearchResult> searchResults, String sort, String order) {
if (StringUtils.isEmpty(sort)) {
return;
}
if (StringUtils.isEmpty(order)) {
order = "ASC";
}
final String orderValue = order;
if ("title".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
o1.getTitle().compareTo(o2.getTitle());
}
return o2.getTitle().compareTo(o1.getTitle());
}
});
} else if ("relevancy".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
return (int) (o1.getRelevancy() - o2.getRelevancy());
}
return (int) (o2.getRelevancy() - o1.getRelevancy());
}
});
} else if ("date".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
return (int) (o1.getDate() - o2.getDate());
}
return (int) (o2.getDate() - o1.getDate());
}
});
}
}
| private void sortSearchResult(List<SearchResult> searchResults, String sort, String order) {
if (StringUtils.isEmpty(sort)) {
return;
}
if (StringUtils.isEmpty(order)) {
order = "ASC";
}
final String orderValue = order;
if ("title".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
return o1.getTitle().compareTo(o2.getTitle());
}
return o2.getTitle().compareTo(o1.getTitle());
}
});
} else if ("relevancy".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
return Long.valueOf(o1.getRelevancy()).compareTo(Long.valueOf(o2.getRelevancy()));
}
return Long.valueOf(o2.getRelevancy()).compareTo(Long.valueOf(o1.getRelevancy()));
}
});
} else if ("date".equalsIgnoreCase(sort)) {
Collections.sort(searchResults, new Comparator<SearchResult>() {
@Override
public int compare(SearchResult o1, SearchResult o2) {
if ("ASC".equalsIgnoreCase(orderValue)) {
return Long.valueOf(o1.getDate()).compareTo(Long.valueOf(o2.getDate()));
}
return Long.valueOf(o2.getDate()).compareTo(Long.valueOf(o1.getDate()));
}
});
}
}
|
diff --git a/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetPersistentPresenceJabberImpl.java b/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetPersistentPresenceJabberImpl.java
index 717211046..7a7d9663d 100644
--- a/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetPersistentPresenceJabberImpl.java
+++ b/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetPersistentPresenceJabberImpl.java
@@ -1,1202 +1,1199 @@
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.util.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.jabberconstants.*;
import net.java.sip.communicator.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.util.StringUtils;
/**
* The Jabber implementation of a Persistent Presence Operation set. This class
* manages our own presence status as well as subscriptions for the presence
* status of our buddies. It also offers methods for retrieving and modifying
* the buddy contact list and adding listeners for changes in its layout.
*
* @author Damian Minkov
* @author Lubomir Marinov
*/
public class OperationSetPersistentPresenceJabberImpl
extends AbstractOperationSetPersistentPresence<
ProtocolProviderServiceJabberImpl>
{
/**
* The logger.
*/
private static final Logger logger =
Logger.getLogger(OperationSetPersistentPresenceJabberImpl.class);
/**
* Contains our current status message. Note that this field would only
* be changed once the server has confirmed the new status message and
* not immediately upon setting a new one..
*/
private String currentStatusMessage = "";
/**
* The presence status that we were last notified of entering.
* The initial one is OFFLINE
*/
private PresenceStatus currentStatus;
/**
* A map containing bindings between SIP Communicator's jabber presence
* status instances and Jabber status codes
*/
private static Map<String, Presence.Mode> scToJabberModesMappings
= new Hashtable<String, Presence.Mode>();
static
{
scToJabberModesMappings.put(JabberStatusEnum.AWAY,
Presence.Mode.away);
scToJabberModesMappings.put(JabberStatusEnum.ON_THE_PHONE,
Presence.Mode.away);
scToJabberModesMappings.put(JabberStatusEnum.EXTENDED_AWAY,
Presence.Mode.xa);
scToJabberModesMappings.put(JabberStatusEnum.DO_NOT_DISTURB,
Presence.Mode.dnd);
scToJabberModesMappings.put(JabberStatusEnum.FREE_FOR_CHAT,
Presence.Mode.chat);
scToJabberModesMappings.put(JabberStatusEnum.AVAILABLE,
Presence.Mode.available);
}
/**
* The server stored contact list that will be encapsulating smack's
* buddy list.
*/
private final ServerStoredContactListJabberImpl ssContactList;
/**
* Listens for subscriptions.
*/
private JabberSubscriptionListener subscribtionPacketListener = null;
/**
* Current resource priority. 10 is default value.
*/
private int resourcePriority = 10;
/**
* Manages statuses and different user resources.
*/
private ContactChangesListener contactChangesListener = null;
/**
* Creates the OperationSet.
* @param provider the parent provider.
*/
public OperationSetPersistentPresenceJabberImpl(
ProtocolProviderServiceJabberImpl provider)
{
super(provider);
currentStatus =
parentProvider.getJabberStatusEnum().getStatus(
JabberStatusEnum.OFFLINE);
ssContactList = new ServerStoredContactListJabberImpl( this , provider);
parentProvider.addRegistrationStateChangeListener(
new RegistrationStateListener());
}
/**
* Registers a listener that would receive events upon changes in server
* stored groups.
*
* @param listener a ServerStoredGroupChangeListener impl that would
* receive events upon group changes.
*/
public void addServerStoredGroupChangeListener(ServerStoredGroupListener
listener)
{
ssContactList.addGroupListener(listener);
}
/**
* Creates a group with the specified name and parent in the server
* stored contact list.
*
* @param parent the group where the new group should be created
* @param groupName the name of the new group to create.
* @throws OperationFailedException if such group already exists
*/
public void createServerStoredContactGroup(ContactGroup parent,
String groupName)
throws OperationFailedException
{
assertConnected();
if (!parent.canContainSubgroups())
throw new IllegalArgumentException(
"The specified contact group cannot contain child groups. Group:"
+ parent );
ssContactList.createGroup(groupName);
}
/**
* Creates a non persistent contact for the specified address. This would
* also create (if necessary) a group for volatile contacts that would not
* be added to the server stored contact list. The volatile contact would
* remain in the list until it is really added to the contact list or
* until the application is terminated.
* @param id the address of the contact to create.
* @return the newly created volatile <tt>ContactImpl</tt>
*/
public ContactJabberImpl createVolatileContact(String id)
{
return ssContactList.createVolatileContact(id);
}
/**
* Creates and returns a unresolved contact from the specified
* <tt>address</tt> and <tt>persistentData</tt>.
*
* @param address an identifier of the contact that we'll be creating.
* @param persistentData a String returned Contact's getPersistentData()
* method during a previous run and that has been persistently stored
* locally.
* @param parentGroup the group where the unresolved contact is supposed
* to belong to.
* @return the unresolved <tt>Contact</tt> created from the specified
* <tt>address</tt> and <tt>persistentData</tt>
*/
public Contact createUnresolvedContact(String address,
String persistentData,
ContactGroup parentGroup)
{
if(! (parentGroup instanceof ContactGroupJabberImpl ||
parentGroup instanceof RootContactGroupJabberImpl) )
throw new IllegalArgumentException(
"Argument is not an jabber contact group (group="
+ parentGroup + ")");
ContactJabberImpl contact =
ssContactList.createUnresolvedContact(parentGroup, address);
contact.setPersistentData(persistentData);
return contact;
}
/**
* Creates and returns a unresolved contact from the specified
* <tt>address</tt> and <tt>persistentData</tt>.
*
* @param address an identifier of the contact that we'll be creating.
* @param persistentData a String returned Contact's getPersistentData()
* method during a previous run and that has been persistently stored
* locally.
* @return the unresolved <tt>Contact</tt> created from the specified
* <tt>address</tt> and <tt>persistentData</tt>
*/
public Contact createUnresolvedContact(String address,
String persistentData)
{
return createUnresolvedContact( address
, persistentData
, getServerStoredContactListRoot());
}
/**
* Creates and returns a unresolved contact group from the specified
* <tt>address</tt> and <tt>persistentData</tt>.
*
* @param groupUID an identifier, returned by ContactGroup's
* getGroupUID, that the protocol provider may use in order to create
* the group.
* @param persistentData a String returned ContactGroups's
* getPersistentData() method during a previous run and that has been
* persistently stored locally.
* @param parentGroup the group under which the new group is to be
* created or null if this is group directly underneath the root.
* @return the unresolved <tt>ContactGroup</tt> created from the
* specified <tt>uid</tt> and <tt>persistentData</tt>
*/
public ContactGroup createUnresolvedContactGroup(String groupUID,
String persistentData, ContactGroup parentGroup)
{
return ssContactList.createUnresolvedContactGroup(groupUID);
}
/**
* Returns a reference to the contact with the specified ID in case we
* have a subscription for it and null otherwise/
*
* @param contactID a String identifier of the contact which we're
* seeking a reference of.
* @return a reference to the Contact with the specified
* <tt>contactID</tt> or null if we don't have a subscription for the
* that identifier.
*/
public Contact findContactByID(String contactID)
{
return ssContactList.findContactById(contactID);
}
/**
* Returns the status message that was confirmed by the serfver
*
* @return the last status message that we have requested and the aim
* server has confirmed.
*/
public String getCurrentStatusMessage()
{
return currentStatusMessage;
}
/**
* Returns the protocol specific contact instance representing the local
* user.
*
* @return the Contact (address, phone number, or uin) that the Provider
* implementation is communicating on behalf of.
*/
public Contact getLocalContact()
{
return null;
}
/**
* Returns a PresenceStatus instance representing the state this provider
* is currently in.
*
* @return the PresenceStatus last published by this provider.
*/
public PresenceStatus getPresenceStatus()
{
return currentStatus;
}
/**
* Returns the root group of the server stored contact list.
*
* @return the root ContactGroup for the ContactList stored by this
* service.
*/
public ContactGroup getServerStoredContactListRoot()
{
return ssContactList.getRootGroup();
}
/**
* Returns the set of PresenceStatus objects that a user of this service
* may request the provider to enter.
*
* @return Iterator a PresenceStatus array containing "enterable" status
* instances.
*/
public Iterator<PresenceStatus> getSupportedStatusSet()
{
return parentProvider.getJabberStatusEnum().getSupportedStatusSet();
}
/**
* Removes the specified contact from its current parent and places it
* under <tt>newParent</tt>.
*
* @param contactToMove the <tt>Contact</tt> to move
* @param newParent the <tt>ContactGroup</tt> where <tt>Contact</tt>
* would be placed.
*/
public void moveContactToGroup(Contact contactToMove,
ContactGroup newParent)
{
assertConnected();
if( !(contactToMove instanceof ContactJabberImpl) )
throw new IllegalArgumentException(
"The specified contact is not an jabber contact." +
contactToMove);
if( !(newParent instanceof ContactGroupJabberImpl) )
throw new IllegalArgumentException(
"The specified group is not an jabber contact group."
+ newParent);
ssContactList.moveContact((ContactJabberImpl)contactToMove,
(ContactGroupJabberImpl)newParent);
}
/**
* Requests the provider to enter into a status corresponding to the
* specified parameters.
*
* @param status the PresenceStatus as returned by
* getRequestableStatusSet
* @param statusMessage the message that should be set as the reason to
* enter that status
* @throws IllegalArgumentException if the status requested is not a
* valid PresenceStatus supported by this provider.
* @throws IllegalStateException if the provider is not currently
* registered.
* @throws OperationFailedException with code NETWORK_FAILURE if
* publishing the status fails due to a network error.
*/
public void publishPresenceStatus(PresenceStatus status,
String statusMessage)
throws IllegalArgumentException,
IllegalStateException,
OperationFailedException
{
assertConnected();
JabberStatusEnum jabberStatusEnum =
parentProvider.getJabberStatusEnum();
boolean isValidStatus = false;
for (Iterator<PresenceStatus> supportedStatusIter
= jabberStatusEnum.getSupportedStatusSet();
supportedStatusIter.hasNext();)
{
if (supportedStatusIter.next().equals(status))
{
isValidStatus = true;
break;
}
}
if (!isValidStatus)
throw new IllegalArgumentException(status
+ " is not a valid Jabber status");
if (status.equals(jabberStatusEnum.getStatus(JabberStatusEnum.OFFLINE)))
{
parentProvider.unregister();
}
else
{
Presence presence = new Presence(Presence.Type.available);
presence.setMode(presenceStatusToJabberMode(status));
presence.setPriority(resourcePriority);
// on the phone is a special status which is away
// with custom status message
if(status.equals(jabberStatusEnum.getStatus(
JabberStatusEnum.ON_THE_PHONE)))
{
presence.setStatus(JabberStatusEnum.ON_THE_PHONE);
}
else
presence.setStatus(statusMessage);
//presence.addExtension(new Version());
parentProvider.getConnection().sendPacket(presence);
}
fireProviderStatusChangeEvent(currentStatus, status);
if(!getCurrentStatusMessage().equals(statusMessage))
{
String oldStatusMessage = getCurrentStatusMessage();
currentStatusMessage = statusMessage;
fireProviderStatusMessageChangeEvent(oldStatusMessage,
getCurrentStatusMessage());
}
}
/**
* Gets the <tt>PresenceStatus</tt> of a contact with a specific
* <tt>String</tt> identifier.
*
* @param contactIdentifier the identifier of the contact whose status we're
* interested in.
* @return the <tt>PresenceStatus</tt> of the contact with the specified
* <tt>contactIdentifier</tt>
* @throws IllegalArgumentException if the specified
* <tt>contactIdentifier</tt> does not identify a contact known to the
* underlying protocol provider
* @throws IllegalStateException if the underlying protocol provider is not
* registered/signed on a public service
* @throws OperationFailedException with code NETWORK_FAILURE if retrieving
* the status fails due to errors experienced during network communication
*/
public PresenceStatus queryContactStatus(String contactIdentifier)
throws IllegalArgumentException,
IllegalStateException,
OperationFailedException
{
/*
* As stated by the javadoc, IllegalStateException signals that the
* ProtocolProviderService is not registered.
*/
assertConnected();
XMPPConnection xmppConnection = parentProvider.getConnection();
if (xmppConnection == null)
{
throw
new IllegalArgumentException(
"The provider/account must be signed on in order to"
+ " query the status of a contact in its roster");
}
Presence presence
= xmppConnection.getRoster().getPresence(contactIdentifier);
if(presence != null)
return jabberStatusToPresenceStatus(presence, parentProvider);
else
{
return
parentProvider.getJabberStatusEnum().getStatus(
JabberStatusEnum.OFFLINE);
}
}
/**
* Removes the specified group from the server stored contact list.
*
* @param group the group to remove.
*/
public void removeServerStoredContactGroup(ContactGroup group)
{
assertConnected();
if( !(group instanceof ContactGroupJabberImpl) )
throw new IllegalArgumentException(
"The specified group is not an jabber contact group: " + group);
ssContactList.removeGroup(((ContactGroupJabberImpl)group));
}
/**
* Removes the specified group change listener so that it won't receive
* any further events.
*
* @param listener the ServerStoredGroupChangeListener to remove
*/
public void removeServerStoredGroupChangeListener(ServerStoredGroupListener
listener)
{
ssContactList.removeGroupListener(listener);
}
/**
* Renames the specified group from the server stored contact list.
*
* @param group the group to rename.
* @param newName the new name of the group.
*/
public void renameServerStoredContactGroup(ContactGroup group,
String newName)
{
assertConnected();
if( !(group instanceof ContactGroupJabberImpl) )
throw new IllegalArgumentException(
"The specified group is not an jabber contact group: " + group);
ssContactList.renameGroup((ContactGroupJabberImpl)group, newName);
}
/**
* Handler for incoming authorization requests.
*
* @param handler an instance of an AuthorizationHandler for
* authorization requests coming from other users requesting
* permission add us to their contact list.
*/
public void setAuthorizationHandler(AuthorizationHandler handler)
{
if(subscribtionPacketListener == null)
{
subscribtionPacketListener = new JabberSubscriptionListener();
parentProvider
.getConnection()
.addPacketListener(
subscribtionPacketListener,
new PacketTypeFilter(Presence.class));
}
subscribtionPacketListener.handler = handler;
}
/**
* Persistently adds a subscription for the presence status of the
* contact corresponding to the specified contactIdentifier and indicates
* that it should be added to the specified group of the server stored
* contact list.
*
* @param parent the parent group of the server stored contact list
* where the contact should be added. <p>
* @param contactIdentifier the contact whose status updates we are
* subscribing for.
* @throws IllegalArgumentException if <tt>contact</tt> or
* <tt>parent</tt> are not a contact known to the underlying protocol
* provider.
* @throws IllegalStateException if the underlying protocol provider is
* not registered/signed on a public service.
* @throws OperationFailedException with code NETWORK_FAILURE if
* subscribing fails due to errors experienced during network
* communication
*/
public void subscribe(ContactGroup parent, String contactIdentifier)
throws IllegalArgumentException, IllegalStateException,
OperationFailedException
{
assertConnected();
if(! (parent instanceof ContactGroupJabberImpl) )
throw new IllegalArgumentException(
"Argument is not an jabber contact group (group="
+ parent + ")");
ssContactList.addContact(
(ContactGroupJabberImpl)parent, contactIdentifier);
}
/**
* Adds a subscription for the presence status of the contact
* corresponding to the specified contactIdentifier.
*
* @param contactIdentifier the identifier of the contact whose status
* updates we are subscribing for. <p>
* @throws IllegalArgumentException if <tt>contact</tt> is not a contact
* known to the underlying protocol provider
* @throws IllegalStateException if the underlying protocol provider is
* not registered/signed on a public service.
* @throws OperationFailedException with code NETWORK_FAILURE if
* subscribing fails due to errors experienced during network
* communication
*/
public void subscribe(String contactIdentifier) throws
IllegalArgumentException, IllegalStateException,
OperationFailedException
{
assertConnected();
ssContactList.addContact(contactIdentifier);
}
/**
* Removes a subscription for the presence status of the specified
* contact.
*
* @param contact the contact whose status updates we are unsubscribing
* from.
* @throws IllegalArgumentException if <tt>contact</tt> is not a contact
* known to the underlying protocol provider
* @throws IllegalStateException if the underlying protocol provider is
* not registered/signed on a public service.
* @throws OperationFailedException with code NETWORK_FAILURE if
* unsubscribing fails due to errors experienced during network
* communication
*/
public void unsubscribe(Contact contact) throws IllegalArgumentException,
IllegalStateException, OperationFailedException
{
assertConnected();
if(! (contact instanceof ContactJabberImpl) )
throw new IllegalArgumentException(
"Argument is not an jabber contact (contact=" + contact + ")");
ssContactList.removeContact((ContactJabberImpl)contact);
}
/**
* Converts the specified jabber status to one of the status fields of the
* JabberStatusEnum class.
*
* @param presence the Jabber Status
* @param jabberProvider the parent provider.
* @return a PresenceStatus instance representation of the Jabber Status
* parameter. The returned result is one of the JabberStatusEnum fields.
*/
public static PresenceStatus jabberStatusToPresenceStatus(
Presence presence, ProtocolProviderServiceJabberImpl jabberProvider)
{
JabberStatusEnum jabberStatusEnum =
jabberProvider.getJabberStatusEnum();
// fixing issue: 336
// from the smack api :
// A null presence mode value is interpreted to be the same thing
// as Presence.Mode.available.
if(presence.getMode() == null && presence.isAvailable())
return jabberStatusEnum.getStatus(JabberStatusEnum.AVAILABLE);
else if(presence.getMode() == null && !presence.isAvailable())
return jabberStatusEnum.getStatus(JabberStatusEnum.OFFLINE);
Presence.Mode mode = presence.getMode();
if(mode.equals(Presence.Mode.available))
return jabberStatusEnum.getStatus(JabberStatusEnum.AVAILABLE);
else if(mode.equals(Presence.Mode.away))
{
// on the phone a special status
// which is away with custom status message
if(presence.getStatus() != null
&& presence.getStatus().contains(JabberStatusEnum.ON_THE_PHONE))
return jabberStatusEnum.getStatus(JabberStatusEnum.ON_THE_PHONE);
else
return jabberStatusEnum.getStatus(JabberStatusEnum.AWAY);
}
else if(mode.equals(Presence.Mode.chat))
return jabberStatusEnum.getStatus(JabberStatusEnum.FREE_FOR_CHAT);
else if(mode.equals(Presence.Mode.dnd))
return jabberStatusEnum.getStatus(JabberStatusEnum.DO_NOT_DISTURB);
else if(mode.equals(Presence.Mode.xa))
return jabberStatusEnum.getStatus(JabberStatusEnum.EXTENDED_AWAY);
else
{
//unknown status
if(presence.isAway())
return jabberStatusEnum.getStatus(JabberStatusEnum.AWAY);
if(presence.isAvailable())
return jabberStatusEnum.getStatus(JabberStatusEnum.AVAILABLE);
return jabberStatusEnum.getStatus(JabberStatusEnum.OFFLINE);
}
}
/**
* Converts the specified JabberStatusEnum member to the corresponding
* Jabber Mode
*
* @param status the jabberStatus
* @return a PresenceStatus instance
*/
public static Presence.Mode presenceStatusToJabberMode(
PresenceStatus status)
{
return scToJabberModesMappings.get(status
.getStatusName());
}
/**
* Utility method throwing an exception if the stack is not properly
* initialized.
*
* @throws IllegalStateException if the underlying stack is not registered
* and initialized.
*/
void assertConnected()
throws IllegalStateException
{
if (parentProvider == null)
{
throw
new IllegalStateException(
"The provider must be non-null and signed on the"
+ " Jabber service before being able to"
+ " communicate.");
}
if (!parentProvider.isRegistered())
{
// if we are not registered but the current status is online
// change the current status
if((currentStatus != null) && currentStatus.isOnline())
{
fireProviderStatusChangeEvent(
currentStatus,
parentProvider.getJabberStatusEnum().getStatus(
JabberStatusEnum.OFFLINE));
}
throw
new IllegalStateException(
"The provider must be signed on the Jabber service"
+ " before being able to communicate.");
}
}
/**
* Fires provider status change.
*
* @param oldStatus old status
* @param newStatus new status
*/
public void fireProviderStatusChangeEvent(
PresenceStatus oldStatus,
PresenceStatus newStatus)
{
if (!oldStatus.equals(newStatus))
{
currentStatus = newStatus;
super.fireProviderStatusChangeEvent(oldStatus, newStatus);
PresenceStatus offlineStatus =
parentProvider.getJabberStatusEnum().getStatus(
JabberStatusEnum.OFFLINE);
if(newStatus.equals(offlineStatus))
{
//send event notifications saying that all our buddies are
//offline. The protocol does not implement top level buddies
//nor subgroups for top level groups so a simple nested loop
//would be enough.
Iterator<ContactGroup> groupsIter =
getServerStoredContactListRoot().subgroups();
while(groupsIter.hasNext())
{
ContactGroup group = groupsIter.next();
Iterator<Contact> contactsIter = group.contacts();
while(contactsIter.hasNext())
{
ContactJabberImpl contact
= (ContactJabberImpl)contactsIter.next();
PresenceStatus oldContactStatus
= contact.getPresenceStatus();
if(!oldContactStatus.isOnline())
continue;
contact.updatePresenceStatus(offlineStatus);
fireContactPresenceStatusChangeEvent(
contact,
contact.getParentContactGroup(),
oldContactStatus,
offlineStatus);
}
}
//do the same for all contacts in the root group
Iterator<Contact> contactsIter
= getServerStoredContactListRoot().contacts();
while (contactsIter.hasNext())
{
ContactJabberImpl contact
= (ContactJabberImpl) contactsIter.next();
PresenceStatus oldContactStatus
= contact.getPresenceStatus();
if (!oldContactStatus.isOnline())
continue;
contact.updatePresenceStatus(offlineStatus);
fireContactPresenceStatusChangeEvent(
contact
, contact.getParentContactGroup()
, oldContactStatus, offlineStatus);
}
}
}
}
/**
* Sets the display name for <tt>contact</tt> to be <tt>newName</tt>.
* <p>
* @param contact the <tt>Contact</tt> that we are renaming
* @param newName a <tt>String</tt> containing the new display name for
* <tt>metaContact</tt>.
* @throws IllegalArgumentException if <tt>contact</tt> is not an
* instance that belongs to the underlying implementation.
*/
public void setDisplayName(Contact contact, String newName)
throws IllegalArgumentException
{
assertConnected();
if(! (contact instanceof ContactJabberImpl) )
throw new IllegalArgumentException(
"Argument is not an jabber contact (contact=" + contact + ")");
((ContactJabberImpl)contact).getSourceEntry().setName(newName);
}
/**
* Our listener that will tell us when we're registered to server
* and is ready to accept us as a listener.
*/
private class RegistrationStateListener
implements RegistrationStateChangeListener
{
/**
* The method is called by a ProtocolProvider implementation whenever
* a change in the registration state of the corresponding provider had
* occurred.
* @param evt ProviderStatusChangeEvent the event describing the status
* change.
*/
public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
if (logger.isDebugEnabled())
logger.debug("The Jabber provider changed state from: "
+ evt.getOldState()
+ " to: " + evt.getNewState());
if(evt.getNewState() == RegistrationState.REGISTERED)
{
contactChangesListener = new ContactChangesListener();
parentProvider.getConnection().getRoster()
.addRosterListener(contactChangesListener);
fireProviderStatusChangeEvent(
currentStatus,
parentProvider
.getJabberStatusEnum()
.getStatus(JabberStatusEnum.AVAILABLE));
// init ssList
ssContactList.init();
}
else if(evt.getNewState() == RegistrationState.UNREGISTERED
|| evt.getNewState() == RegistrationState.AUTHENTICATION_FAILED
|| evt.getNewState() == RegistrationState.CONNECTION_FAILED)
{
//since we are disconnected, we won't receive any further status
//updates so we need to change by ourselves our own status as
//well as set to offline all contacts in our contact list that
//were online
PresenceStatus oldStatus = currentStatus;
PresenceStatus offlineStatus =
parentProvider.getJabberStatusEnum().getStatus(
JabberStatusEnum.OFFLINE);
currentStatus = offlineStatus;
fireProviderStatusChangeEvent(oldStatus, currentStatus);
ssContactList.cleanup();
subscribtionPacketListener = null;
if(parentProvider.getConnection() != null &&
parentProvider.getConnection().getRoster() != null)
parentProvider.getConnection().getRoster()
.removeRosterListener(contactChangesListener);
contactChangesListener = null;
}
}
}
/**
* Fires the status change, respecting resource priorities.
* @param presence the presence changed.
*/
void firePresenceStatusChanged(Presence presence)
{
if(contactChangesListener != null)
contactChangesListener.firePresenceStatusChanged(presence);
}
/**
* Manage changes of statuses by resource.
*/
private class ContactChangesListener
implements RosterListener
{
/**
* Map containing all statuses for a userID.
*/
private final Map<String, TreeSet<Presence>> statuses =
new Hashtable<String, TreeSet<Presence>>();
/**
* Not used here.
* @param addresses list of addresses added
*/
public void entriesAdded(Collection<String> addresses)
{}
/**
* Not used here.
* @param addresses list of addresses updated
*/
public void entriesUpdated(Collection<String> addresses)
{}
/**
* Not used here.
* @param addresses list of addresses deleted
*/
public void entriesDeleted(Collection<String> addresses)
{}
/**
* Received on resource status change.
* @param presence presence that has changed
*/
public void presenceChanged(Presence presence)
{
firePresenceStatusChanged(presence);
}
/**
* Fires the status change, respecting resource priorities.
*
* @param presence the presence changed.
*/
void firePresenceStatusChanged(Presence presence)
{
try
{
String userID
= StringUtils.parseBareAddress(presence.getFrom());
if (logger.isDebugEnabled())
logger.debug("Received a status update for buddy=" + userID);
// all contact statuses that are received from all its resources
- // ordered by priority
+ // ordered by priority(higher first) and those with equal
+ // priorities order with the one that is most connected as
+ // first
TreeSet<Presence> userStats = statuses.get(userID);
if(userStats == null)
{
userStats = new TreeSet<Presence>(new Comparator<Presence>()
{
public int compare(Presence o1, Presence o2)
{
- int res = o1.getPriority() - o2.getPriority();
+ int res = o2.getPriority() - o1.getPriority();
// if statuses are with same priorities
// return which one is more available
// counts the JabberStatusEnum order
if(res == 0)
{
- res =
- jabberStatusToPresenceStatus(
- o1,
- parentProvider)
- .getStatus()
- - jabberStatusToPresenceStatus(
- o2,
- parentProvider)
- .getStatus();
+ res = jabberStatusToPresenceStatus(
+ o2, parentProvider).getStatus()
+ - jabberStatusToPresenceStatus(
+ o1, parentProvider).getStatus();
}
return res;
}
});
statuses.put(userID, userStats);
}
else
{
String resource = StringUtils.parseResource(
presence.getFrom());
// remove the status for this resource
// if we are online we will update its value with the new
// status
for (Iterator<Presence> iter = userStats.iterator();
iter.hasNext();)
{
Presence p = iter.next();
if (StringUtils.parseResource(p.getFrom()).equals(
resource))
iter.remove();
}
}
if(!jabberStatusToPresenceStatus(presence, parentProvider)
.equals(
parentProvider
.getJabberStatusEnum()
.getStatus(JabberStatusEnum.OFFLINE)))
{
userStats.add(presence);
}
Presence currentPresence;
if (userStats.size() == 0)
{
currentPresence = presence;
/*
* We no longer have statuses for userID so it doesn't make
* sense to retain (1) the TreeSet and (2) its slot in the
* statuses Map.
*/
statuses.remove(userID);
}
else
currentPresence = userStats.first();
ContactJabberImpl sourceContact
= ssContactList.findContactById(userID);
if (sourceContact == null)
{
logger.warn("No source contact found for id=" + userID);
return;
}
// statuses may be the same and only change in status message
sourceContact.setStatusMessage(currentPresence.getStatus());
PresenceStatus oldStatus
= sourceContact.getPresenceStatus();
PresenceStatus newStatus
= jabberStatusToPresenceStatus(
currentPresence,
parentProvider);
// when old and new status are the same do nothing
// no change
if(oldStatus.equals(newStatus))
return;
sourceContact.updatePresenceStatus(newStatus);
ContactGroup parent
= ssContactList.findContactGroup(sourceContact);
if (logger.isDebugEnabled())
logger.debug("Will Dispatch the contact status event.");
fireContactPresenceStatusChangeEvent(sourceContact, parent,
oldStatus, newStatus);
}
catch (IllegalStateException ex)
{
logger.error("Failed changing status", ex);
}
catch (IllegalArgumentException ex)
{
logger.error("Failed changing status", ex);
}
}
}
/**
* Listens for subscription events coming from stack.
*/
private class JabberSubscriptionListener
implements PacketListener
{
/**
* The authorization handler.
*/
AuthorizationHandler handler = null;
/**
* Process packets.
* @param packet packet received to be processed
*/
public void processPacket(Packet packet)
{
Presence presence = (Presence) packet;
if (presence == null)
return;
Presence.Type presenceType = presence.getType();
final String fromID = presence.getFrom();
if (presenceType == Presence.Type.subscribe)
{
// run waiting for user response in different thread
// as this seems to block the packet dispatch thread
// and we don't receive anything till we unblock it
new Thread(new Runnable() {
public void run()
{
if (logger.isTraceEnabled())
{
logger.trace(
fromID
+ " wants to add you to its contact list");
}
// buddy want to add you to its roster
ContactJabberImpl srcContact
= ssContactList.findContactById(fromID);
if(srcContact == null)
srcContact = createVolatileContact(fromID);
AuthorizationRequest req = new AuthorizationRequest();
AuthorizationResponse response
= handler.processAuthorisationRequest(req, srcContact);
Presence.Type responsePresenceType;
if(response != null
&& response.getResponseCode()
.equals(AuthorizationResponse.ACCEPT))
{
responsePresenceType = Presence.Type.subscribed;
if (logger.isInfoEnabled())
logger.info("Sending Accepted Subscription");
}
else
{
responsePresenceType = Presence.Type.unsubscribed;
if (logger.isInfoEnabled())
logger.info("Sending Rejected Subscription");
}
Presence responsePacket = new Presence(
responsePresenceType);
responsePacket.setTo(fromID);
parentProvider.getConnection().sendPacket(responsePacket);
}}).start();
}
else if (presenceType == Presence.Type.unsubscribed)
{
if (logger.isTraceEnabled())
logger.trace(fromID + " does not allow your subscription");
ContactJabberImpl contact
= ssContactList.findContactById(fromID);
if(contact != null)
{
AuthorizationResponse response
= new AuthorizationResponse(
AuthorizationResponse.REJECT,
"");
handler.processAuthorizationResponse(response, contact);
try{
ssContactList.removeContact(contact);
}
catch(OperationFailedException e)
{
logger.error(
"Cannot remove contact that unsubscribed.");
}
}
}
else if (presenceType == Presence.Type.subscribed)
{
ContactJabberImpl contact
= ssContactList.findContactById(fromID);
AuthorizationResponse response
= new AuthorizationResponse(
AuthorizationResponse.ACCEPT,
"");
handler.processAuthorizationResponse(response, contact);
}
}
}
/**
* Returns the jabber account resource priority property value.
*
* @return the jabber account resource priority property value
*/
public int getResourcePriority()
{
return resourcePriority;
}
/**
* Updates the jabber account resource priority property value.
*
* @param resourcePriority the new priority to set
*/
public void setResourcePriority(int resourcePriority)
{
this.resourcePriority = resourcePriority;
}
}
| false | true | void firePresenceStatusChanged(Presence presence)
{
try
{
String userID
= StringUtils.parseBareAddress(presence.getFrom());
if (logger.isDebugEnabled())
logger.debug("Received a status update for buddy=" + userID);
// all contact statuses that are received from all its resources
// ordered by priority
TreeSet<Presence> userStats = statuses.get(userID);
if(userStats == null)
{
userStats = new TreeSet<Presence>(new Comparator<Presence>()
{
public int compare(Presence o1, Presence o2)
{
int res = o1.getPriority() - o2.getPriority();
// if statuses are with same priorities
// return which one is more available
// counts the JabberStatusEnum order
if(res == 0)
{
res =
jabberStatusToPresenceStatus(
o1,
parentProvider)
.getStatus()
- jabberStatusToPresenceStatus(
o2,
parentProvider)
.getStatus();
}
return res;
}
});
statuses.put(userID, userStats);
}
else
{
String resource = StringUtils.parseResource(
presence.getFrom());
// remove the status for this resource
// if we are online we will update its value with the new
// status
for (Iterator<Presence> iter = userStats.iterator();
iter.hasNext();)
{
Presence p = iter.next();
if (StringUtils.parseResource(p.getFrom()).equals(
resource))
iter.remove();
}
}
if(!jabberStatusToPresenceStatus(presence, parentProvider)
.equals(
parentProvider
.getJabberStatusEnum()
.getStatus(JabberStatusEnum.OFFLINE)))
{
userStats.add(presence);
}
Presence currentPresence;
if (userStats.size() == 0)
{
currentPresence = presence;
/*
* We no longer have statuses for userID so it doesn't make
* sense to retain (1) the TreeSet and (2) its slot in the
* statuses Map.
*/
statuses.remove(userID);
}
else
currentPresence = userStats.first();
ContactJabberImpl sourceContact
= ssContactList.findContactById(userID);
if (sourceContact == null)
{
logger.warn("No source contact found for id=" + userID);
return;
}
// statuses may be the same and only change in status message
sourceContact.setStatusMessage(currentPresence.getStatus());
PresenceStatus oldStatus
= sourceContact.getPresenceStatus();
PresenceStatus newStatus
= jabberStatusToPresenceStatus(
currentPresence,
parentProvider);
// when old and new status are the same do nothing
// no change
if(oldStatus.equals(newStatus))
return;
sourceContact.updatePresenceStatus(newStatus);
ContactGroup parent
= ssContactList.findContactGroup(sourceContact);
if (logger.isDebugEnabled())
logger.debug("Will Dispatch the contact status event.");
fireContactPresenceStatusChangeEvent(sourceContact, parent,
oldStatus, newStatus);
}
catch (IllegalStateException ex)
{
logger.error("Failed changing status", ex);
}
catch (IllegalArgumentException ex)
{
logger.error("Failed changing status", ex);
}
}
| void firePresenceStatusChanged(Presence presence)
{
try
{
String userID
= StringUtils.parseBareAddress(presence.getFrom());
if (logger.isDebugEnabled())
logger.debug("Received a status update for buddy=" + userID);
// all contact statuses that are received from all its resources
// ordered by priority(higher first) and those with equal
// priorities order with the one that is most connected as
// first
TreeSet<Presence> userStats = statuses.get(userID);
if(userStats == null)
{
userStats = new TreeSet<Presence>(new Comparator<Presence>()
{
public int compare(Presence o1, Presence o2)
{
int res = o2.getPriority() - o1.getPriority();
// if statuses are with same priorities
// return which one is more available
// counts the JabberStatusEnum order
if(res == 0)
{
res = jabberStatusToPresenceStatus(
o2, parentProvider).getStatus()
- jabberStatusToPresenceStatus(
o1, parentProvider).getStatus();
}
return res;
}
});
statuses.put(userID, userStats);
}
else
{
String resource = StringUtils.parseResource(
presence.getFrom());
// remove the status for this resource
// if we are online we will update its value with the new
// status
for (Iterator<Presence> iter = userStats.iterator();
iter.hasNext();)
{
Presence p = iter.next();
if (StringUtils.parseResource(p.getFrom()).equals(
resource))
iter.remove();
}
}
if(!jabberStatusToPresenceStatus(presence, parentProvider)
.equals(
parentProvider
.getJabberStatusEnum()
.getStatus(JabberStatusEnum.OFFLINE)))
{
userStats.add(presence);
}
Presence currentPresence;
if (userStats.size() == 0)
{
currentPresence = presence;
/*
* We no longer have statuses for userID so it doesn't make
* sense to retain (1) the TreeSet and (2) its slot in the
* statuses Map.
*/
statuses.remove(userID);
}
else
currentPresence = userStats.first();
ContactJabberImpl sourceContact
= ssContactList.findContactById(userID);
if (sourceContact == null)
{
logger.warn("No source contact found for id=" + userID);
return;
}
// statuses may be the same and only change in status message
sourceContact.setStatusMessage(currentPresence.getStatus());
PresenceStatus oldStatus
= sourceContact.getPresenceStatus();
PresenceStatus newStatus
= jabberStatusToPresenceStatus(
currentPresence,
parentProvider);
// when old and new status are the same do nothing
// no change
if(oldStatus.equals(newStatus))
return;
sourceContact.updatePresenceStatus(newStatus);
ContactGroup parent
= ssContactList.findContactGroup(sourceContact);
if (logger.isDebugEnabled())
logger.debug("Will Dispatch the contact status event.");
fireContactPresenceStatusChangeEvent(sourceContact, parent,
oldStatus, newStatus);
}
catch (IllegalStateException ex)
{
logger.error("Failed changing status", ex);
}
catch (IllegalArgumentException ex)
{
logger.error("Failed changing status", ex);
}
}
|
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/ChoiceGroup.java b/enough-polish-j2me/source/src/de/enough/polish/ui/ChoiceGroup.java
index b0b15e5..2940a62 100644
--- a/enough-polish-j2me/source/src/de/enough/polish/ui/ChoiceGroup.java
+++ b/enough-polish-j2me/source/src/de/enough/polish/ui/ChoiceGroup.java
@@ -1,2189 +1,2195 @@
//#condition polish.usePolishGui
// generated by de.enough.doc2java.Doc2Java (www.enough.de) on Sat Dec 06 15:06:44 CET 2003
/*
* Copyright (c) 2004-2005 Robert Virkus / Enough Software
*
* This file is part of J2ME Polish.
*
* J2ME Polish is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* J2ME Polish is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with J2ME Polish; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Commercial licenses are also available, please
* refer to the accompanying LICENSE.txt or visit
* http://www.j2mepolish.org for details.
*/
package de.enough.polish.ui;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
//#if polish.android
import de.enough.polish.android.midlet.MidletBridge;
//#endif
import de.enough.polish.util.ArrayList;
import de.enough.polish.util.Locale;
/**
* A <code>ChoiceGroup</code> is a group of selectable elements intended to be
* placed within a <CODE>Form</CODE>. The group may be created with a mode that requires a
* single choice to be made or that allows multiple choices. The
* implementation is responsible for providing the graphical representation of
* these modes and must provide visually different graphics for different
* modes. For example, it might use "radio buttons" for the
* single choice
* mode and "check boxes" for the multiple choice mode.
*
* <p> <strong>Note:</strong> most of the essential methods have been
* specified in the <CODE>Choice</CODE> interface.</p>
* <HR>
*
* @author Robert Virkus, [email protected]
* @since MIDP 1.0
*/
public class ChoiceGroup
extends Container
implements Choice
//#if polish.ChoiceGroup.supressCommands == true
//#define tmp.suppressMarkCommands
//#define tmp.suppressSelectCommand
//#else
//#if polish.ChoiceGroup.suppressMarkCommands == true
//#define tmp.suppressMarkCommands
//#else
//#define tmp.allowMarkCommands
//#endif
//#if polish.ChoiceGroup.suppressSelectCommand == true
//#define tmp.suppressSelectCommand
//#else
//#define tmp.allowSelectCommand
//#endif
//#endif
//#if tmp.suppressMarkCommands && tmp.suppressSelectCommand
//#define tmp.suppressAllCommands
//#else
, ItemCommandListener
//#endif
{
//#ifndef tmp.suppressMarkCommands
//#ifdef polish.i18n.useDynamicTranslations
public static Command MARK_COMMAND = new Command( Locale.get("polish.command.mark"), Command.ITEM, 9 );
//#elifdef polish.command.mark:defined
//#= public static final Command MARK_COMMAND = new Command("${polish.command.mark}", Command.ITEM, 9 );
//#else
//# public static final Command MARK_COMMAND = new Command( "Mark", Command.ITEM, 9 );
//#endif
//#ifdef polish.i18n.useDynamicTranslations
public static Command UNMARK_COMMAND = new Command( Locale.get("polish.command.unmark"), Command.ITEM, 9 );
//#elifdef polish.command.mark:defined
//#= public static final Command UNMARK_COMMAND = new Command("${polish.command.unmark}", Command.ITEM, 10 );
//#else
//# public static final Command UNMARK_COMMAND = new Command( "Unmark", Command.ITEM, 10 );
//#endif
//#endif
private int selectedIndex;
//private boolean isExclusive;
private boolean isMultiple;
protected int choiceType;
private boolean isImplicit;
private Command selectCommand;
//#ifdef polish.usePopupItem
private static Image popupImage;
private boolean isPopup;
private int popupColor = 0;
private int popupBackgroundColor = 0xFFFFFF;
private IconItem popupItem;
private boolean isPopupClosed;
//#ifdef polish.css.popup-roundtrip
private boolean popupRoundTrip;
//#endif
//private int popupOpenY;
private int popupParentOpenY;
private int originalContentWidth;
private int originalContentHeight;
private int originalBackgroundHeight;
// private boolean closePopupOnKeyRelease;
//#endif
//#ifndef tmp.suppressAllCommands
private ItemCommandListener additionalItemCommandListener;
//#endif
//#if polish.css.view-type || polish.css.columns
//#define tmp.supportViewType
//#endif
//#if ! tmp.suppressSelectCommand && tmp.supportViewType
private boolean isSelectCommandAdded;
//#endif
//#ifdef polish.hasPointerEvents
private boolean isPointerReleaseShouldTriggerKeyRelease;
//#endif
/**
* Creates a new, empty <code>ChoiceGroup</code>, specifying its
* title and its type.
* The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* choice type is not allowed within a <code>ChoiceGroup</code>.
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @throws IllegalArgumentException - if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType)
{
this( label, choiceType, new String[0], null, null, false );
}
/**
* Creates a new, empty <code>ChoiceGroup</code>, specifying its
* title and its type.
* The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* choice type is not allowed within a <code>ChoiceGroup</code>.
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param style the CSS style for this item
* @throws IllegalArgumentException if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, Style style)
{
this( label, choiceType, new String[0], null, style, false );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>Strings</code>
* and <code>Images</code> to be used as its
* initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>stringElements</code> array must be non-null and
* every array element
* must also be non-null. The length of the
* <code>stringElements</code> array
* determines the number of elements in the <code>ChoiceGroup</code>. The
* <code>imageElements</code> array
* may be <code>null</code> to indicate that the
* <code>ChoiceGroup</code> elements have no images.
* If the
* <code>imageElements</code> array is non-null, it must be the
* same length as the
* <code>stringElements</code> array. Individual elements of the
* <code>imageElements</code> array
* may be <code>null</code> in order to indicate the absence of an
* image for the
* corresponding <code>ChoiceGroup</code> element. Non-null elements
* of the
* <code>imageElements</code> array may refer to mutable or
* immutable images.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param stringElements set of strings specifying the string parts of the ChoiceGroup elements
* @param imageElements set of images specifying the image parts of the ChoiceGroup elements
* @throws NullPointerException if stringElements is null or if the stringElements array contains any null elements
* @throws IllegalArgumentException if the imageElements array is non-null and has a different length from the stringElements array
* or if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, String[] stringElements, Image[] imageElements)
{
this( label, choiceType, stringElements, imageElements, null, false );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>Strings</code>
* and <code>Images</code> to be used as its
* initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>stringElements</code> array must be non-null and
* every array element
* must also be non-null. The length of the
* <code>stringElements</code> array
* determines the number of elements in the <code>ChoiceGroup</code>. The
* <code>imageElements</code> array
* may be <code>null</code> to indicate that the
* <code>ChoiceGroup</code> elements have no images.
* If the
* <code>imageElements</code> array is non-null, it must be the
* same length as the
* <code>stringElements</code> array. Individual elements of the
* <code>imageElements</code> array
* may be <code>null</code> in order to indicate the absence of an
* image for the
* corresponding <code>ChoiceGroup</code> element. Non-null elements
* of the
* <code>imageElements</code> array may refer to mutable or
* immutable images.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param stringElements set of strings specifying the string parts of the ChoiceGroup elements
* @param imageElements set of images specifying the image parts of the ChoiceGroup elements
* @param style The CSS style for this item
* @throws NullPointerException if stringElements is null or if the stringElements array contains any null elements
* @throws IllegalArgumentException if the imageElements array is non-null and has a different length from the stringElements array
* or if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, String[] stringElements, Image[] imageElements, Style style )
{
this( label, choiceType, stringElements, imageElements, style, false );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>Strings</code>
* and <code>Images</code> to be used as its
* initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>stringElements</code> array must be non-null and
* every array element
* must also be non-null. The length of the
* <code>stringElements</code> array
* determines the number of elements in the <code>ChoiceGroup</code>. The
* <code>imageElements</code> array
* may be <code>null</code> to indicate that the
* <code>ChoiceGroup</code> elements have no images.
* If the
* <code>imageElements</code> array is non-null, it must be the
* same length as the
* <code>stringElements</code> array. Individual elements of the
* <code>imageElements</code> array
* may be <code>null</code> in order to indicate the absence of an
* image for the
* corresponding <code>ChoiceGroup</code> element. Non-null elements
* of the
* <code>imageElements</code> array may refer to mutable or
* immutable images.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param stringElements set of strings specifying the string parts of the ChoiceGroup elements
* @param imageElements set of images specifying the image parts of the ChoiceGroup elements
* @param style The CSS style for this item
* @param allowImplicit true when the Choice.IMPLICIT choiceType is also allowed
* @throws NullPointerException if stringElements is null or if the stringElements array contains any null elements
* @throws IllegalArgumentException if the imageElements array is non-null and has a different length from the stringElements array
* or if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP (unless allowImplicit is defined)
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, String[] stringElements, Image[] imageElements, Style style, boolean allowImplicit )
{
this( label, choiceType,
buildChoiceItems(stringElements, imageElements, choiceType, style),
style, allowImplicit );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>ChoiceItem</code>s
* to be used as its initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>items</code>s array must be non-null and
* every <code>ChoiceItem</code> must have its text be a non-null
* <code>String</code>.
* The length of the <code>items</code> array
* determines the number of elements in the <code>ChoiceGroup</code>.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param items set of <code>ChoiceItem</code>s specifying the ChoiceGroup elements
* @throws NullPointerException if <code>items</code> is null
* or if getText() for one of the <code>ChoiceItem</code> in the array
* retuns a null <code>String</code>.
* @throws IllegalArgumentException if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP (unless allowImplicit is defined)
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, ChoiceItem[] items)
{
this( label, choiceType, items, null, false );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>ChoiceItem</code>s
* to be used as its initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>items</code>s array must be non-null and
* every <code>ChoiceItem</code> must have its text be a non-null
* <code>String</code>.
* The length of the <code>items</code> array
* determines the number of elements in the <code>ChoiceGroup</code>.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param items set of <code>ChoiceItem</code>s specifying the ChoiceGroup elements
* @param style The CSS style for this item
* @throws NullPointerException if <code>items</code> is null
* or if getText() for one of the <code>ChoiceItem</code> in the array
* retuns a null <code>String</code>.
* @throws IllegalArgumentException if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP (unless allowImplicit is defined)
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, ChoiceItem[] items, Style style )
{
this( label, choiceType, items, style, false );
}
/**
* Creates a new <code>ChoiceGroup</code>, specifying its title,
* the type of the
* <code>ChoiceGroup</code>, and an array of <code>ChoiceItem</code>s
* to be used as its initial contents.
*
* <p>The type must be one of <code>EXCLUSIVE</code>,
* <code>MULTIPLE</code>, or <code>POPUP</code>. The
* <code>IMPLICIT</code>
* type is not allowed for <code>ChoiceGroup</code>.</p>
*
* <p>The <code>items</code>s array must be non-null and
* every <code>ChoiceItem</code> must have its text be a non-null
* <code>String</code>.
* The length of the <code>items</code> array
* determines the number of elements in the <code>ChoiceGroup</code>.</p>
*
* @param label the item's label (see Item)
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param items set of <code>ChoiceItem</code>s specifying the ChoiceGroup elements
* @param style The CSS style for this item
* @param allowImplicit true when the Choice.IMPLICIT choiceType is also allowed
* @throws IllegalArgumentException if choiceType is not one of EXCLUSIVE, MULTIPLE, or POPUP (unless allowImplicit is defined)
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
public ChoiceGroup( String label, int choiceType, ChoiceItem[] items, Style style, boolean allowImplicit )
{
super( label, false, style, -1 );
if (choiceType == Choice.EXCLUSIVE
//#if !polish.usePopupItem
|| choiceType == Choice.POPUP
//#endif
) {
//this.isExclusive = true;
} else if (choiceType == Choice.MULTIPLE) {
this.isMultiple = true;
//#ifdef polish.usePopupItem
} else if (choiceType == Choice.POPUP) {
this.isPopup = true;
this.isPopupClosed = true;
this.popupItem = new IconItem( null, null, style );
this.popupItem.setImageAlign( Graphics.RIGHT );
this.popupItem.setAppearanceMode( BUTTON );
this.popupItem.parent = this;
//#endif
} else if (choiceType == Choice.IMPLICIT && allowImplicit ) {
this.isImplicit = true;
//#if !(polish.hasVirtualKeyboard || (polish.android && !polish.android.autoFocus))
setAutoFocusEnabled( true );
//#endif
} else {
throw new IllegalArgumentException(
//#ifdef polish.verboseDebug
"invalid choiceType [" + choiceType + "] - IMPLICIT=" + Choice.IMPLICIT + "."
//#endif
);
}
this.choiceType = choiceType;
if (items != null) {
for (int i = 0; i < items.length; i++) {
ChoiceItem item = items[i];
append( item );
}
}
}
/**
* Builds an array of <code>ChoiceItems</code> out of
* an array of <code>String</code>s and <code>Image</code>s,
* specifying the <code>choiceType</code> and <code>style</code>
* common to any <code>ChoiceItem</code> in the resulting array.
*
* @param stringElements set of strings specifying the string parts of the ChoiceGroup elements
* @param imageElements set of images specifying the image parts of the ChoiceGroup elements
* @param choiceType EXCLUSIVE, MULTIPLE, or POPUP
* @param style The CSS style for this item
* @return an aray of choice items
* @throws NullPointerException if stringElements is null or if the stringElements array contains any null elements
* @throws IllegalArgumentException if the imageElements array is non-null and has a different length from the stringElements array
* @see Choice#EXCLUSIVE
* @see Choice#MULTIPLE
* @see Choice#IMPLICIT
* @see Choice#POPUP
*/
protected static ChoiceItem[] buildChoiceItems(String[] stringElements, Image[] imageElements, int choiceType, Style style)
{
//#ifndef polish.skipArgumentCheck
if (imageElements != null && imageElements.length != stringElements.length) {
//#ifdef polish.verboseDebug
throw new IllegalArgumentException("imageElements need to have the same length as the stringElements.");
//#else
//# throw new IllegalArgumentException();
//#endif
}
//#endif
ChoiceItem[] items = new ChoiceItem[stringElements.length];
for (int i = 0; i < stringElements.length; ++i) {
Image img = null;
if (imageElements != null) {
img = imageElements[i];
}
items[i] = new ChoiceItem( stringElements[i], img, choiceType, style );
}
return items;
}
//#ifdef polish.usePopupItem
/**
* Creates or returns the default image for popup groups.
*
* @return the default popup image
*/
protected Image createPopupImage() {
if (popupImage == null) {
popupImage = Image.createImage( 9, 12 );
Graphics g = popupImage.getGraphics();
g.setColor( this.popupBackgroundColor );
g.fillRect(0, 0, 10, 13 );
g.setColor( this.popupColor );
g.drawLine(0, 0, 9, 0 );
g.drawLine( 3, 3, 3, 9 );
g.drawLine( 4, 3, 4, 10 );
g.drawLine( 5, 3, 5, 9 );
g.drawLine( 2, 8, 6, 8 );
g.drawLine( 1, 7, 7, 7 );
}
return popupImage;
}
//#endif
/**
* Gets the <code>String</code> part of the element referenced by
* <code>elementNum</code>.
*
* @param elementNum the index of the element to be queried
* @return the string part of the element
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#getString(int) in interface Choice
* @see #getImage(int)
*/
public String getString(int elementNum)
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
return item.getText();
}
/**
* Gets the <code>Image</code> part of the element referenced by
* <code>elementNum</code>.
*
* @param elementNum the number of the element to be queried
* @return the image part of the element, or null if there is no image
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#getImage(int) in interface Choice
* @see #getString(int)
*/
public Image getImage(int elementNum)
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
return item.getImage();
}
/**
* Gets the <code>ChoiceItem</code> of the element referenced by
* <code>elementNum</code>.
*
* @param elementNum the number of the element to be queried
* @return the ChoiceItem of the element
* @throws IndexOutOfBoundsException if elementNum is invalid
*/
public ChoiceItem getItem( int elementNum )
{
return (ChoiceItem)this.itemsList.get( elementNum );
}
/**
* Appends an element to the <code>ChoiceGroup</code>.
*
* @param stringPart the string part of the element to be added
* @param imagePart the image part of the element to be added, or null if there is no image part
* @return the assigned index of the element
* @throws NullPointerException if stringPart is null
* @see Choice#append( String, Image) in interface Choice
*/
public int append( String stringPart, Image imagePart)
{
return append( stringPart, imagePart, null );
}
/**
* Appends an element to the <code>ChoiceGroup</code>.
*
* @param stringPart the string part of the element to be added
* @param imagePart the image part of the element to be added, or null if there is no image part
* @param elementStyle the style for the appended ChoiceItem
* @return the assigned index of the element
* @throws NullPointerException if stringPart is null
* @see Choice#append( String, Image) in interface Choice
*/
public int append( String stringPart, Image imagePart, Style elementStyle )
{
ChoiceItem item = new ChoiceItem( stringPart, imagePart, this.choiceType, elementStyle );
return append( item, elementStyle );
}
/**
* Appends a ChoiceItem to this choice group.
*
* @param item the item
* @return the assigned index of the element
*/
public int append( ChoiceItem item ) {
return append( item, null );
}
/**
* Appends a ChoiceItem to this choice group.
*
* @param item the item
* @param elementStyle the style of the item, ignored when null
* @return the assigned index of the element
*/
public int append( ChoiceItem item, Style elementStyle ) {
add( item );
if ( elementStyle != null ) {
// set the field directly instead of calling setStyle() so that the style is applied later when it's needed
item.style = elementStyle;
item.isStyleInitialized = false;
}
int itemIndex = this.itemsList.size() - 1;
if (this.choiceType == Choice.EXCLUSIVE && item.isSelected) {
if (this.selectedIndex != -1) {
((ChoiceItem)get( this.selectedIndex )).select( false );
}
this.selectedIndex = itemIndex;
}
//#if ! tmp.suppressMarkCommands
if (this.isMultiple) {
selectChoiceItem(item, item.isSelected);
item.setItemCommandListener( this );
}
//#endif
//#ifdef polish.usePopupItem
if (this.isPopup && this.isPopupClosed && this.selectedIndex == -1) {
this.popupItem.setText( item.text );
this.selectedIndex = 0;
}
//#endif
return itemIndex;
}
/**
* Inserts an element into the <code>ChoiceGroup</code> just prior to
* the element specified.
*
* @param elementNum the index of the element where insertion is to occur
* @param stringPart the string part of the element to be inserted
* @param imagePart the image part of the element to be inserted, or null if there is no image part
* @throws IndexOutOfBoundsException if elementNum is invalid
* @throws NullPointerException if stringPart is null
* @see Choice#insert(int, String, Image) in interface Choice
*/
public void insert(int elementNum, String stringPart, Image imagePart)
{
insert( elementNum, stringPart, imagePart, null );
}
/**
* Inserts an element into the <code>ChoiceGroup</code> just prior to
* the element specified.
*
* @param elementNum the index of the element where insertion is to occur
* @param stringPart the string part of the element to be inserted
* @param imagePart the image part of the element to be inserted, or null if there is no image part
* @param elementStyle the style for the inserted ChoiceItem
* @throws IndexOutOfBoundsException if elementNum is invalid
* @throws NullPointerException if stringPart is null
* @see Choice#insert(int, String, Image) in interface Choice
*/
public void insert(int elementNum, String stringPart, Image imagePart, Style elementStyle)
{
ChoiceItem item = new ChoiceItem( stringPart, imagePart, this.choiceType, elementStyle );
add(elementNum, item);
}
/**
* Inserts an element into the <code>ChoiceGroup</code> just prior to
* the element specified.
*
* @param elementNum the index of the element where insertion is to occur
* @param item ChoiceItem of the element to be inserted
* @throws IndexOutOfBoundsException if elementNum is invalid
*/
public void insert(int elementNum, ChoiceItem item)
{
add(elementNum, item);
}
/**
* Inserts an element into the <code>ChoiceGroup</code> just prior to
* the element specified.
*
* @param elementNum the index of the element where insertion is to occur
* @param item ChoiceItem of the element to be inserted
* @param elementStyle the style for the inserted ChoiceItem
* @throws IndexOutOfBoundsException if elementNum is invalid
*/
public void insert(int elementNum, ChoiceItem item, Style elementStyle)
{
if (elementStyle != null) {
item.setStyle(elementStyle);
}
add(elementNum, item);
}
/**
* Sets the <code>String</code> and <code>Image</code> parts of the
* element referenced by <code>elementNum</code>,
* replacing the previous contents of the element.
*
* @param elementNum - the index of the element to be set
* @param stringPart - the string part of the new element
* @param imagePart - the image part of the element, or null if there is no image part
* @throws IndexOutOfBoundsException - if elementNum is invalid
* @throws NullPointerException - if stringPart is null
* @see Choice#set(int, String, Image) in interface Choice
*/
public void set(int elementNum, String stringPart, Image imagePart)
{
set( elementNum, stringPart, imagePart, null );
}
/**
* Sets the <code>String</code> and <code>Image</code> parts of the
* element referenced by <code>elementNum</code>,
* replacing the previous contents of the element.
*
* @param elementNum the index of the element to be set
* @param stringPart the string part of the new element
* @param imagePart the image part of the element, or null if there is no image part
* @param elementStyle the style for the new list element.
* @throws IndexOutOfBoundsException if elementNum is invalid
* @throws NullPointerException if stringPart is null
* @see Choice#set(int, String, Image) in interface Choice
*/
public void set(int elementNum, String stringPart, Image imagePart, Style elementStyle )
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
item.setText( stringPart );
if (imagePart != null) {
item.setImage(imagePart);
}
if (elementStyle != null) {
item.setStyle(elementStyle);
}
if (isInitialized()) {
setInitialized(false);
repaint();
}
}
// /**
// * Sets the <code>ChoiceItem</code> of the
// * element referenced by <code>elementNum</code>,
// * replacing the previous one.
// *
// * @param elementNum the index of the element to be set
// * @param item the ChoiceItem of the new element
// * @throws IndexOutOfBoundsException if elementNum is invalid
// */
// public void set(int elementNum, ChoiceItem item )
// {
// super.set(elementNum, item);
// if (this.isInitialized) {
// this.isInitialized = false;
// repaint();
// }
// }
// /**
// * Sets the <code>ChoiceItem</code> of the
// * element referenced by <code>elementNum</code>,
// * replacing the previous one.
// *
// * @param elementNum the index of the element to be set
// * @param item the ChoiceItem of the new element
// * @param elementStyle the style for the new list element.
// * @throws IndexOutOfBoundsException if elementNum is invalid
// */
// public void set(int elementNum, ChoiceItem item, Style elementStyle )
// {
// if (elementStyle != null) {
// item.setStyle(elementStyle);
// }
// delete( elementNum );
// add( elementNum, item );
// if (this.isInitialized) {
// this.isInitialized = false;
// repaint();
// }
// }
/**
* Deletes the element referenced by <code>elementNum</code>.
*
* @param elementNum the index of the element to be deleted
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#delete(int) in interface Choice
*/
public void delete(int elementNum)
{
remove(elementNum);
//#ifdef polish.usePopupItem
if (this.isPopup) {
if (this.selectedIndex == elementNum ) {
if (this.itemsList.size() > 0) {
this.selectedIndex = -1;
if (this.isPopupClosed) {
setSelectedIndex( 0, true );
}
} else {
this.selectedIndex = -1;
}
} else if ( elementNum < this.selectedIndex ) {
this.selectedIndex--;
}
} else {
//#endif
if (this.selectedIndex == elementNum ) {
this.selectedIndex = -1;
} else if (elementNum < this.selectedIndex) {
this.selectedIndex--;
}
//#ifdef polish.usePopupItem
}
//#endif
}
/**
* Deletes all elements from this <code>ChoiceGroup</code>.
*
* @see Choice#deleteAll() in interface Choice
*/
public void deleteAll()
{
clear();
}
/*
* (non-Javadoc)
* @see de.enough.polish.ui.Container#clear()
*/
public void clear() {
this.selectedIndex = -1;
super.clear();
}
/**
* Gets a boolean value indicating whether this element is selected.
*
* @param elementNum the index of the element to be queried
* @return selection state of the element
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#isSelected(int) in interface Choice
*/
public boolean isSelected(int elementNum)
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
return item.isSelected;
}
/**
* Returns the index number of an element in the
* <code>ChoiceGroup</code> that is
* selected. For <code>ChoiceGroup</code> objects of type
* <code>EXCLUSIVE</code> and <code>POPUP</code>
* there is at most one element selected, so
* this method is useful for determining the user's choice.
* Returns <code>-1</code> if
* there are no elements in the <code>ChoiceGroup</code>.
*
* <p>For <code>ChoiceGroup</code> objects of type
* <code>MULTIPLE</code>, this always
* returns <code>-1</code> because no
* single value can in general represent the state of such a
* <code>ChoiceGroup</code>.
* To get the complete state of a <code>MULTIPLE</code>
* <code>Choice</code>, see <A HREF="../../../javax/microedition/lcdui/ChoiceGroup.html#getSelectedFlags(boolean[])"><CODE>getSelectedFlags</CODE></A>.</p>
*
* @return index of selected element, or -1 if none
* @see Choice#getSelectedIndex() in interface Choice
* @see #setSelectedIndex(int, boolean)
*/
public int getSelectedIndex()
{
if (this.isMultiple || this.itemsList.size() == 0) {
return -1;
} else if (!this.isImplicit || this.focusedIndex == -1) {
return this.selectedIndex;
} else {
// this is an implicit/focused choice:
return this.focusedIndex;
}
}
/**
* Queries the state of a <code>ChoiceGroup</code> and returns the state of
* all elements in the
* boolean array
* <code>selectedArray_return</code>. <strong>Note:</strong> this
* is a result parameter.
* It must be at least as long as the size
* of the <code>ChoiceGroup</code> as returned by <code>size()</code>.
* If the array is longer, the extra
* elements are set to <code>false</code>.
*
* <p>For <code>ChoiceGroup</code> objects of type
* <code>MULTIPLE</code>, any
* number of elements may be selected and set to true in the result
* array. For <code>ChoiceGroup</code> objects of type
* <code>EXCLUSIVE</code> and <code>POPUP</code>
* exactly one element will be selected, unless there are
* zero elements in the <code>ChoiceGroup</code>. </p>
*
* @param selectedArray_return array to contain the results
* @return the number of selected elements in the ChoiceGroup
* @throws IllegalArgumentException if selectedArray_return is shorter than the size of the ChoiceGroup
* @throws NullPointerException if selectedArray_return is null
* @see Choice#getSelectedFlags(boolean[]) in interface Choice
* @see #setSelectedFlags(boolean[])
*/
public int getSelectedFlags(boolean[] selectedArray_return)
{
//#ifndef polish.skipArgumentCheck
if (selectedArray_return.length < this.itemsList.size()) {
//#ifdef polish.verboseDebug
throw new IllegalArgumentException("length of selectedArray is too small");
//#else
//# throw new IllegalArgumentException();
//#endif
}
//#endif
ChoiceItem[] myItems = (ChoiceItem[]) this.itemsList.toArray( new ChoiceItem[ this.itemsList.size() ] );
int selectedItems = 0;
for (int i = 0; i < myItems.length; i++) {
ChoiceItem item = myItems[i];
if (item.isSelected || (this.isImplicit && i == this.focusedIndex) || (!this.isMultiple && i == this.selectedIndex)) {
selectedArray_return[i] = true;
selectedItems++;
} else {
selectedArray_return[i] = false;
}
}
return selectedItems;
}
/**
* For <code>ChoiceGroup</code> objects of type
* <code>MULTIPLE</code>, this simply sets an
* individual element's selected state.
*
* <P>For <code>ChoiceGroup</code> objects of type
* <code>EXCLUSIVE</code> and <code>POPUP</code>, this can be used only to
* select an element. That is, the <code> selected </code> parameter must
* be <code> true </code>. When an element is selected, the previously
* selected element is deselected. If <code> selected </code> is <code>
* false </code>, this call is ignored.</P>
*
* <p>For both list types, the <code>elementNum</code> parameter
* must be within
* the range
* <code>[0..size()-1]</code>, inclusive. </p>
*
* @param elementNum the number of the element. Indexing of the elements is zero-based
* @param selected the new state of the element true=selected, false=not selected
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#setSelectedIndex(int, boolean) in interface Choice
* @see #getSelectedIndex()
*/
public void setSelectedIndex(int elementNum, boolean selected)
{
//#debug
System.out.println("setSelectedIndex: index=" + elementNum + ", selected=" + selected + ", current selectedIndex=" + this.selectedIndex) ;
if (this.isMultiple) {
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
selectChoiceItem(item, selected);
} else {
if (!selected) {
return; // ignore this call
}
if (this.selectedIndex != -1) {
ChoiceItem oldSelected = (ChoiceItem) this.itemsList.get( this.selectedIndex );
oldSelected.select( false );
}
if(elementNum != -1)
{
this.selectedIndex = elementNum;
ChoiceItem newSelected = (ChoiceItem) this.itemsList.get( elementNum );
newSelected.select( true );
if (this.isFocused) {
if ( isInitialized()) {
focusChild( elementNum, newSelected, 0, true );
} else {
setAutoFocusEnabled( true );
this.autoFocusIndex = elementNum;
}
}
//#ifdef polish.usePopupItem
if (this.isPopup) {
this.popupItem.setText( newSelected.getText() );
}
//#endif
}
}
if (isInitialized()) {
setInitialized(false);
repaint();
}
notifyValueChanged(null);
}
/**
* Attempts to set the selected state of every element in the
* <code>ChoiceGroup</code>. The array
* must be at least as long as the size of the
* <code>ChoiceGroup</code>. If the array is
* longer, the additional values are ignored. <p>
*
* For <code>ChoiceGroup</code> objects of type
* <code>MULTIPLE</code>, this sets the selected
* state of every
* element in the <code>Choice</code>. An arbitrary number of
* elements may be selected.
* <p>
*
* For <code>ChoiceGroup</code> objects of type
* <code>EXCLUSIVE</code> and <code>POPUP</code>, exactly one array
* element must have the value <code>true</code>. If no element is
* <code>true</code>,
* the first element
* in the <code>Choice</code> will be selected. If two or more
* elements are <code>true</code>, the
* implementation will choose the first <code>true</code> element
* and select it. <p>
*
* @param selectedArray an array in which the method collect the selection status
* @throws IllegalArgumentException if selectedArray is shorter than the size of the ChoiceGroup
* @throws NullPointerException if the selectedArray is null
* @see Choice#setSelectedFlags(boolean[]) in interface Choice
* @see #getSelectedFlags(boolean[])
*/
public void setSelectedFlags(boolean[] selectedArray)
{
if (selectedArray == null || selectedArray.length == 0) {
// ignore these flags
return;
}
//#ifndef polish.skipArgumentCheck
if (selectedArray.length < this.itemsList.size()) {
//#ifdef polish.verboseDebug
throw new IllegalArgumentException("length of selectedArray is too small");
//#else
//# throw new IllegalArgumentException();
//#endif
}
//#endif
if (this.isMultiple) {
ChoiceItem[] myItems = (ChoiceItem[]) this.itemsList.toArray( new ChoiceItem[ this.itemsList.size() ] );
for (int i = 0; i < myItems.length; i++) {
ChoiceItem item = myItems[i];
boolean isSelected = selectedArray[i];
selectChoiceItem(item, isSelected);
}
} else {
int index = 0;
for (int i = 0; i < selectedArray.length; i++) {
if (selectedArray[i]) {
index = i;
break;
}
}
if (index > this.itemsList.size()) {
index = 0;
}
setSelectedIndex( index, true );
}
if (isInitialized()) {
setInitialized(false);
repaint();
}
notifyValueChanged(null);
}
/**
* Sets the application's preferred policy for fitting
* <code>Choice</code> element contents to the available screen space. The set policy applies for all
* elements of the <code>Choice</code> object. Valid values are
* <CODE>Choice.TEXT_WRAP_DEFAULT</CODE>,
* <CODE>Choice.TEXT_WRAP_ON</CODE>,
* and <CODE>Choice.TEXT_WRAP_OFF</CODE>.
* Fit policy is a hint, and the
* implementation may disregard the application's preferred policy.
* The J2ME Polish implementation always uses the TEXT_WRAP_ON policy.
*
* @param fitPolicy preferred content fit policy for choice elements
* @see Choice#setFitPolicy(int) in interface Choice
* @see #getFitPolicy()
* @since MIDP 2.0
*/
public void setFitPolicy(int fitPolicy)
{
//this.fitPolicy = fitPolicy;
// ignore hint
}
/**
* Gets the application's preferred policy for fitting
* <code>Choice</code> element contents to the available screen space. The value returned is the
* policy that had been set by the application, even if that value had
* been disregarded by the implementation.
*
* @return always Choice.TEXT_WRAP_ON
* @see Choice#getFitPolicy() in interface Choice
* @see #setFitPolicy(int)
* @since MIDP 2.0
*/
public int getFitPolicy()
{
return Choice.TEXT_WRAP_ON;
}
/**
* Sets the application's preferred font for
* rendering the specified element of this <code>Choice</code>.
* An element's font is a hint, and the implementation may disregard
* the application's preferred font.
* The J2ME Polish implementation uses the font defined by the appropriate
* CSS style and ignores the font which is set here.
*
* @param elementNum the index of the element, starting from zero
* @param font the preferred font to use to render the element
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#setFont(int, Font) in interface Choice
* @see #getFont(int)
* @since MIDP 2.0
*/
public void setFont(int elementNum, Font font)
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
item.setPreferredFont( font );
}
/**
* Gets the application's preferred font for
* rendering the specified element of this <code>Choice</code>. The
* value returned is the font that had been set by the application,
* even if that value had been disregarded by the implementation.
* If no font had been set by the application, or if the application
* explicitly set the font to <code>null</code>, the value is the default
* font chosen by the implementation.
*
* <p> The <code>elementNum</code> parameter must be within the range
* <code>[0..size()-1]</code>, inclusive.</p>
*
* @param elementNum the index of the element, starting from zero
* @return the preferred font to use to render the element
* @throws IndexOutOfBoundsException if elementNum is invalid
* @see Choice#getFont(int) in interface Choice
* @see #setFont(int elementNum, Font font)
* @since MIDP 2.0
*/
public Font getFont(int elementNum)
{
ChoiceItem item = (ChoiceItem) this.itemsList.get( elementNum );
Font font = item.preferredFont;
if (font == null) {
font = item.font;
}
return font;
}
//#ifdef polish.usePopupItem
protected void hideNotify() {
if (this.isPopup && !this.isPopupClosed) {
closePopup();
}
}
//#endif
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#paint(int, int, javax.microedition.lcdui.Graphics)
*/
public void paintContent(int x, int y, int leftBorder, int rightBorder, Graphics g) {
//#if tmp.supportViewType
if (this.containerView != null) {
super.paintContent(x, y, leftBorder, rightBorder, g);
return;
}
//#endif
if (this.isPopup && this.isPopupClosed) {
this.popupItem.paintContent(x, y, leftBorder, rightBorder, g);
} else {
//System.out.println("painting popup content at y=" + y + ", yScrollOffse=" + this.yOffset + ", clipY=" + g.getClipY() + ", clipHeight=" + g.getClipHeight());
super.paintContent(x, y, leftBorder, rightBorder, g );
}
}
//#endif
//#ifdef polish.usePopupItem
protected void init( int firstLineWidth, int availWidth, int availHeight ) {
super.init(firstLineWidth, availWidth, availHeight);
//#if tmp.supportViewType
if (this.containerView != null) {
return;
}
//#endif
if (this.isPopup && !this.isPopupClosed) {
this.backgroundWidth += (this.originalContentWidth - this.contentWidth);
this.backgroundHeight += (this.originalContentHeight - this.contentHeight);
}
}
//#endif
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#initItem()
*/
protected void initContent(int firstLineWidth, int availWidth, int availHeight) {
super.initContent(firstLineWidth, availWidth, availHeight);
//#if tmp.supportViewType
if (this.containerView != null) {
return;
}
//#endif
if (this.isPopup) {
//System.out.println("initContent of POPUP " + this + ", isClosed=" + this.isPopupClosed );
if (this.popupItem.image == null) {
this.popupItem.setImage( createPopupImage() );
}
if (this.isPopupClosed) {
if (this.popupItem.getText() == null && this.itemsList.size() > 0) {
ChoiceItem selectedItem = (ChoiceItem) this.itemsList.get( 0 );
this.popupItem.setText( selectedItem.getText() );
}
this.internalX = NO_POSITION_SET;
} else {
this.originalContentWidth = this.contentWidth;
this.originalContentHeight = this.contentHeight;
}
this.popupItem.getItemWidth( this.availableWidth, this.availableWidth, this.availableHeight );
this.originalBackgroundHeight = this.contentHeight + this.marginTop + this.marginBottom;
if (!this.useSingleRow && this.label != null) {
this.originalBackgroundHeight += this.label.itemHeight + this.paddingVertical;
}
if (this.popupItem.contentWidth > this.contentWidth) {
this.contentWidth = this.popupItem.contentWidth;
} else {
this.popupItem.setContentWidth(this.contentWidth);
}
this.contentHeight = this.popupItem.contentHeight;
}
}
//#endif
//
// //#ifdef polish.usePopupItem
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Container#setItemWidth(int)
// */
// public void setItemWidth(int width) {
// System.out.println("increasing popup width to " + width);
// if (!this.isPopup) {
// super.setItemWidth(width);
// } else {
// int diff = (width - this.itemWidth);
// int availWidth = (this.availContentWidth + diff);
// this.popupItem.setItemWidth(availWidth);
// this.contentWidth = availWidth;
// this.backgroundWidth += diff;
// this.itemWidth = width;
// }
// }
// //#endif
//
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#updateInternalPosition(Item)
*/
protected void updateInternalPosition(Item item) {
if (this.isPopup && this.isPopupClosed) {
if (this.parent instanceof Container) {
this.internalX = NO_POSITION_SET;
((Container)this.parent).updateInternalPosition(this);
}
} else {
super.updateInternalPosition( item );
}
}
//#endif
//#ifdef polish.useDynamicStyles
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#getCssSelector()
*/
protected String createCssSelector() {
return "choicegroup";
}
//#endif
//#ifdef polish.usePopupItem
private void closePopup() {
if (this.isPopupClosed) {
return;
}
getScreen().removeCommandsLayer();
this.isPopupClosed = true;
this.internalX = NO_POSITION_SET;
if (this.parent instanceof Container) {
//#debug
System.out.println("closing popup and adjusting scroll y offset to " + this.popupParentOpenY);
Container container = (Container)this.parent;
container.setScrollYOffset( this.popupParentOpenY, false );
}
setInitialized(false);
}
//#endif
//#ifdef polish.usePopupItem
private void openPopup() {
if (!this.isPopupClosed) {
return;
}
//#if polish.javaplatform >= Android/1.5
if (this.isShown) {
MidletBridge.instance.hideSoftKeyboard();
}
//#endif
getScreen().addCommandsLayer( new Command[]{ StyleSheet.OK_CMD, StyleSheet.CANCEL_CMD} );
//this.popupOpenY = this.yTopPos;
if (this.parent instanceof Container) {
this.popupParentOpenY = ((Container)this.parent).getScrollYOffset();
//#debug
System.out.println("opening popup and storing scroll y offset of " + this.popupParentOpenY);
}
//System.out.println("openPopup: backgroundHeight=" + this.originalBackgroundHeight + ", itemHeight=" + this.itemHeight);
this.isPopupClosed = false;
focusChild( this.selectedIndex );
// recalculate the internal positions of the selected choice:
if (this.selectedIndex != -1) {
Item item = (Item) this.itemsList.get( this.selectedIndex );
//System.out.println("selectedIndex=" + this.selectedIndex + ", isInitialized=" + item.isInitialized);
this.internalY = item.relativeY;
this.internalHeight = item.itemHeight;
this.internalX = item.relativeX;
this.internalWidth = item.itemWidth;
}
setInitialized(false);
this.backgroundHeight = this.originalBackgroundHeight;
}
//#endif
/**
* Checks if the popup window is currently closed for a POPUP ChoiceGroup.
* @return true when this is a POPUP ChoiceGroup and the popup is closed
*/
public boolean isPopupClosed()
{
boolean result = false;
//#ifdef polish.usePopupItem
result = this.isPopupClosed;
//#endif
return result;
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handleKeyPressed(int, int)
*/
protected boolean handleKeyPressed(int keyCode, int gameAction) {
if (this.itemsList.size() == 0) {
//#debug
System.out.println("itemsList.size()==0, aborting handleKeyPressed");
return super.handleKeyPressed(keyCode, gameAction);
}
boolean gameActionIsFire = (gameAction == Canvas.FIRE);
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", isFire=" + gameActionIsFire);
//#if polish.ChoiceGroup.handleDefaultCommandFirst == true
if (gameActionIsFire) {
//#ifdef polish.usePopupItem
if (!this.isPopup || this.isPopupClosed) {
//#endif
ItemCommandListener listener = this.itemCommandListener;
//#ifndef tmp.suppressAllCommands
listener = this.additionalItemCommandListener;
//#endif
if (this.defaultCommand != null && listener != null) {
listener.commandAction( this.defaultCommand, this );
notifyItemPressedStart();
return true;
}
//#ifdef polish.usePopupItem
}
//#endif
}
//#endif
boolean processed = false;
//#ifdef polish.usePopupItem
if (!(this.isPopup && this.isPopupClosed)) {
processed = super.handleKeyPressed(keyCode, gameAction);
//#ifdef polish.css.popup-roundtrip
if (!processed && this.popupRoundTrip && this.isPopup && !this.isPopupClosed && this.itemsList.size() > 1) {
int nextFocusedIndex = -1;
if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8 ) {
// focus the first item of the opened POPUP choice:
for (int i= 0; i < this.itemsList.size(); i++ ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
} else if ( gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
for (int i= this.itemsList.size()-1; i >= 0; i-- ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
}
if (nextFocusedIndex != -1) {
focusChild(nextFocusedIndex);
processed = true;
}
}
//#endif
}
//#else
- processed = super.handleKeyPressed(keyCode, gameAction);
+ //#if polish.Container.dontUseNumberKeys != true
+ if ( keyCode < Canvas.KEY_NUM0 || keyCode > Canvas.KEY_NUM9 ) {
+ processed = super.handleKeyPressed(keyCode, gameAction);
+ }
+ //#else
+ processed = super.handleKeyPressed(keyCode, gameAction);
+ //#endif
//#endif
//#debug
System.out.println("ChoiceGroup: container handled keyPressEvent: " + processed);
if (!processed) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
//#ifdef polish.usePopupItem
if (this.isPopup && this.isPopupClosed && gameActionIsFire) {
notifyItemPressedStart(); // open popup in handleKeyReleased()
return true;
} else
//#endif
if (gameActionIsFire && choiceItem != null) {
choiceItem.notifyItemPressedStart();
return true;
} else {
//#if polish.Container.dontUseNumberKeys != true
if (keyCode >= Canvas.KEY_NUM1 && keyCode <= Canvas.KEY_NUM9) {
int index = keyCode - Canvas.KEY_NUM1;
if (index < this.itemsList.size()) {
Item item = getItem(index);
if (
//#ifdef polish.usePopupItem
(!this.isPopup || !this.isPopupClosed) &&
//#endif
(item.appearanceMode != PLAIN) )
{
// either this is not a POPUP or the POPUP is opened:
setSelectedIndex( index, true );
//#ifdef polish.usePopupItem
if (this.isPopup) {
closePopup();
}
//#endif
if (this.isImplicit) {
// call command listener:
Screen scr = getScreen();
if (scr != null) {
Command selectCmd = this.selectCommand;
if (selectCmd == null) {
selectCmd = List.SELECT_COMMAND;
}
scr.callCommandListener( selectCmd );
}
} else {
notifyStateChanged();
}
notifyItemPressedStart();
return true;
}
}
}
//#endif
// //#ifdef polish.usePopupItem
// if (this.isPopup && (this.isPopupClosed == false)) {
// this.closePopupOnKeyRelease = true;
// return true;
// }
// //#endif
}
}
// //#else
// // no popup item is used by this application:
// processed = super.handleKeyPressed(keyCode, gameAction);
// if (!processed) {
// if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5 && this.focusedIndex != -1 ) {
// ChoiceItem item = (ChoiceItem) this.focusedItem;
// item.notifyItemPressedStart();
// if (this.isMultiple) {
// item.toggleSelect();
// } else {
// setSelectedIndex(this.focusedIndex, true);
// }
// if ( this.choiceType != IMPLICIT )
// {
// notifyStateChanged();
// }
// return true;
// //#if polish.Container.dontUseNumberKeys != true
// } else if ( (keyCode >= Canvas.KEY_NUM1) && (keyCode <= Canvas.KEY_NUM9) ) {
// int index = keyCode - Canvas.KEY_NUM1;
// if (index < this.itemsList.size()) {
// Item item = getItem(index);
// if (item.appearanceMode != PLAIN) {
// setSelectedIndex( index, true );
// if (this.isImplicit) {
// // call command listener:
// Screen scr = getScreen();
// if (scr != null) {
// Command selectCmd = this.selectCommand;
// if (selectCmd == null) {
// selectCmd = List.SELECT_COMMAND;
// }
// scr.callCommandListener( selectCmd );
// }
// } else {
// notifyStateChanged();
// }
// }
// return true;
// }
// //#endif
// }
// }
// //#endif
return processed;
}
//#ifdef polish.usePopupItem
protected boolean handleNavigate(int keyCode, int gameAction) {
if (this.isPopup && this.isPopupClosed) {
return false;
}
return super.handleNavigate(keyCode, gameAction);
}
//#endif
/**
* Selects a choice item.
* @param item the item
* @param isSelected true when it should be marked as selected
*/
protected void selectChoiceItem(ChoiceItem item, boolean isSelected)
{
item.select(isSelected);
//#if !tmp.suppressMarkCommands
if (this.isMultiple) {
if (isSelected) {
item.removeCommand(ChoiceGroup.MARK_COMMAND);
item.setDefaultCommand(ChoiceGroup.UNMARK_COMMAND);
} else {
item.removeCommand(ChoiceGroup.UNMARK_COMMAND);
item.setDefaultCommand(ChoiceGroup.MARK_COMMAND);
}
}
//#endif
}
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#handleKeyReleased(int, int)
*/
protected boolean handleKeyReleased(int keyCode, int gameAction) {
//#debug
System.out.println("handleKeyReleased( " + keyCode + ", " + gameAction + " ) for " + this + ", isPressed="+ this.isPressed );
//#ifdef polish.usePopupItem
boolean isClosed = this.isPopupClosed;
//#endif
// note: this was a rough fix for selecting an entry on a popup choice group when the "Select" command button
// was pressed - that worked for few cases and additionally required a Nokia layout, so it's outcommented for now
// if ((gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5)
// || (
// //#if polish.key.LeftSoftKey:defined
// //#= keyCode == ${polish.key.LeftSoftKey}
// //#else
// keyCode == -6
// //#endif
// && this.isPopup && !this.isPopupClosed
// )
// ) {
boolean gameActionIsFire = (gameAction == Canvas.FIRE);
if (gameActionIsFire) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
boolean handled = false;
if (choiceItem != null
//#ifdef polish.usePopupItem
&& !(this.isPopup && isClosed)
//#endif
)
{
if (this.isMultiple) {
selectChoiceItem( choiceItem, !choiceItem.isSelected);
handled = true;
} else if (this.selectedIndex != this.focusedIndex){
setSelectedIndex(this.focusedIndex, true);
handled = true;
}
if ( handled && (this.choiceType != Choice.IMPLICIT) )
{
notifyStateChanged();
}
if (choiceItem.isPressed) {
choiceItem.notifyItemPressedEnd();
if (this.isImplicit) {
// call command listener:
Screen scr = getScreen();
if (scr != null) {
Command selectCmd = this.selectCommand;
if (selectCmd == null) {
selectCmd = List.SELECT_COMMAND;
}
scr.callCommandListener( selectCmd );
handled = true;
}
}
}
}
//#ifdef polish.usePopupItem
if (this.isPopup) {
if (isClosed) {
notifyItemPressedEnd();
openPopup();
} else {
closePopup();
}
handled = true;
}
//#endif
return handled;
}
// //#ifdef polish.usePopupItem
// if (this.closePopupOnKeyRelease) {
// this.closePopupOnKeyRelease = false;
// closePopup();
// return true;
// }
// //#endif
return super.handleKeyReleased(keyCode, gameAction);
}
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerPressed(int, int)
*/
protected boolean handlePointerPressed(int relX, int relY) {
//#debug
System.out.println("ChoiceGroup.handlePointerPressed(" + relX + ", " + relY + ") for " + this );
//#ifdef polish.usePopupItem
if (this.isPopup && this.isPopupClosed && !isInItemArea(relX, relY)) {
return false;
}
//#endif
int index = this.focusedIndex;
boolean handled = super.handlePointerPressed(relX, relY); // focuses the appropriate item, might change this.focusedIndex...
relY -= this.contentY;
relX -= this.contentX;
//#ifdef tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
relX -= contView.getScrollXOffset();
}
//#endif
boolean triggerKey = (
(handled || isInItemArea(relX, relY, this.focusedItem))
//#if polish.css.view-type
&& (index == this.focusedIndex || contView == null || contView.allowsDirectSelectionByPointerEvent)
//#endif
);
//#debug
System.out.println("triggerKey=" + triggerKey + ", handled=" + handled + ", index=" + index + ", focusedIndex=" + this.focusedIndex + ", focusedItem=" + this.focusedItem + ", isInItemArea(relX, relY, this.focusedItem)=" + isInItemArea(relX, relY, this.focusedItem));
if ( triggerKey )
{
this.isPointerReleaseShouldTriggerKeyRelease = true;
handled |= handleKeyPressed( 0, Canvas.FIRE );
}
return handled;
}
//#endif
//#ifdef polish.hasPointerEvents
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#handlePointerReleased(int, int)
*/
protected boolean handlePointerReleased(int relX, int relY) {
//#debug
System.out.println("ChoiceGroup.handlePointerReleased(" + relX + ", " + relY + ") for " + this + ", isPointerReleaseShouldTriggerKeyRelease=" + this.isPointerReleaseShouldTriggerKeyRelease + ", focusedItem=" + this.focusedItem + ", focusuedIndex=" + this.focusedIndex);
if (this.enableScrolling && Math.abs(getScrollYOffset() - this.lastPointerPressYOffset)>20) {
// if we handle this case below, we would trigger choice elements accidently while dragging items:
return super.handlePointerReleased(relX, relY);
}
//#ifdef polish.usePopupItem
boolean isClosed = this.isPopupClosed;
if (this.isFocused && this.isPopup && isClosed) {
if (isInItemArea(relX, relY)) {
openPopup();
return true;
} else {
return false;
}
}
//#endif
if ( this.isPointerReleaseShouldTriggerKeyRelease ) {
this.isPointerReleaseShouldTriggerKeyRelease = false;
boolean handled = handlePointerScrollReleased(relX, relY);
if (!handled) {
//#ifdef tmp.supportViewType
ContainerView contView = this.containerView;
if (contView != null) {
handled = contView.handlePointerReleased(relX, relY - this.yOffset);
}
//#endif
int x = relX;
//#ifdef tmp.supportViewType
if (contView != null) {
x -= contView.getScrollXOffset();
}
//#endif
// System.out.println("isInItemArea(relX - this.contentX, relY - this.yOffset - this.contentY, this.focusedItem)=" + isInItemArea(relX - this.contentX, relY - this.yOffset - this.contentY, this.focusedItem));
if (!handled && isInItemArea(x - this.contentX, relY - this.yOffset - this.contentY, this.focusedItem)) {
handled = handleKeyReleased( 0, Canvas.FIRE );
}
}
if (handled) {
return true;
}
}
boolean handled = super.handlePointerReleased(relX, relY);
//#ifdef polish.usePopupItem
if (!handled && this.isPopup && !isClosed) { // && isEventCloseBy ) {
closePopup();
handled = true;
}
//#endif
return handled;
}
//#endif
// //#ifdef polish.hasPointerEvents && polish.usePopupItem
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Container#handlePointerDragged(int, int)
// */
// protected boolean handlePointerDragged(int relX, int relY)
// {
// if (this.isPopup && !this.isPopupClosed) {
//
// }
// return super.handlePointerDragged(relX, relY);
// }
// //#endif
//#if polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#isInContentArea(int, int)
*/
public boolean isInContentArea(int relX, int relY) {
if (this.isPopup && !this.isPopupClosed) {
if (relY < this.contentY || relY > this.contentY + this.originalContentHeight) {
return false;
}
if (relX < this.contentX || relX > this.contentX + this.originalContentWidth) {
return false;
}
return true;
} else {
return super.isInContentArea(relX, relY);
}
}
//#endif
//#if polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#isInItemArea(int, int)
*/
public boolean isInItemArea(int relX, int relY) {
if (this.isPopup) {
if(this.isPopupClosed) {
if (relY < 0 || relY > this.itemHeight) {
return false;
}
} else {
if (relY < 0 || relY > (this.itemHeight + (this.originalContentHeight - this.contentHeight))
|| relX < 0 || relX > (this.itemWidth + (this.originalContentWidth - this.contentWidth)))
{
return false;
}
}
return true;
} else {
return super.isInItemArea(relX, relY);
}
}
//#endif
/**
* Sets the select command for this choice group.
*
* @param command the new select command
*/
protected void setSelectCommand(Command command) {
this.selectCommand = command;
}
//#ifndef tmp.suppressAllCommands
/**
* Sets the command for selecting this (and opening this POPUP) choicegroup.
* This implementation only works like described when not all ChoiceGroup commands are deactivated
* by specifying the <variable name="polish.ChoiceGroup.suppressMarkCommands" value="true"/>
* and <variable name="polish.ChoiceGroup.suppressSelectCommand" value="true"/>
* preprocessing variables. When all commands are deactivated by the mentioned preprocessing variables,
* the implementation of Item is used instead.
*
* @param cmd the new command for selecting this choice group
*/
public void setDefaultCommand(Command cmd) {
if (this.choiceType == Choice.MULTIPLE) {
//#ifndef tmp.suppressMarkCommands
removeCommand( MARK_COMMAND );
//#endif
} else {
//#ifndef tmp.suppressSelectCommand
removeCommand( List.SELECT_COMMAND );
if (this.selectCommand != null) {
removeCommand( this.selectCommand );
}
//#endif
}
//removed due to potential infinite loops
/*
* if (this.additionalItemCommandListener == null) {
this.additionalItemCommandListener = this.itemCommandListener;
}*/
addCommand( cmd );
this.selectCommand = cmd;
this.defaultCommand = cmd;
this.itemCommandListener = this;
}
//#endif
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#defocus(de.enough.polish.ui.Style)
*/
public void defocus(Style originalStyle) {
if (this.isPopup) {
if (this.isPopupClosed) {
this.popupItem.setStyle( originalStyle );
} else {
closePopup();
}
setStyle( originalStyle );
// now remove any commands which are associated with this item:
Screen scr = getScreen();
if (scr != null) {
scr.removeItemCommands(this);
}
// change the label-style of this container:
//#ifdef polish.css.label-style
Style tmpLabelStyle = null;
if ( originalStyle != null) {
tmpLabelStyle = (Style) originalStyle.getObjectProperty("label-style");
}
if (tmpLabelStyle == null) {
tmpLabelStyle = StyleSheet.labelStyle;
}
if (this.label != null && tmpLabelStyle != null && this.label.style != tmpLabelStyle) {
this.label.setStyle( tmpLabelStyle );
}
//#endif
this.isFocused = false;
} else {
super.defocus(originalStyle);
}
}
//#endif
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Item#focus(de.enough.polish.ui.Style, int)
*/
protected Style focus(Style focusStyle, int direction) {
if (this.isPopup && this.isPopupClosed) {
if (focusStyle == null) {
focusStyle = getFocusedStyle();
}
Style original = this.style;
this.popupItem.setStyle( focusStyle );
setStyle( focusStyle );
// now remove any commands which are associated with this item:
showCommands();
// Screen scr = getScreen();
// if (scr != null) {
// scr.setItemCommands(this);
// }
// change the label-style of this container:
//#ifdef polish.css.label-style
if (this.label != null) {
Style labStyle = (Style) focusStyle.getObjectProperty("label-style");
if (labStyle != null) {
this.labelStyle = this.label.style;
this.label.setStyle( labStyle );
}
}
//#endif
this.isFocused = true;
return original;
} else {
return super.focus(focusStyle, direction);
}
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#setStyleWithBackground(de.enough.polish.ui.Style, boolean)
*/
public void setStyleWithBackground(Style style, boolean ignoreBackground)
{
// System.out.println("ChoiceGroup " + this.label + ", setStyle " + style.name);
super.setStyleWithBackground(style, ignoreBackground);
//#ifdef polish.usePopupItem
if (this.isPopup && this.popupItem != null) {
this.popupItem.setStyle( style );
}
if (this.isPopup && this.popupItem.image == null ) {
//#ifdef polish.css.popup-image
String url = style.getProperty("popup-image");
if (url != null ) {
this.popupItem.setImage( url );
}
//#endif
//#ifdef polish.css.popup-roundtrip
Boolean popupRoundTripBool = style.getBooleanProperty("popup-roundtrip");
if (popupRoundTripBool != null) {
this.popupRoundTrip = popupRoundTripBool.booleanValue();
}
//#endif
//#if ! tmp.suppressSelectCommand && tmp.supportViewType
if (!this.isSelectCommandAdded && this.choiceType == Choice.EXCLUSIVE && this.containerView == null) {
if (this.selectCommand != null) {
setDefaultCommand( this.selectCommand );
} else {
setDefaultCommand( List.SELECT_COMMAND );
}
this.isSelectCommandAdded = true;
}
//#endif
}
//#endif
//#ifndef tmp.suppressAllCommands
if (this.choiceType == Choice.MULTIPLE) {
//#ifndef tmp.suppressMarkCommands
//#ifdef polish.i18n.useDynamicTranslations
String cmdLabel = Locale.get("polish.command.mark");
if (cmdLabel != MARK_COMMAND.getLabel()) {
MARK_COMMAND = new Command( cmdLabel, Command.ITEM, 9 );
}
cmdLabel = Locale.get("polish.command.unmark");
if (cmdLabel != UNMARK_COMMAND.getLabel()) {
UNMARK_COMMAND = new Command( cmdLabel, Command.ITEM, 10 );
}
//#endif
//addCommand( MARK_COMMAND );
//addCommand( UNMARK_COMMAND );
//#endif
} else if (this.choiceType == Choice.EXCLUSIVE){
//#if !tmp.suppressSelectCommand
//#if tmp.supportViewType
if (this.containerView == null) {
//#endif
//#ifdef polish.i18n.useDynamicTranslations
String cmdLabel = Locale.get("polish.command.select");
if (cmdLabel != List.SELECT_COMMAND.getLabel()) {
List.SELECT_COMMAND = new Command( cmdLabel, Command.ITEM, 3 );
}
//#endif
setDefaultCommand( List.SELECT_COMMAND );
//#if tmp.supportViewType
}
//#endif
//#endif
}
this.itemCommandListener = this;
//#endif
setStyle( style, true );
}
//#ifdef polish.usePopupItem
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#setStyle(de.enough.polish.ui.Style, boolean)
*/
public void setStyle(Style style, boolean resetStyle) {
super.setStyle(style, resetStyle);
if (!resetStyle && this.isPopup && this.popupItem != null) {
this.popupItem.setStyle( style, resetStyle );
}
if (this.isPopup && this.popupItem.image == null ) {
//#ifdef polish.css.popup-color
Integer color = style.getIntProperty("popup-color");
if (color != null) {
this.popupColor = color.intValue();
}
//#endif
//#ifdef polish.css.popup-background-color
Integer bgColor = style.getIntProperty("popup-background-color");
if (bgColor != null) {
this.popupBackgroundColor = bgColor.intValue();
}
//#endif
}
}
//#endif
//#ifndef tmp.suppressAllCommands
/* (non-Javadoc)
* @see de.enough.polish.ui.ItemCommandListener#commandAction(javax.microedition.lcdui.Command, de.enough.polish.ui.Item)
*/
public void commandAction(Command c, Item item) {
//#debug
System.out.println("handle item command " + c.getLabel() + " for " + item );
if (item == this || this.itemsList.contains(item)) {
handleCommand( c );
}
}
//#endif
//#if polish.usePopupItem || !tmp.suppressAllCommands
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#handleCommand(javax.microedition.lcdui.Command)
*/
protected boolean handleCommand(Command cmd)
{
//#debug
System.out.println("handle command " + cmd.getLabel());
//#ifdef polish.usePopupItem
if (this.isPopup && !this.isPopupClosed) {
if (cmd == StyleSheet.OK_CMD) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
if (choiceItem != null)
{
setSelectedIndex(this.focusedIndex, true);
notifyStateChanged();
}
closePopup();
return true;
} else if (cmd == StyleSheet.CANCEL_CMD) {
closePopup();
return true;
}
}
//#endif
//#ifndef tmp.suppressAllCommands
//#if tmp.allowSelectCommand && tmp.allowMarkCommands
if (cmd == List.SELECT_COMMAND || cmd == MARK_COMMAND || cmd == this.selectCommand ) {
//#elif tmp.allowSelectCommand
//# if (cmd == List.SELECT_COMMAND || cmd == this.selectCommand ) {
//#elif tmp.allowMarkCommands
//# if (cmd == MARK_COMMAND || cmd == this.selectCommand ) {
//#else
//#abort Invalid combination of suppressed commands for a ChoiceGroup!
//# if (false) {
//#endif
if (this.focusedIndex != -1) {
setSelectedIndex( this.focusedIndex, true );
if ( (this.choiceType != Choice.IMPLICIT)
//#ifdef polish.usePopupItem
&& !(this.isPopup && !this.isPopupClosed)
//#endif
) {
notifyStateChanged();
}
//#ifdef polish.usePopupItem
if (this.isPopup) {
if (this.isPopupClosed) {
openPopup();
} else {
closePopup();
}
repaint();
}
//#endif
return !this.isImplicit;
}
//#ifdef polish.usePopupItem
else if (this.isPopup && this.isPopupClosed) {
openPopup();
return true;
}
//#endif
//#ifdef tmp.allowMarkCommands
} else if (cmd == UNMARK_COMMAND ) {
if (this.focusedIndex != -1) {
setSelectedIndex( this.focusedIndex, false );
if ( (this.choiceType != Choice.IMPLICIT)
//#ifdef polish.usePopupItem
&& !(this.isPopup && !this.isPopupClosed)
//#endif
) {
notifyStateChanged();
}
return true;
}
//#endif
} else if (this.additionalItemCommandListener != null && this.additionalItemCommandListener != this) {
this.additionalItemCommandListener.commandAction(cmd, this);
return true;
}
//#endif
return super.handleCommand(cmd);
}
//#endif
//#ifndef tmp.suppressAllCommands
public void setItemCommandListener(ItemCommandListener l) {
this.additionalItemCommandListener = l;
}
//#endif
/* (non-Javadoc)
* @see de.enough.polish.ui.Container#setItemsList(de.enough.polish.util.ArrayList)
*/
public void setItemsList(ArrayList itemsList) {
this.selectedIndex = -1;
super.setItemsList(itemsList);
}
/**
* Retrieves the choice type of this group
* @return the choice type, either MULTIPLE, EXCLUSIVE or POPUP
*/
public int getType()
{
return this.choiceType;
}
// //#ifdef polish.usePopupItem
// /* (non-Javadoc)
// * @see de.enough.polish.ui.Item#getItemHeightOverlap()
// */
// public int getItemHeightOverlap()
// {
// if (this.isPopup && !this.isPopupClosed) {
// int res = this.backgroundHeight - this.itemHeight;
// if (res > 0) {
// return res;
// }
// }
// return 0;
// }
// //#endif
}
| true | true | protected boolean handleKeyPressed(int keyCode, int gameAction) {
if (this.itemsList.size() == 0) {
//#debug
System.out.println("itemsList.size()==0, aborting handleKeyPressed");
return super.handleKeyPressed(keyCode, gameAction);
}
boolean gameActionIsFire = (gameAction == Canvas.FIRE);
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", isFire=" + gameActionIsFire);
//#if polish.ChoiceGroup.handleDefaultCommandFirst == true
if (gameActionIsFire) {
//#ifdef polish.usePopupItem
if (!this.isPopup || this.isPopupClosed) {
//#endif
ItemCommandListener listener = this.itemCommandListener;
//#ifndef tmp.suppressAllCommands
listener = this.additionalItemCommandListener;
//#endif
if (this.defaultCommand != null && listener != null) {
listener.commandAction( this.defaultCommand, this );
notifyItemPressedStart();
return true;
}
//#ifdef polish.usePopupItem
}
//#endif
}
//#endif
boolean processed = false;
//#ifdef polish.usePopupItem
if (!(this.isPopup && this.isPopupClosed)) {
processed = super.handleKeyPressed(keyCode, gameAction);
//#ifdef polish.css.popup-roundtrip
if (!processed && this.popupRoundTrip && this.isPopup && !this.isPopupClosed && this.itemsList.size() > 1) {
int nextFocusedIndex = -1;
if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8 ) {
// focus the first item of the opened POPUP choice:
for (int i= 0; i < this.itemsList.size(); i++ ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
} else if ( gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
for (int i= this.itemsList.size()-1; i >= 0; i-- ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
}
if (nextFocusedIndex != -1) {
focusChild(nextFocusedIndex);
processed = true;
}
}
//#endif
}
//#else
processed = super.handleKeyPressed(keyCode, gameAction);
//#endif
//#debug
System.out.println("ChoiceGroup: container handled keyPressEvent: " + processed);
if (!processed) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
//#ifdef polish.usePopupItem
if (this.isPopup && this.isPopupClosed && gameActionIsFire) {
notifyItemPressedStart(); // open popup in handleKeyReleased()
return true;
} else
//#endif
if (gameActionIsFire && choiceItem != null) {
choiceItem.notifyItemPressedStart();
return true;
} else {
//#if polish.Container.dontUseNumberKeys != true
if (keyCode >= Canvas.KEY_NUM1 && keyCode <= Canvas.KEY_NUM9) {
int index = keyCode - Canvas.KEY_NUM1;
if (index < this.itemsList.size()) {
Item item = getItem(index);
if (
//#ifdef polish.usePopupItem
(!this.isPopup || !this.isPopupClosed) &&
//#endif
(item.appearanceMode != PLAIN) )
{
// either this is not a POPUP or the POPUP is opened:
setSelectedIndex( index, true );
//#ifdef polish.usePopupItem
if (this.isPopup) {
closePopup();
}
//#endif
if (this.isImplicit) {
// call command listener:
Screen scr = getScreen();
if (scr != null) {
Command selectCmd = this.selectCommand;
if (selectCmd == null) {
selectCmd = List.SELECT_COMMAND;
}
scr.callCommandListener( selectCmd );
}
} else {
notifyStateChanged();
}
notifyItemPressedStart();
return true;
}
}
}
//#endif
// //#ifdef polish.usePopupItem
// if (this.isPopup && (this.isPopupClosed == false)) {
// this.closePopupOnKeyRelease = true;
// return true;
// }
// //#endif
}
}
// //#else
// // no popup item is used by this application:
// processed = super.handleKeyPressed(keyCode, gameAction);
// if (!processed) {
// if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5 && this.focusedIndex != -1 ) {
// ChoiceItem item = (ChoiceItem) this.focusedItem;
// item.notifyItemPressedStart();
// if (this.isMultiple) {
// item.toggleSelect();
// } else {
// setSelectedIndex(this.focusedIndex, true);
// }
// if ( this.choiceType != IMPLICIT )
// {
// notifyStateChanged();
// }
// return true;
// //#if polish.Container.dontUseNumberKeys != true
// } else if ( (keyCode >= Canvas.KEY_NUM1) && (keyCode <= Canvas.KEY_NUM9) ) {
// int index = keyCode - Canvas.KEY_NUM1;
// if (index < this.itemsList.size()) {
// Item item = getItem(index);
// if (item.appearanceMode != PLAIN) {
// setSelectedIndex( index, true );
// if (this.isImplicit) {
// // call command listener:
// Screen scr = getScreen();
// if (scr != null) {
// Command selectCmd = this.selectCommand;
// if (selectCmd == null) {
// selectCmd = List.SELECT_COMMAND;
// }
// scr.callCommandListener( selectCmd );
// }
// } else {
// notifyStateChanged();
// }
// }
// return true;
// }
// //#endif
// }
// }
// //#endif
return processed;
}
| protected boolean handleKeyPressed(int keyCode, int gameAction) {
if (this.itemsList.size() == 0) {
//#debug
System.out.println("itemsList.size()==0, aborting handleKeyPressed");
return super.handleKeyPressed(keyCode, gameAction);
}
boolean gameActionIsFire = (gameAction == Canvas.FIRE);
//#debug
System.out.println("handleKeyPressed( " + keyCode + ", " + gameAction + " ) for " + this + ", isFire=" + gameActionIsFire);
//#if polish.ChoiceGroup.handleDefaultCommandFirst == true
if (gameActionIsFire) {
//#ifdef polish.usePopupItem
if (!this.isPopup || this.isPopupClosed) {
//#endif
ItemCommandListener listener = this.itemCommandListener;
//#ifndef tmp.suppressAllCommands
listener = this.additionalItemCommandListener;
//#endif
if (this.defaultCommand != null && listener != null) {
listener.commandAction( this.defaultCommand, this );
notifyItemPressedStart();
return true;
}
//#ifdef polish.usePopupItem
}
//#endif
}
//#endif
boolean processed = false;
//#ifdef polish.usePopupItem
if (!(this.isPopup && this.isPopupClosed)) {
processed = super.handleKeyPressed(keyCode, gameAction);
//#ifdef polish.css.popup-roundtrip
if (!processed && this.popupRoundTrip && this.isPopup && !this.isPopupClosed && this.itemsList.size() > 1) {
int nextFocusedIndex = -1;
if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8 ) {
// focus the first item of the opened POPUP choice:
for (int i= 0; i < this.itemsList.size(); i++ ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
} else if ( gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
for (int i= this.itemsList.size()-1; i >= 0; i-- ) {
Item item = (Item) this.itemsList.get(i);
if (item.appearanceMode != PLAIN) {
nextFocusedIndex = i;
break;
}
}
}
if (nextFocusedIndex != -1) {
focusChild(nextFocusedIndex);
processed = true;
}
}
//#endif
}
//#else
//#if polish.Container.dontUseNumberKeys != true
if ( keyCode < Canvas.KEY_NUM0 || keyCode > Canvas.KEY_NUM9 ) {
processed = super.handleKeyPressed(keyCode, gameAction);
}
//#else
processed = super.handleKeyPressed(keyCode, gameAction);
//#endif
//#endif
//#debug
System.out.println("ChoiceGroup: container handled keyPressEvent: " + processed);
if (!processed) {
ChoiceItem choiceItem = (ChoiceItem) this.focusedItem;
//#ifdef polish.usePopupItem
if (this.isPopup && this.isPopupClosed && gameActionIsFire) {
notifyItemPressedStart(); // open popup in handleKeyReleased()
return true;
} else
//#endif
if (gameActionIsFire && choiceItem != null) {
choiceItem.notifyItemPressedStart();
return true;
} else {
//#if polish.Container.dontUseNumberKeys != true
if (keyCode >= Canvas.KEY_NUM1 && keyCode <= Canvas.KEY_NUM9) {
int index = keyCode - Canvas.KEY_NUM1;
if (index < this.itemsList.size()) {
Item item = getItem(index);
if (
//#ifdef polish.usePopupItem
(!this.isPopup || !this.isPopupClosed) &&
//#endif
(item.appearanceMode != PLAIN) )
{
// either this is not a POPUP or the POPUP is opened:
setSelectedIndex( index, true );
//#ifdef polish.usePopupItem
if (this.isPopup) {
closePopup();
}
//#endif
if (this.isImplicit) {
// call command listener:
Screen scr = getScreen();
if (scr != null) {
Command selectCmd = this.selectCommand;
if (selectCmd == null) {
selectCmd = List.SELECT_COMMAND;
}
scr.callCommandListener( selectCmd );
}
} else {
notifyStateChanged();
}
notifyItemPressedStart();
return true;
}
}
}
//#endif
// //#ifdef polish.usePopupItem
// if (this.isPopup && (this.isPopupClosed == false)) {
// this.closePopupOnKeyRelease = true;
// return true;
// }
// //#endif
}
}
// //#else
// // no popup item is used by this application:
// processed = super.handleKeyPressed(keyCode, gameAction);
// if (!processed) {
// if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5 && this.focusedIndex != -1 ) {
// ChoiceItem item = (ChoiceItem) this.focusedItem;
// item.notifyItemPressedStart();
// if (this.isMultiple) {
// item.toggleSelect();
// } else {
// setSelectedIndex(this.focusedIndex, true);
// }
// if ( this.choiceType != IMPLICIT )
// {
// notifyStateChanged();
// }
// return true;
// //#if polish.Container.dontUseNumberKeys != true
// } else if ( (keyCode >= Canvas.KEY_NUM1) && (keyCode <= Canvas.KEY_NUM9) ) {
// int index = keyCode - Canvas.KEY_NUM1;
// if (index < this.itemsList.size()) {
// Item item = getItem(index);
// if (item.appearanceMode != PLAIN) {
// setSelectedIndex( index, true );
// if (this.isImplicit) {
// // call command listener:
// Screen scr = getScreen();
// if (scr != null) {
// Command selectCmd = this.selectCommand;
// if (selectCmd == null) {
// selectCmd = List.SELECT_COMMAND;
// }
// scr.callCommandListener( selectCmd );
// }
// } else {
// notifyStateChanged();
// }
// }
// return true;
// }
// //#endif
// }
// }
// //#endif
return processed;
}
|
diff --git a/asm/src/org/objectweb/asm/AnnotationWriter.java b/asm/src/org/objectweb/asm/AnnotationWriter.java
index 2d6002da..46fa6a95 100644
--- a/asm/src/org/objectweb/asm/AnnotationWriter.java
+++ b/asm/src/org/objectweb/asm/AnnotationWriter.java
@@ -1,321 +1,323 @@
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000,2002,2003 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.objectweb.asm;
/**
* An {@link AnnotationVisitor} that generates annotations in bytecode form.
*
* @author Eric Bruneton
* @author Eugene Kuleshov
*/
final class AnnotationWriter implements AnnotationVisitor {
/**
* The class writer to which this annotation must be added.
*/
private final ClassWriter cw;
/**
* The number of values in this annotation.
*/
private int size;
/**
* <tt>true<tt> if values are named, <tt>false</tt> otherwise. Annotation
* writers used for annotation default and annotation arrays use unnamed
* values.
*/
private final boolean named;
/**
* The annotation values in bytecode form. This byte vector only contains the
* values themselves, i.e. the number of values must be stored as a unsigned
* short just before these bytes.
*/
private final ByteVector bv;
/**
* The byte vector to be used to store the number of values of this
* annotation. See {@link #bv}.
*/
private final ByteVector parent;
/**
* Where the number of values of this annotation must be stored in
* {@link #parent}.
*/
private final int offset;
/**
* Next annotation writer. This field is used to store annotation lists.
*/
AnnotationWriter next;
/**
* Previous annotation writer. This field is used to store annotation lists.
*/
AnnotationWriter prev;
// --------------------------------------------------------------------------
// Constructor
// --------------------------------------------------------------------------
/**
* Constructs a new {@link AnnotationWriter}.
*
* @param cw the class writer to which this annotation must be added.
* @param named <tt>true<tt> if values are named, <tt>false</tt> otherwise.
* @param bv where the annotation values must be stored.
* @param parent where the number of annotation values must be stored.
* @param offset where in <tt>parent</tt> the number of annotation values must
* be stored.
*/
AnnotationWriter (
final ClassWriter cw,
final boolean named,
final ByteVector bv,
final ByteVector parent,
final int offset)
{
this.cw = cw;
this.named = named;
this.bv = bv;
this.parent = parent;
this.offset = offset;
}
// --------------------------------------------------------------------------
// Implementation of the AnnotationVisitor interface
// --------------------------------------------------------------------------
public void visit (final String name, final Object value) {
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
- if (value instanceof Byte) {
+ if (value instanceof String) {
+ bv.put12('s', cw.newUTF8((String)value));
+ } else if (value instanceof Byte) {
bv.put12('B', cw.newInteger(((Byte)value).byteValue()).index);
} else if (value instanceof Boolean) {
bv.put12('Z', cw.newInteger(((Boolean)value).booleanValue() ? 1 : 0).index);
} else if (value instanceof Character) {
bv.put12('C', cw.newInteger(((Character)value).charValue()).index);
} else if (value instanceof Short) {
bv.put12('S', cw.newInteger(((Short)value).shortValue()).index);
} else if (value instanceof Type) {
bv.put12('c', cw.newUTF8(((Type)value).getDescriptor()));
} else if (value instanceof byte[]) {
byte[] v = (byte[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('B', cw.newInteger(v[i]).index);
}
// support for arrays: TODO should we keep this?
} else if (value instanceof boolean[]) {
boolean[] v = (boolean[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('Z', cw.newInteger(v[i] ? 1 : 0).index);
}
} else if (value instanceof short[]) {
short[] v = (short[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('S', cw.newInteger(v[i]).index);
}
} else if (value instanceof char[]) {
char[] v = (char[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('C', cw.newInteger(v[i]).index);
}
} else if (value instanceof int[]) {
int[] v = (int[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('I', cw.newInteger(v[i]).index);
}
} else if (value instanceof long[]) {
long[] v = (long[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('J', cw.newLong(v[i]).index);
}
} else if (value instanceof float[]) {
float[] v = (float[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('F', cw.newFloat(v[i]).index);
}
} else if (value instanceof double[]) {
double[] v = (double[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('D', cw.newDouble(v[i]).index);
}
} else {
Item i = cw.newConstItem(value);
bv.put12(i.type, i.index);
}
}
public void visitEnum (
final String name,
final String desc,
final String value)
{
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
bv.put12('e', cw.newUTF8(desc)).putShort(cw.newUTF8(value));
}
public AnnotationVisitor visitAnnotation (
final String name,
final String desc)
{
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
// write tag and type, and reserve space for values count
bv.put12('@', cw.newUTF8(desc)).putShort(0);
return new AnnotationWriter(cw, true, bv, bv, bv.length - 2);
}
public AnnotationVisitor visitArray (final String name) {
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
// write tag, and reserve space for array size
bv.put12('[', 0);
return new AnnotationWriter(cw, false, bv, bv, bv.length - 2);
}
public void visitEnd () {
byte[] data = parent.data;
data[offset] = (byte)(size >>> 8);
data[offset+1] = (byte)size;
}
// --------------------------------------------------------------------------
// Utility methods
// --------------------------------------------------------------------------
/**
* Returns the size of this annotation writer list.
*
* @return the size of this annotation writer list.
*/
int getSize () {
int size = 0;
AnnotationWriter aw = this;
while (aw != null) {
size += aw.bv.length;
aw = aw.next;
}
return size;
}
/**
* Puts the annotations of this annotation writer list into the given byte
* vector.
*
* @param out where the annotations must be put.
*/
void put (final ByteVector out) {
int n = 0;
int size = 2;
AnnotationWriter aw = this;
AnnotationWriter last = null;
while (aw != null) {
++n;
size += aw.bv.length;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putInt(size);
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
}
/**
* Puts the given annotation lists into the given byte vector.
*
* @param panns an array of annotation writer lists.
* @param out where the annotations must be put.
*/
static void put (final AnnotationWriter[] panns, final ByteVector out) {
int size = 1 + 2*panns.length;
for (int i = 0; i < panns.length; ++i) {
size += panns[i] == null ? 0 : panns[i].getSize();
}
out.putInt(size).putByte(panns.length);
for (int i = 0; i < panns.length; ++i) {
AnnotationWriter aw = panns[i];
AnnotationWriter last = null;
int n = 0;
while (aw != null) {
++n;
aw.visitEnd(); // in case user forgot to call visitEnd
aw.prev = last;
last = aw;
aw = aw.next;
}
out.putShort(n);
aw = last;
while (aw != null) {
out.putByteArray(aw.bv.data, 0, aw.bv.length);
aw = aw.prev;
}
}
}
}
| true | true | public void visit (final String name, final Object value) {
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
if (value instanceof Byte) {
bv.put12('B', cw.newInteger(((Byte)value).byteValue()).index);
} else if (value instanceof Boolean) {
bv.put12('Z', cw.newInteger(((Boolean)value).booleanValue() ? 1 : 0).index);
} else if (value instanceof Character) {
bv.put12('C', cw.newInteger(((Character)value).charValue()).index);
} else if (value instanceof Short) {
bv.put12('S', cw.newInteger(((Short)value).shortValue()).index);
} else if (value instanceof Type) {
bv.put12('c', cw.newUTF8(((Type)value).getDescriptor()));
} else if (value instanceof byte[]) {
byte[] v = (byte[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('B', cw.newInteger(v[i]).index);
}
// support for arrays: TODO should we keep this?
} else if (value instanceof boolean[]) {
boolean[] v = (boolean[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('Z', cw.newInteger(v[i] ? 1 : 0).index);
}
} else if (value instanceof short[]) {
short[] v = (short[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('S', cw.newInteger(v[i]).index);
}
} else if (value instanceof char[]) {
char[] v = (char[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('C', cw.newInteger(v[i]).index);
}
} else if (value instanceof int[]) {
int[] v = (int[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('I', cw.newInteger(v[i]).index);
}
} else if (value instanceof long[]) {
long[] v = (long[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('J', cw.newLong(v[i]).index);
}
} else if (value instanceof float[]) {
float[] v = (float[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('F', cw.newFloat(v[i]).index);
}
} else if (value instanceof double[]) {
double[] v = (double[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('D', cw.newDouble(v[i]).index);
}
} else {
Item i = cw.newConstItem(value);
bv.put12(i.type, i.index);
}
}
| public void visit (final String name, final Object value) {
++size;
if (named) {
bv.putShort(cw.newUTF8(name));
}
if (value instanceof String) {
bv.put12('s', cw.newUTF8((String)value));
} else if (value instanceof Byte) {
bv.put12('B', cw.newInteger(((Byte)value).byteValue()).index);
} else if (value instanceof Boolean) {
bv.put12('Z', cw.newInteger(((Boolean)value).booleanValue() ? 1 : 0).index);
} else if (value instanceof Character) {
bv.put12('C', cw.newInteger(((Character)value).charValue()).index);
} else if (value instanceof Short) {
bv.put12('S', cw.newInteger(((Short)value).shortValue()).index);
} else if (value instanceof Type) {
bv.put12('c', cw.newUTF8(((Type)value).getDescriptor()));
} else if (value instanceof byte[]) {
byte[] v = (byte[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('B', cw.newInteger(v[i]).index);
}
// support for arrays: TODO should we keep this?
} else if (value instanceof boolean[]) {
boolean[] v = (boolean[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('Z', cw.newInteger(v[i] ? 1 : 0).index);
}
} else if (value instanceof short[]) {
short[] v = (short[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('S', cw.newInteger(v[i]).index);
}
} else if (value instanceof char[]) {
char[] v = (char[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('C', cw.newInteger(v[i]).index);
}
} else if (value instanceof int[]) {
int[] v = (int[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('I', cw.newInteger(v[i]).index);
}
} else if (value instanceof long[]) {
long[] v = (long[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('J', cw.newLong(v[i]).index);
}
} else if (value instanceof float[]) {
float[] v = (float[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('F', cw.newFloat(v[i]).index);
}
} else if (value instanceof double[]) {
double[] v = (double[])value;
bv.put12('[', v.length);
for (int i = 0; i < v.length; i++) {
bv.put12('D', cw.newDouble(v[i]).index);
}
} else {
Item i = cw.newConstItem(value);
bv.put12(i.type, i.index);
}
}
|
diff --git a/src/java/org/apache/commons/daemon/Main.java b/src/java/org/apache/commons/daemon/Main.java
index 33c1d34..0fae05d 100644
--- a/src/java/org/apache/commons/daemon/Main.java
+++ b/src/java/org/apache/commons/daemon/Main.java
@@ -1,241 +1,244 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* @version $Id: Main.java 937350 2010-04-23 16:03:39Z mturk $ */
package org.apache.commons.daemon;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.daemon.support.DaemonConfiguration;
/**
* Implementation of the Daemon that allows running
* standard applications as daemons.
* The applications must have the mechanism to manage
* the application lifecycle.
*
* @version 1.0 <i>(SVN $Revision: 925053 $)</i>
* @author Mladen Turk
*/
public class Main implements Daemon
{
private final static String ARGS = "args";
private final static String START_CLASS = "start";
private final static String START_METHOD = "start.method";
private final static String STOP_CLASS = "stop";
private final static String STOP_METHOD = "stop.method";
private final static String STOP_ARGS = "stop.args";
private String configFileName = null;
private final DaemonConfiguration config;
private final Invoker startup;
private final Invoker shutdown;
public Main()
{
super();
config = new DaemonConfiguration();
startup = new Invoker();
shutdown = new Invoker();
}
/**
* Called from DaemonLoader on init stage.
*/
public void init(DaemonContext context)
throws Exception
{
String[] args = context.getArguments();
if (args != null) {
int i;
// Parse our arguments and remove them
// from the final argument array we are
// passing to our child.
for (i = 0; i < args.length; i++) {
if (args[i].equals("--")) {
// Done with argument processing
break;
}
else if (args[i].equals("-daemon-properties")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
configFileName = args[i];
}
else if (args[i].equals("-start")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setClassName(args[i]);
}
- else if (args[i].equals("-start-mehod")) {
+ else if (args[i].equals("-start-method")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setMethodName(args[i]);
}
else if (args[i].equals("-stop")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setClassName(args[i]);
}
else if (args[i].equals("-stop-method")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setMethodName(args[i]);
}
else if (args[i].equals("-stop-argument")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
String[] aa = new String[1];
aa[0] = args[i];
shutdown.addArguments(aa);
}
else {
// This is not our option.
// Everything else will be forwarded to the main
break;
}
}
- String[] copy = new String[args.length - i];
- startup.addArguments(copy);
+ if (args.length > i) {
+ String[] copy = new String[args.length - i];
+ System.arraycopy(args, i, copy, 0, copy.length);
+ startup.addArguments(copy);
+ }
}
if (config.load(configFileName)) {
// Setup params if not set via cmdline.
startup.setClassName(config.getProperty(START_CLASS));
startup.setMethodName(config.getProperty(START_METHOD));
// Merge the config with command line arguments
startup.addArguments(config.getPropertyArray(ARGS));
shutdown.setClassName(config.getProperty(STOP_CLASS));
shutdown.setMethodName(config.getProperty(STOP_METHOD));
shutdown.addArguments(config.getPropertyArray(STOP_ARGS));
}
startup.validate();
shutdown.validate();
}
/**
*/
public void start()
throws Exception
{
startup.invoke();
}
/**
*/
public void stop()
throws Exception
{
shutdown.invoke();
}
/**
*/
public void destroy()
{
// Nothing for the moment
System.err.println("Main: instance " + this.hashCode() + " destroy");
}
// Internal class for wrapping the start/stop methods
class Invoker
{
private String name = null;
private String call = null;
private String[] args = null;
private Method inst = null;
private Class main = null;
protected Invoker()
{
}
protected void setClassName(String name)
{
if (this.name == null)
this.name = name;
}
protected void setMethodName(String name)
{
if (this.call == null)
this.call = name;
}
protected void addArguments(String[] args)
{
if (args != null) {
ArrayList aa = new ArrayList();
if (this.args != null)
aa.addAll(Arrays.asList(this.args));
aa.addAll(Arrays.asList(args));
this.args = Arrays.copyOf(aa.toArray(), aa.size(), String[].class);
}
}
protected void invoke()
throws Exception
{
if (name.equals("System") && call.equals("exit")) {
// Just call a System.exit()
// The start method was probably installed
// a shutdown hook.
System.exit(0);
}
else {
Object obj = main.newInstance();
Object arg[] = new Object[1];
arg[0] = args;
inst.invoke(obj, arg);
}
}
// Load the class using reflection
protected void validate()
throws Exception
{
/* Check the class name */
if (name == null) {
name = "System";
call = "exit";
return;
}
if (args == null)
args = new String[0];
if (call == null)
call = "main";
// Get the ClassLoader loading this class
ClassLoader cl = Main.class.getClassLoader();
if (cl == null)
throw new NullPointerException("Cannot retrieve ClassLoader instance");
Class[] ca = new Class[1];
ca[0] = args.getClass();
// Find the required class
main = cl.loadClass(name);
if (main == null)
throw new ClassNotFoundException(name);
// Find the required method.
// NoSuchMethodException will be thrown if matching method
// is not found.
inst = main.getMethod(call, ca);
}
}
}
| false | true | public void init(DaemonContext context)
throws Exception
{
String[] args = context.getArguments();
if (args != null) {
int i;
// Parse our arguments and remove them
// from the final argument array we are
// passing to our child.
for (i = 0; i < args.length; i++) {
if (args[i].equals("--")) {
// Done with argument processing
break;
}
else if (args[i].equals("-daemon-properties")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
configFileName = args[i];
}
else if (args[i].equals("-start")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setClassName(args[i]);
}
else if (args[i].equals("-start-mehod")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setMethodName(args[i]);
}
else if (args[i].equals("-stop")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setClassName(args[i]);
}
else if (args[i].equals("-stop-method")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setMethodName(args[i]);
}
else if (args[i].equals("-stop-argument")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
String[] aa = new String[1];
aa[0] = args[i];
shutdown.addArguments(aa);
}
else {
// This is not our option.
// Everything else will be forwarded to the main
break;
}
}
String[] copy = new String[args.length - i];
startup.addArguments(copy);
}
if (config.load(configFileName)) {
// Setup params if not set via cmdline.
startup.setClassName(config.getProperty(START_CLASS));
startup.setMethodName(config.getProperty(START_METHOD));
// Merge the config with command line arguments
startup.addArguments(config.getPropertyArray(ARGS));
shutdown.setClassName(config.getProperty(STOP_CLASS));
shutdown.setMethodName(config.getProperty(STOP_METHOD));
shutdown.addArguments(config.getPropertyArray(STOP_ARGS));
}
startup.validate();
shutdown.validate();
}
| public void init(DaemonContext context)
throws Exception
{
String[] args = context.getArguments();
if (args != null) {
int i;
// Parse our arguments and remove them
// from the final argument array we are
// passing to our child.
for (i = 0; i < args.length; i++) {
if (args[i].equals("--")) {
// Done with argument processing
break;
}
else if (args[i].equals("-daemon-properties")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
configFileName = args[i];
}
else if (args[i].equals("-start")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setClassName(args[i]);
}
else if (args[i].equals("-start-method")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
startup.setMethodName(args[i]);
}
else if (args[i].equals("-stop")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setClassName(args[i]);
}
else if (args[i].equals("-stop-method")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
shutdown.setMethodName(args[i]);
}
else if (args[i].equals("-stop-argument")) {
if (++i == args.length)
throw new IllegalArgumentException(args[i - 1]);
String[] aa = new String[1];
aa[0] = args[i];
shutdown.addArguments(aa);
}
else {
// This is not our option.
// Everything else will be forwarded to the main
break;
}
}
if (args.length > i) {
String[] copy = new String[args.length - i];
System.arraycopy(args, i, copy, 0, copy.length);
startup.addArguments(copy);
}
}
if (config.load(configFileName)) {
// Setup params if not set via cmdline.
startup.setClassName(config.getProperty(START_CLASS));
startup.setMethodName(config.getProperty(START_METHOD));
// Merge the config with command line arguments
startup.addArguments(config.getPropertyArray(ARGS));
shutdown.setClassName(config.getProperty(STOP_CLASS));
shutdown.setMethodName(config.getProperty(STOP_METHOD));
shutdown.addArguments(config.getPropertyArray(STOP_ARGS));
}
startup.validate();
shutdown.validate();
}
|
diff --git a/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/internal/widgets/menuitemkit/MenuItemLCAUtil.java b/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/internal/widgets/menuitemkit/MenuItemLCAUtil.java
index 3741bb08a..2e18b9faa 100644
--- a/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/internal/widgets/menuitemkit/MenuItemLCAUtil.java
+++ b/bundles/org.eclipse.rap.rwt/src/org/eclipse/swt/internal/widgets/menuitemkit/MenuItemLCAUtil.java
@@ -1,49 +1,53 @@
/*******************************************************************************
* Copyright (c) 2002-2006 Innoopract Informationssysteme GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Innoopract Informationssysteme GmbH - initial API and implementation
******************************************************************************/
package org.eclipse.swt.internal.widgets.menuitemkit;
import java.io.IOException;
import org.eclipse.rwt.internal.lifecycle.JSConst;
import org.eclipse.rwt.lifecycle.JSWriter;
import org.eclipse.swt.internal.widgets.ItemLCAUtil;
import org.eclipse.swt.internal.widgets.Props;
import org.eclipse.swt.widgets.MenuItem;
final class MenuItemLCAUtil {
static void newItem( final MenuItem menuItem,
final String jsClass,
final boolean isQxAtom )
throws IOException
{
JSWriter writer = JSWriter.getWriterFor( menuItem );
writer.newWidget( jsClass );
if( isQxAtom ) {
writer.callStatic( "org.eclipse.swt.MenuUtil.setLabelMode",
new Object[] { menuItem } );
}
- writer.call( menuItem.getParent(), "add", new Object[]{ menuItem } );
+// writer.call( menuItem.getParent(), "add", new Object[]{ menuItem } );
+ int index = menuItem.getParent().indexOf( menuItem );
+ writer.call( menuItem.getParent(),
+ "addAt",
+ new Object[]{ menuItem, new Integer( index ) } );
}
static void writeEnabled( final MenuItem menuItem ) throws IOException {
Boolean newValue = Boolean.valueOf( menuItem.isEnabled() );
JSWriter writer = JSWriter.getWriterFor( menuItem );
Boolean defValue = Boolean.TRUE;
writer.set( Props.ENABLED, JSConst.QX_FIELD_ENABLED, newValue, defValue );
}
static void writeImageAndText( final MenuItem menuItem ) throws IOException {
ItemLCAUtil.writeText( menuItem, true );
ItemLCAUtil.writeImage( menuItem );
}
}
| true | true | static void newItem( final MenuItem menuItem,
final String jsClass,
final boolean isQxAtom )
throws IOException
{
JSWriter writer = JSWriter.getWriterFor( menuItem );
writer.newWidget( jsClass );
if( isQxAtom ) {
writer.callStatic( "org.eclipse.swt.MenuUtil.setLabelMode",
new Object[] { menuItem } );
}
writer.call( menuItem.getParent(), "add", new Object[]{ menuItem } );
}
| static void newItem( final MenuItem menuItem,
final String jsClass,
final boolean isQxAtom )
throws IOException
{
JSWriter writer = JSWriter.getWriterFor( menuItem );
writer.newWidget( jsClass );
if( isQxAtom ) {
writer.callStatic( "org.eclipse.swt.MenuUtil.setLabelMode",
new Object[] { menuItem } );
}
// writer.call( menuItem.getParent(), "add", new Object[]{ menuItem } );
int index = menuItem.getParent().indexOf( menuItem );
writer.call( menuItem.getParent(),
"addAt",
new Object[]{ menuItem, new Integer( index ) } );
}
|
diff --git a/src/com/android/email/activity/MessagesAdapter.java b/src/com/android/email/activity/MessagesAdapter.java
index d97fad95..07717f8d 100644
--- a/src/com/android/email/activity/MessagesAdapter.java
+++ b/src/com/android/email/activity/MessagesAdapter.java
@@ -1,245 +1,248 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.activity;
import com.android.email.Email;
import com.android.email.R;
import com.android.email.ResourceHelper;
import com.android.email.Utility;
import com.android.email.data.ThrottlingCursorLoader;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Message;
import com.android.email.provider.EmailContent.MessageColumns;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import java.util.HashSet;
import java.util.Set;
/**
* This class implements the adapter for displaying messages based on cursors.
*/
/* package */ class MessagesAdapter extends CursorAdapter {
private static final String STATE_CHECKED_ITEMS =
"com.android.email.activity.MessagesAdapter.checkedItems";
/* package */ static final String[] MESSAGE_PROJECTION = new String[] {
EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY,
MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP,
MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT,
MessageColumns.FLAGS, MessageColumns.SNIPPET
};
public static final int COLUMN_ID = 0;
public static final int COLUMN_MAILBOX_KEY = 1;
public static final int COLUMN_ACCOUNT_KEY = 2;
public static final int COLUMN_DISPLAY_NAME = 3;
public static final int COLUMN_SUBJECT = 4;
public static final int COLUMN_DATE = 5;
public static final int COLUMN_READ = 6;
public static final int COLUMN_FAVORITE = 7;
public static final int COLUMN_ATTACHMENTS = 8;
public static final int COLUMN_FLAGS = 9;
public static final int COLUMN_SNIPPET = 10;
private final ResourceHelper mResourceHelper;
/** If true, show color chips. */
private boolean mShowColorChips;
/**
* Set of seleced message IDs.
*/
private final HashSet<Long> mSelectedSet = new HashSet<Long>();
/**
* Callback from MessageListAdapter. All methods are called on the UI thread.
*/
public interface Callback {
/** Called when the use starts/unstars a message */
void onAdapterFavoriteChanged(MessageListItem itemView, boolean newFavorite);
/** Called when the user selects/unselects a message */
void onAdapterSelectedChanged(MessageListItem itemView, boolean newSelected,
int mSelectedCount);
}
private final Callback mCallback;
public MessagesAdapter(Context context, Callback callback) {
super(context.getApplicationContext(), null, 0 /* no auto requery */);
mResourceHelper = ResourceHelper.getInstance(context);
mCallback = callback;
}
public void onSaveInstanceState(Bundle outState) {
Set<Long> checkedset = getSelectedSet();
long[] checkedarray = new long[checkedset.size()];
int i = 0;
for (Long l : checkedset) {
checkedarray[i] = l;
i++;
}
outState.putLongArray(STATE_CHECKED_ITEMS, checkedarray);
}
public void loadState(Bundle savedInstanceState) {
Set<Long> checkedset = getSelectedSet();
for (long l: savedInstanceState.getLongArray(STATE_CHECKED_ITEMS)) {
checkedset.add(l);
}
}
/**
* Set true for combined mailboxes.
*/
public void setShowColorChips(boolean show) {
mShowColorChips = show;
}
public Set<Long> getSelectedSet() {
return mSelectedSet;
}
public boolean isSelected(MessageListItem itemView) {
return mSelectedSet.contains(itemView.mMessageId);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Reset the view (in case it was recycled) and prepare for binding
MessageListItem itemView = (MessageListItem) view;
itemView.bindViewInit(this);
// Load the public fields in the view (for later use)
itemView.mMessageId = cursor.getLong(COLUMN_ID);
itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY);
final long accountId = cursor.getLong(COLUMN_ACCOUNT_KEY);
itemView.mAccountId = accountId;
itemView.mRead = cursor.getInt(COLUMN_READ) != 0;
itemView.mIsFavorite = cursor.getInt(COLUMN_FAVORITE) != 0;
itemView.mHasInvite =
(cursor.getInt(COLUMN_FLAGS) & Message.FLAG_INCOMING_MEETING_INVITE) != 0;
itemView.mHasAttachment = cursor.getInt(COLUMN_ATTACHMENTS) != 0;
itemView.mTimestamp = cursor.getLong(COLUMN_DATE);
itemView.mSender = cursor.getString(COLUMN_DISPLAY_NAME);
itemView.mSnippet = cursor.getString(COLUMN_SNIPPET);
itemView.mSnippetLineCount = MessageListItem.NEEDS_LAYOUT;
itemView.mColorChipPaint =
mShowColorChips ? mResourceHelper.getAccountColorPaint(accountId) : null;
String text = cursor.getString(COLUMN_SUBJECT);
String snippet = cursor.getString(COLUMN_SNIPPET);
if (!TextUtils.isEmpty(snippet)) {
if (TextUtils.isEmpty(text)) {
text = snippet;
} else {
text = context.getString(R.string.message_list_snippet, text, snippet);
}
}
+ if (text == null) {
+ text = "";
+ }
itemView.mSnippet = text;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//return mInflater.inflate(R.layout.message_list_item, parent, false);
MessageListItem item = new MessageListItem(context);
item.setVisibility(View.VISIBLE);
return item;
}
public void toggleSelected(MessageListItem itemView) {
updateSelected(itemView, !isSelected(itemView));
}
/**
* This is used as a callback from the list items, to set the selected state
*
* <p>Must be called on the UI thread.
*
* @param itemView the item being changed
* @param newSelected the new value of the selected flag (checkbox state)
*/
private void updateSelected(MessageListItem itemView, boolean newSelected) {
if (newSelected) {
mSelectedSet.add(itemView.mMessageId);
} else {
mSelectedSet.remove(itemView.mMessageId);
}
if (mCallback != null) {
mCallback.onAdapterSelectedChanged(itemView, newSelected, mSelectedSet.size());
}
}
/**
* This is used as a callback from the list items, to set the favorite state
*
* <p>Must be called on the UI thread.
*
* @param itemView the item being changed
* @param newFavorite the new value of the favorite flag (star state)
*/
public void updateFavorite(MessageListItem itemView, boolean newFavorite) {
changeFavoriteIcon(itemView, newFavorite);
if (mCallback != null) {
mCallback.onAdapterFavoriteChanged(itemView, newFavorite);
}
}
private void changeFavoriteIcon(MessageListItem view, boolean isFavorite) {
view.invalidate();
}
public static Loader<Cursor> createLoader(Context context, long mailboxId) {
if (Email.DEBUG_LIFECYCLE && Email.DEBUG) {
Log.d(Email.LOG_TAG, "MessagesAdapter createLoader mailboxId=" + mailboxId);
}
return new MessagesCursorLoader(context, mailboxId);
}
private static class MessagesCursorLoader extends ThrottlingCursorLoader {
private final Context mContext;
private final long mMailboxId;
public MessagesCursorLoader(Context context, long mailboxId) {
// Initialize with no where clause. We'll set it later.
super(context, EmailContent.Message.CONTENT_URI,
MESSAGE_PROJECTION, null, null,
EmailContent.MessageColumns.TIMESTAMP + " DESC");
mContext = context;
mMailboxId = mailboxId;
}
@Override
public Cursor loadInBackground() {
// Determine the where clause. (Can't do this on the UI thread.)
setSelection(Utility.buildMailboxIdSelection(mContext, mMailboxId));
// Then do a query.
return super.loadInBackground();
}
}
}
| true | true | public void bindView(View view, Context context, Cursor cursor) {
// Reset the view (in case it was recycled) and prepare for binding
MessageListItem itemView = (MessageListItem) view;
itemView.bindViewInit(this);
// Load the public fields in the view (for later use)
itemView.mMessageId = cursor.getLong(COLUMN_ID);
itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY);
final long accountId = cursor.getLong(COLUMN_ACCOUNT_KEY);
itemView.mAccountId = accountId;
itemView.mRead = cursor.getInt(COLUMN_READ) != 0;
itemView.mIsFavorite = cursor.getInt(COLUMN_FAVORITE) != 0;
itemView.mHasInvite =
(cursor.getInt(COLUMN_FLAGS) & Message.FLAG_INCOMING_MEETING_INVITE) != 0;
itemView.mHasAttachment = cursor.getInt(COLUMN_ATTACHMENTS) != 0;
itemView.mTimestamp = cursor.getLong(COLUMN_DATE);
itemView.mSender = cursor.getString(COLUMN_DISPLAY_NAME);
itemView.mSnippet = cursor.getString(COLUMN_SNIPPET);
itemView.mSnippetLineCount = MessageListItem.NEEDS_LAYOUT;
itemView.mColorChipPaint =
mShowColorChips ? mResourceHelper.getAccountColorPaint(accountId) : null;
String text = cursor.getString(COLUMN_SUBJECT);
String snippet = cursor.getString(COLUMN_SNIPPET);
if (!TextUtils.isEmpty(snippet)) {
if (TextUtils.isEmpty(text)) {
text = snippet;
} else {
text = context.getString(R.string.message_list_snippet, text, snippet);
}
}
itemView.mSnippet = text;
}
| public void bindView(View view, Context context, Cursor cursor) {
// Reset the view (in case it was recycled) and prepare for binding
MessageListItem itemView = (MessageListItem) view;
itemView.bindViewInit(this);
// Load the public fields in the view (for later use)
itemView.mMessageId = cursor.getLong(COLUMN_ID);
itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY);
final long accountId = cursor.getLong(COLUMN_ACCOUNT_KEY);
itemView.mAccountId = accountId;
itemView.mRead = cursor.getInt(COLUMN_READ) != 0;
itemView.mIsFavorite = cursor.getInt(COLUMN_FAVORITE) != 0;
itemView.mHasInvite =
(cursor.getInt(COLUMN_FLAGS) & Message.FLAG_INCOMING_MEETING_INVITE) != 0;
itemView.mHasAttachment = cursor.getInt(COLUMN_ATTACHMENTS) != 0;
itemView.mTimestamp = cursor.getLong(COLUMN_DATE);
itemView.mSender = cursor.getString(COLUMN_DISPLAY_NAME);
itemView.mSnippet = cursor.getString(COLUMN_SNIPPET);
itemView.mSnippetLineCount = MessageListItem.NEEDS_LAYOUT;
itemView.mColorChipPaint =
mShowColorChips ? mResourceHelper.getAccountColorPaint(accountId) : null;
String text = cursor.getString(COLUMN_SUBJECT);
String snippet = cursor.getString(COLUMN_SNIPPET);
if (!TextUtils.isEmpty(snippet)) {
if (TextUtils.isEmpty(text)) {
text = snippet;
} else {
text = context.getString(R.string.message_list_snippet, text, snippet);
}
}
if (text == null) {
text = "";
}
itemView.mSnippet = text;
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/portal/behaviors/FutureUpdateBehavior.java b/src/main/java/pl/psnc/dl/wf4ever/portal/behaviors/FutureUpdateBehavior.java
index 8ca8211..f9db92d 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/portal/behaviors/FutureUpdateBehavior.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/portal/behaviors/FutureUpdateBehavior.java
@@ -1,111 +1,114 @@
package pl.psnc.dl.wf4ever.portal.behaviors;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractAjaxTimerBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.time.Duration;
/**
* An Ajax timer behavior that polls a future waiting for it to be done and once it is updates the component model,
* stops the timer and calls a callback function.
*
* Based on https://gist.github.com/jonnywray/636875.
*
* @param <T>
* @author Jonny Wray
* @author Piotr Hołubowicz
*/
public class FutureUpdateBehavior<T> extends AbstractAjaxTimerBehavior {
/** id. */
private static final long serialVersionUID = 1293362922535868808L;
/** Logger. */
private static final Logger LOGGER = Logger.getLogger(FutureUpdateBehavior.class);
/** The job that will finish in some time. */
private IModel<Future<T>> future;
/** The model to save the job result to. */
private IModel<T> model;
private Component[] components;
/**
* Constructor.
*
* @param updateInterval
* the interval between AJAX polls
* @param future
* The job that will finish in some time
* @param model
* The model to save the job result to
*/
public FutureUpdateBehavior(Duration updateInterval, IModel<Future<T>> future, IModel<T> model,
Component... components) {
super(updateInterval);
this.model = model;
this.future = future;
this.components = components;
}
/**
* The job has finished successfully. The default implementation posts an event.
*
* @param target
* AJAX target
*/
protected void onPostSuccess(AjaxRequestTarget target) {
for (Component component : components) {
target.add(component);
}
}
/**
* The job has thrown an exception or was interrupted.
*
* @param target
* AJAX target
* @param e
* the exception
*/
protected void onUpdateError(AjaxRequestTarget target, Exception e) {
getComponent().error("Could not finish the task: " + e.getLocalizedMessage());
target.add(getComponent());
LOGGER.error("Could not finish the task", e);
}
@Override
protected void onTimer(final AjaxRequestTarget target) {
- if (future.getObject().isDone()) {
+ if (future.getObject() == null) {
+ stop();
+ LOGGER.warn("The future object is no longer available");
+ } else if (future.getObject().isDone()) {
try {
T data = future.getObject().get();
if (model != null) {
model.setObject(data);
}
stop();
onPostSuccess(target);
} catch (InterruptedException | ExecutionException e) {
stop();
String message = "Error occurred while fetching data: " + e.getMessage();
LOGGER.error(message, e);
onUpdateError(target, e);
}
}
}
@Override
public CharSequence getCallbackScript() {
return super.getCallbackScript();
}
}
| true | true | protected void onTimer(final AjaxRequestTarget target) {
if (future.getObject().isDone()) {
try {
T data = future.getObject().get();
if (model != null) {
model.setObject(data);
}
stop();
onPostSuccess(target);
} catch (InterruptedException | ExecutionException e) {
stop();
String message = "Error occurred while fetching data: " + e.getMessage();
LOGGER.error(message, e);
onUpdateError(target, e);
}
}
}
| protected void onTimer(final AjaxRequestTarget target) {
if (future.getObject() == null) {
stop();
LOGGER.warn("The future object is no longer available");
} else if (future.getObject().isDone()) {
try {
T data = future.getObject().get();
if (model != null) {
model.setObject(data);
}
stop();
onPostSuccess(target);
} catch (InterruptedException | ExecutionException e) {
stop();
String message = "Error occurred while fetching data: " + e.getMessage();
LOGGER.error(message, e);
onUpdateError(target, e);
}
}
}
|
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
index 177daabf..440a7103 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTML.java
@@ -1,881 +1,882 @@
/*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.modules.extractor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.URIException;
import org.archive.io.ReplayCharSequence;
import org.archive.modules.CrawlMetadata;
import org.archive.modules.CrawlURI;
import org.archive.modules.net.RobotsHonoringPolicy;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import org.archive.util.ArchiveUtils;
import org.archive.util.DevUtils;
import org.archive.util.TextUtils;
import org.archive.util.UriUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Basic link-extraction, from an HTML content-body,
* using regular expressions.
*
* @author gojomo
*
*/
public class ExtractorHTML extends ContentExtractor implements InitializingBean {
private static final long serialVersionUID = 2L;
private static Logger logger =
Logger.getLogger(ExtractorHTML.class.getName());
private final static String MAX_ELEMENT_REPLACE = "MAX_ELEMENT";
private final static String MAX_ATTR_NAME_REPLACE = "MAX_ATTR_NAME";
private final static String MAX_ATTR_VAL_REPLACE = "MAX_ATTR_VAL";
public final static String A_META_ROBOTS = "meta-robots";
/**
* Compiled relevant tag extractor.
*
* <p>
* This pattern extracts either:
* <li> (1) whole <script>...</script> or
* <li> (2) <style>...</style> or
* <li> (3) <meta ...> or
* <li> (4) any other open-tag with at least one attribute
* (eg matches "<a href='boo'>" but not "</a>" or "<br>")
* <p>
* groups:
* <li> 1: SCRIPT SRC=foo>boo</SCRIPT
* <li> 2: just script open tag
* <li> 3: STYLE TYPE=moo>zoo</STYLE
* <li> 4: just style open tag
* <li> 5: entire other tag, without '<' '>'
* <li> 6: element
* <li> 7: META
* <li> 8: !-- comment --
*/
// version w/ less unnecessary backtracking
{
setMaxElementLength(64);
}
public int getMaxElementLength() {
return (Integer) kp.get("maxElementLength");
}
public void setMaxElementLength(int max) {
kp.put("maxElementLength",max);
}
static final String RELEVANT_TAG_EXTRACTOR =
"(?is)<(?:((script[^>]*+)>.*?</script)" + // 1, 2
"|((style[^>]*+)>.*?</style)" + // 3, 4
"|(((meta)|(?:\\w{1,"+MAX_ELEMENT_REPLACE+"}))\\s+[^>]*+)" + // 5, 6, 7
"|(!--.*?--))>"; // 8
// version w/ problems with unclosed script tags
// static final String RELEVANT_TAG_EXTRACTOR =
// "(?is)<(?:((script.*?)>.*?</script)|((style.*?)>.*?</style)|(((meta)|(?:\\w+))\\s+.*?)|(!--.*?--))>";
// // this pattern extracts 'href' or 'src' attributes from
// // any open-tag innards matched by the above
// static Pattern RELEVANT_ATTRIBUTE_EXTRACTOR = Pattern.compile(
// "(?is)(\\w+)(?:\\s+|(?:\\s.*?\\s))(?:(href)|(src))\\s*=(?:(?:\\s*\"(.+?)\")|(?:\\s*'(.+?)')|(\\S+))");
//
// // this pattern extracts 'robots' attributes
// static Pattern ROBOTS_ATTRIBUTE_EXTRACTOR = Pattern.compile(
// "(?is)(\\w+)\\s+.*?(?:(robots))\\s*=(?:(?:\\s*\"(.+)\")|(?:\\s*'(.+)')|(\\S+))");
{
setMaxAttributeNameLength(64); // 64 chars
}
public int getMaxAttributeNameLength() {
return (Integer) kp.get("maxAttributeNameLength");
}
public void setMaxAttributeNameLength(int max) {
kp.put("maxAttributeNameLength", max);
}
{
setMaxAttributeValLength(2048); // 2K
}
public int getMaxAttributeValLength() {
return (Integer) kp.get("maxAttributeValLength");
}
public void setMaxAttributeValLength(int max) {
kp.put("maxAttributeValLength", max);
}
// TODO: perhaps cut to near MAX_URI_LENGTH
// this pattern extracts attributes from any open-tag innards
// matched by the above. attributes known to be URIs of various
// sorts are matched specially
static final String EACH_ATTRIBUTE_EXTRACTOR =
"(?is)\\s?((href)|(action)|(on\\w*)" // 1, 2, 3, 4
+"|((?:src)|(?:lowsrc)|(?:background)|(?:cite)|(?:longdesc)" // ...
+"|(?:usemap)|(?:profile)|(?:datasrc))" // 5
+"|(codebase)|((?:classid)|(?:data))|(archive)|(code)" // 6, 7, 8, 9
+"|(value)|(style)|(method)" // 10, 11, 12
+"|([-\\w]{1,"+MAX_ATTR_NAME_REPLACE+"}))" // 13
+"\\s*=\\s*"
+"(?:(?:\"(.{0,"+MAX_ATTR_VAL_REPLACE+"}?)(?:\"|$))" // 14
+"|(?:'(.{0,"+MAX_ATTR_VAL_REPLACE+"}?)(?:'|$))" // 15
+"|(\\S{1,"+MAX_ATTR_VAL_REPLACE+"}))"; // 16
// groups:
// 1: attribute name
// 2: HREF - single URI relative to doc base, or occasionally javascript:
// 3: ACTION - single URI relative to doc base, or occasionally javascript:
// 4: ON[WHATEVER] - script handler
// 5: SRC,LOWSRC,BACKGROUND,CITE,LONGDESC,USEMAP,PROFILE, or DATASRC
// single URI relative to doc base
// 6: CODEBASE - a single URI relative to doc base, affecting other
// attributes
// 7: CLASSID, DATA - a single URI relative to CODEBASE (if supplied)
// 8: ARCHIVE - one or more space-delimited URIs relative to CODEBASE
// (if supplied)
// 9: CODE - a single URI relative to the CODEBASE (is specified).
// 10: VALUE - often includes a uri path on forms
// 11: STYLE - inline attribute style info
// 12: METHOD - form GET/POST
// 13: any other attribute
// 14: double-quote delimited attr value
// 15: single-quote delimited attr value
// 16: space-delimited attr value
static final String WHITESPACE = "\\s";
static final String CLASSEXT =".class";
static final String APPLET = "applet";
static final String BASE = "base";
static final String LINK = "link";
static final String FRAME = "frame";
static final String IFRAME = "iframe";
/**
* If true, FRAME/IFRAME SRC-links are treated as embedded resources (like
* IMG, 'E' hop-type), otherwise they are treated as navigational links.
* Default is true.
*/
{
setTreatFramesAsEmbedLinks(true);
}
public boolean getTreatFramesAsEmbedLinks() {
return (Boolean) kp.get("treatFramesAsEmbedLinks");
}
public void setTreatFramesAsEmbedLinks(boolean asEmbeds) {
kp.put("treatFramesAsEmbedLinks",asEmbeds);
}
/**
* If true, URIs appearing as the ACTION attribute in HTML FORMs are
* ignored. Default is false.
*/
{
setIgnoreFormActionUrls(false);
}
public boolean getIgnoreFormActionUrls() {
return (Boolean) kp.get("ignoreFormActionUrls");
}
public void setIgnoreFormActionUrls(boolean ignoreActions) {
kp.put("ignoreFormActionUrls",ignoreActions);
}
/**
* If true, only ACTION URIs with a METHOD of GET (explicit or implied)
* are extracted. Default is true.
*/
{
setExtractOnlyFormGets(true);
}
public boolean getExtractOnlyFormGets() {
return (Boolean) kp.get("extractOnlyFormGets");
}
public void setExtractOnlyFormGets(boolean onlyGets) {
kp.put("extractOnlyFormGets",onlyGets);
}
/**
* If true, in-page Javascript is scanned for strings that
* appear likely to be URIs. This typically finds both valid
* and invalid URIs, and attempts to fetch the invalid URIs
* sometimes generates webmaster concerns over odd crawler
* behavior. Default is true.
*/
{
setExtractJavascript(true);
}
public boolean getExtractJavascript() {
return (Boolean) kp.get("extractJavascript");
}
public void setExtractJavascript(boolean extractJavascript) {
kp.put("extractJavascript",extractJavascript);
}
/**
* If true, strings that look like URIs found in unusual places (such as
* form VALUE attributes) will be extracted. This typically finds both valid
* and invalid URIs, and attempts to fetch the invalid URIs sometimes
* generate webmaster concerns over odd crawler behavior. Default is true.
*/
{
setExtractValueAttributes(true);
}
public boolean getExtractValueAttributes() {
return (Boolean) kp.get("extractValueAttributes");
}
public void setExtractValueAttributes(boolean extractValueAttributes) {
kp.put("extractValueAttributes",extractValueAttributes);
}
/**
* If true, URIs which end in typical non-HTML extensions (such as .gif)
* will not be scanned as if it were HTML. Default is true.
*/
{
setIgnoreUnexpectedHtml(true);
}
public boolean getIgnoreUnexpectedHtml() {
return (Boolean) kp.get("ignoreUnexpectedHtml");
}
public void setIgnoreUnexpectedHtml(boolean ignoreUnexpectedHtml) {
kp.put("ignoreUnexpectedHtml",ignoreUnexpectedHtml);
}
/**
* CrawlMetadata provides the robots honoring policy to use when
* considering a robots META tag.
*/
CrawlMetadata metadata;
public CrawlMetadata getMetadata() {
return metadata;
}
@Autowired
public void setMetadata(CrawlMetadata provider) {
this.metadata = provider;
}
private Pattern relevantTagExtractor;
private Pattern eachAttributeExtractor;
public ExtractorHTML() {
}
public void afterPropertiesSet() {
String regex = RELEVANT_TAG_EXTRACTOR;
regex = regex.replace(MAX_ELEMENT_REPLACE,
Integer.toString(getMaxElementLength()));
this.relevantTagExtractor = Pattern.compile(regex);
regex = EACH_ATTRIBUTE_EXTRACTOR;
regex = regex.replace(MAX_ATTR_NAME_REPLACE,
Integer.toString(getMaxAttributeNameLength()));
regex = regex.replace(MAX_ATTR_VAL_REPLACE,
Integer.toString(getMaxAttributeValLength()));
this.eachAttributeExtractor = Pattern.compile(regex);
}
protected void processGeneralTag(CrawlURI curi, CharSequence element,
CharSequence cs) {
Matcher attr = eachAttributeExtractor.matcher(cs);
// Just in case it's an OBJECT or APPLET tag
String codebase = null;
ArrayList<String> resources = null;
// Just in case it's a FORM
CharSequence action = null;
CharSequence actionContext = null;
CharSequence method = null;
// Just in case it's a VALUE whose interpretation depends on accompanying NAME
CharSequence valueVal = null;
CharSequence valueContext = null;
CharSequence nameVal = null;
final boolean framesAsEmbeds =
getTreatFramesAsEmbedLinks();
final boolean ignoreFormActions =
getIgnoreFormActionUrls();
final boolean extractValueAttributes =
getExtractValueAttributes();
final String elementStr = element.toString();
while (attr.find()) {
int valueGroup =
(attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
int start = attr.start(valueGroup);
int end = attr.end(valueGroup);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
CharSequence value = cs.subSequence(start, end);
CharSequence attrName = cs.subSequence(attr.start(1),attr.end(1));
value = TextUtils.unescapeHtml(value);
if (attr.start(2) > -1) {
// HREF
CharSequence context = elementContext(element, attr.group(2));
if(elementStr.equalsIgnoreCase(LINK)) {
// <LINK> elements treated as embeds (css, ico, etc)
processEmbed(curi, value, context);
} else {
// other HREFs treated as links
processLink(curi, value, context);
}
if (elementStr.equalsIgnoreCase(BASE)) {
try {
UURI base = UURIFactory.getInstance(value.toString());
curi.setBaseURI(base);
} catch (URIException e) {
logUriError(e, curi.getUURI(), value);
}
}
} else if (attr.start(3) > -1) {
// ACTION
if (!ignoreFormActions) {
action = value;
actionContext = elementContext(element, attr.group(3));
// handling finished only at end (after METHOD also collected)
}
} else if (attr.start(4) > -1) {
// ON____
processScriptCode(curi, value); // TODO: context?
} else if (attr.start(5) > -1) {
// SRC etc.
CharSequence context = elementContext(element, attr.group(5));
// true, if we expect another HTML page instead of an image etc.
final Hop hop;
if(!framesAsEmbeds
&& (elementStr.equalsIgnoreCase(FRAME) || elementStr
.equalsIgnoreCase(IFRAME))) {
hop = Hop.NAVLINK;
} else {
hop = Hop.EMBED;
}
processEmbed(curi, value, context, hop);
} else if (attr.start(6) > -1) {
// CODEBASE
codebase = (value instanceof String)?
(String)value: value.toString();
CharSequence context = elementContext(element,
attr.group(6));
processEmbed(curi, codebase, context);
} else if (attr.start(7) > -1) {
// CLASSID, DATA
if (resources == null) {
resources = new ArrayList<String>();
}
resources.add(value.toString());
} else if (attr.start(8) > -1) {
// ARCHIVE
if (resources==null) {
resources = new ArrayList<String>();
}
String[] multi = TextUtils.split(WHITESPACE, value);
for(int i = 0; i < multi.length; i++ ) {
resources.add(multi[i]);
}
} else if (attr.start(9) > -1) {
// CODE
if (resources==null) {
resources = new ArrayList<String>();
}
// If element is applet and code value does not end with
// '.class' then append '.class' to the code value.
if (elementStr.equalsIgnoreCase(APPLET) &&
!value.toString().toLowerCase().endsWith(CLASSEXT)) {
resources.add(value.toString() + CLASSEXT);
} else {
resources.add(value.toString());
}
} else if (attr.start(10) > -1) {
// VALUE, with possibility of URI
// store value, context for handling at end
valueVal = value;
valueContext = elementContext(element,attr.group(10));
} else if (attr.start(11) > -1) {
// STYLE inline attribute
// then, parse for URIs
numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
this, curi, value));
} else if (attr.start(12) > -1) {
// METHOD
method = value;
// form processing finished at end (after ACTION also collected)
} else if (attr.start(13) > -1) {
if("NAME".equalsIgnoreCase(attrName.toString())) {
// remember 'name' for end-analysis
nameVal = value;
}
if("FLASHVARS".equalsIgnoreCase(attrName.toString())) {
// consider FLASHVARS attribute immediately
valueContext = elementContext(element,attr.group(13));
considerQueryStringValues(curi, value, valueContext,Hop.SPECULATIVE);
}
// any other attribute
// ignore for now
// could probe for path- or script-looking strings, but
// those should be vanishingly rare in other attributes,
// and/or symptomatic of page bugs
}
}
TextUtils.recycleMatcher(attr);
// handle codebase/resources
if (resources != null) {
Iterator<String> iter = resources.iterator();
UURI codebaseURI = null;
String res = null;
try {
if (codebase != null) {
// TODO: Pass in the charset.
codebaseURI = UURIFactory.
getInstance(curi.getUURI(), codebase);
}
while(iter.hasNext()) {
res = iter.next().toString();
res = (String) TextUtils.unescapeHtml(res);
if (codebaseURI != null) {
res = codebaseURI.resolve(res).toString();
}
processEmbed(curi, res, element); // TODO: include attribute too
}
} catch (URIException e) {
curi.getNonFatalFailures().add(e);
} catch (IllegalArgumentException e) {
DevUtils.logger.log(Level.WARNING, "processGeneralTag()\n" +
"codebase=" + codebase + " res=" + res + "\n" +
DevUtils.extraInfo(), e);
}
}
// finish handling form action, now method is available
if(action != null) {
if(method == null || "GET".equalsIgnoreCase(method.toString())
|| ! getExtractOnlyFormGets()) {
processLink(curi, action, actionContext);
}
}
// finish handling VALUE
if(valueVal != null) {
- if("PARAM".equalsIgnoreCase(elementStr) && "flashvars".equalsIgnoreCase(nameVal.toString())) {
+ if ("PARAM".equalsIgnoreCase(elementStr) && nameVal != null
+ && "flashvars".equalsIgnoreCase(nameVal.toString())) {
// special handling for <PARAM NAME='flashvars" VALUE="">
String queryStringLike = valueVal.toString();
// treat value as query-string-like "key=value[;key=value]*" pairings
considerQueryStringValues(curi, queryStringLike, valueContext,Hop.SPECULATIVE);
} else {
// regular VALUE handling
if (extractValueAttributes) {
considerIfLikelyUri(curi,valueVal,valueContext,Hop.NAVLINK);
}
}
}
}
/**
* Consider a query-string-like collections of key=value[;key=value]
* pairs for URI-like strings in the values. Where URI-like strings are
* found, add as discovered outlink.
*
* @param curi origin CrawlURI
* @param queryString query-string-like string
* @param valueContext page context where found
*/
protected void considerQueryStringValues(CrawlURI curi,
CharSequence queryString, CharSequence valueContext, Hop hop) {
for(String pairString : queryString.toString().split(";")) {
String[] keyVal = pairString.split("=");
if(keyVal.length==2) {
considerIfLikelyUri(curi,keyVal[1],valueContext, hop);
}
}
}
/**
* Consider whether a given string is URI-like. If so, add as discovered
* outlink.
*
* @param curi origin CrawlURI
* @param queryString query-string-like string
* @param valueContext page context where found
*/
protected void considerIfLikelyUri(CrawlURI curi, CharSequence candidate,
CharSequence valueContext, Hop hop) {
if(UriUtils.isLikelyUri(candidate)) {
addLinkFromString(curi,candidate,valueContext,hop);
}
}
/**
* Extract the (java)script source in the given CharSequence.
*
* @param curi source CrawlURI
* @param cs CharSequence of javascript code
*/
protected void processScriptCode(CrawlURI curi, CharSequence cs) {
if (getExtractJavascript()) {
numberOfLinksExtracted.addAndGet(
ExtractorJS.considerStrings(this, curi, cs, false));
}
}
static final String JAVASCRIPT = "(?i)^javascript:.*";
/**
* Handle generic HREF cases.
*
* @param curi
* @param value
* @param context
*/
protected void processLink(CrawlURI curi, final CharSequence value,
CharSequence context) {
if (TextUtils.matches(JAVASCRIPT, value)) {
processScriptCode(curi, value. subSequence(11, value.length()));
} else {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("link: " + value.toString() + " from " + curi);
}
addLinkFromString(curi, value, context, Hop.NAVLINK);
numberOfLinksExtracted.incrementAndGet();
}
}
protected void addLinkFromString(CrawlURI curi, CharSequence uri,
CharSequence context, Hop hop) {
try {
// We do a 'toString' on context because its a sequence from
// the underlying ReplayCharSequence and the link its about
// to become a part of is expected to outlive the current
// ReplayCharSequence.
HTMLLinkContext hc = new HTMLLinkContext(context.toString());
int max = getExtractorParameters().getMaxOutlinks();
Link.addRelativeToBase(curi, max, uri.toString(), hc, hop);
} catch (URIException e) {
logUriError(e, curi.getUURI(), uri);
}
}
protected final void processEmbed(CrawlURI curi, CharSequence value,
CharSequence context) {
processEmbed(curi, value, context, Hop.EMBED);
}
protected void processEmbed(CrawlURI curi, final CharSequence value,
CharSequence context, Hop hop) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest("embed (" + hop.getHopChar() + "): " + value.toString() +
" from " + curi);
}
addLinkFromString(curi,
(value instanceof String)?
(String)value: value.toString(),
context, hop);
numberOfLinksExtracted.incrementAndGet();
}
protected boolean shouldExtract(CrawlURI uri) {
if (getIgnoreUnexpectedHtml()) {
try {
// HTML was not expected (eg a GIF was expected) so ignore
// (as if a soft 404)
if (!isHtmlExpectedHere(uri)) {
return false;
}
} catch (URIException e) {
logger.severe("Failed expectedHTML test: " + e.getMessage());
// assume it's okay to extract
}
}
String mime = uri.getContentType().toLowerCase();
return mime.startsWith("text/html")
|| mime.startsWith("application/xhtml")
|| mime.startsWith("text/vnd.wap.wml")
|| mime.startsWith("application/vnd.wap.wml")
|| mime.startsWith("application/vnd.wap.xhtml");
}
public boolean innerExtract(CrawlURI curi) {
ReplayCharSequence cs = null;
try {
cs = curi.getRecorder().getReplayCharSequence();
// Extract all links from the charsequence
extract(curi, cs);
if(cs.getDecodeExceptionCount()>0) {
curi.getNonFatalFailures().add(cs.getCodingException());
}
// Set flag to indicate that link extraction is completed.
return true;
} catch (IOException e) {
curi.getNonFatalFailures().add(e);
logger.log(Level.SEVERE,"Failed get of replay char sequence in " +
Thread.currentThread().getName(), e);
} finally {
ArchiveUtils.closeQuietly(cs);
}
return false;
}
/**
* Run extractor.
* This method is package visible to ease testing.
* @param curi CrawlURI we're processing.
* @param cs Sequence from underlying ReplayCharSequence. This
* is TRANSIENT data. Make a copy if you want the data to live outside
* of this extractors' lifetime.
*/
void extract(CrawlURI curi, CharSequence cs) {
Matcher tags = relevantTagExtractor.matcher(cs);
while(tags.find()) {
if(Thread.interrupted()){
break;
}
if (tags.start(8) > 0) {
// comment match
// for now do nothing
} else if (tags.start(7) > 0) {
// <meta> match
int start = tags.start(5);
int end = tags.end(5);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
if (processMeta(curi,
cs.subSequence(start, end))) {
// meta tag included NOFOLLOW; abort processing
break;
}
} else if (tags.start(5) > 0) {
// generic <whatever> match
int start5 = tags.start(5);
int end5 = tags.end(5);
assert start5 >= 0: "Start is: " + start5 + ", " + curi;
assert end5 >= 0: "End is :" + end5 + ", " + curi;
int start6 = tags.start(6);
int end6 = tags.end(6);
assert start6 >= 0: "Start is: " + start6 + ", " + curi;
assert end6 >= 0: "End is :" + end6 + ", " + curi;
processGeneralTag(curi,
cs.subSequence(start6, end6),
cs.subSequence(start5, end5));
} else if (tags.start(1) > 0) {
// <script> match
int start = tags.start(1);
int end = tags.end(1);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
assert tags.end(2) >= 0: "Tags.end(2) illegal " + tags.end(2) +
", " + curi;
processScript(curi, cs.subSequence(start, end),
tags.end(2) - start);
} else if (tags.start(3) > 0){
// <style... match
int start = tags.start(3);
int end = tags.end(3);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
assert tags.end(4) >= 0: "Tags.end(4) illegal " + tags.end(4) +
", " + curi;
processStyle(curi, cs.subSequence(start, end),
tags.end(4) - start);
}
}
TextUtils.recycleMatcher(tags);
}
static final String NON_HTML_PATH_EXTENSION =
"(?i)(gif)|(jp(e)?g)|(png)|(tif(f)?)|(bmp)|(avi)|(mov)|(mp(e)?g)"+
"|(mp3)|(mp4)|(swf)|(wav)|(au)|(aiff)|(mid)";
/**
* Test whether this HTML is so unexpected (eg in place of a GIF URI)
* that it shouldn't be scanned for links.
*
* @param curi CrawlURI to examine.
* @return True if HTML is acceptable/expected here
* @throws URIException
*/
protected boolean isHtmlExpectedHere(CrawlURI curi) throws URIException {
String path = curi.getUURI().getPath();
if(path==null) {
// no path extension, HTML is fine
return true;
}
int dot = path.lastIndexOf('.');
if (dot < 0) {
// no path extension, HTML is fine
return true;
}
if(dot<(path.length()-5)) {
// extension too long to recognize, HTML is fine
return true;
}
String ext = path.substring(dot+1);
return ! TextUtils.matches(NON_HTML_PATH_EXTENSION, ext);
}
protected void processScript(CrawlURI curi, CharSequence sequence,
int endOfOpenTag) {
// first, get attributes of script-open tag
// as per any other tag
processGeneralTag(curi,sequence.subSequence(0,6),
sequence.subSequence(0,endOfOpenTag));
// then, apply best-effort string-analysis heuristics
// against any code present (false positives are OK)
processScriptCode(
curi, sequence.subSequence(endOfOpenTag, sequence.length()));
}
/**
* Process metadata tags.
* @param curi CrawlURI we're processing.
* @param cs Sequence from underlying ReplayCharSequence. This
* is TRANSIENT data. Make a copy if you want the data to live outside
* of this extractors' lifetime.
* @return True robots exclusion metatag.
*/
protected boolean processMeta(CrawlURI curi, CharSequence cs) {
Matcher attr = eachAttributeExtractor.matcher(cs);
String name = null;
String httpEquiv = null;
String content = null;
while (attr.find()) {
int valueGroup =
(attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
CharSequence value =
cs.subSequence(attr.start(valueGroup), attr.end(valueGroup));
value = TextUtils.unescapeHtml(value);
if (attr.group(1).equalsIgnoreCase("name")) {
name = value.toString();
} else if (attr.group(1).equalsIgnoreCase("http-equiv")) {
httpEquiv = value.toString();
} else if (attr.group(1).equalsIgnoreCase("content")) {
content = value.toString();
}
// TODO: handle other stuff
}
TextUtils.recycleMatcher(attr);
// Look for the 'robots' meta-tag
if("robots".equalsIgnoreCase(name) && content != null ) {
curi.getData().put(A_META_ROBOTS, content);
RobotsHonoringPolicy policy = metadata.getRobotsHonoringPolicy();
String contentLower = content.toLowerCase();
if ((policy == null
|| (!policy.isType(RobotsHonoringPolicy.Type.IGNORE)
&& !policy.isType(RobotsHonoringPolicy.Type.CUSTOM)))
&& (contentLower.indexOf("nofollow") >= 0
|| contentLower.indexOf("none") >= 0)) {
// if 'nofollow' or 'none' is specified and the
// honoring policy is not IGNORE or CUSTOM, end html extraction
logger.fine("HTML extraction skipped due to robots meta-tag for: "
+ curi.toString());
return true;
}
} else if ("refresh".equalsIgnoreCase(httpEquiv) && content != null) {
int urlIndex = content.indexOf("=") + 1;
if(urlIndex>0) {
String refreshUri = content.substring(urlIndex);
try {
int max = getExtractorParameters().getMaxOutlinks();
Link.addRelativeToBase(curi, max, refreshUri,
HTMLLinkContext.META, Hop.REFER);
} catch (URIException e) {
logUriError(e, curi.getUURI(), refreshUri);
}
}
}
return false;
}
/**
* Process style text.
* @param curi CrawlURI we're processing.
* @param sequence Sequence from underlying ReplayCharSequence. This
* is TRANSIENT data. Make a copy if you want the data to live outside
* of this extractors' lifetime.
* @param endOfOpenTag
*/
protected void processStyle(CrawlURI curi, CharSequence sequence,
int endOfOpenTag) {
// First, get attributes of script-open tag as per any other tag.
processGeneralTag(curi, sequence.subSequence(0,6),
sequence.subSequence(0,endOfOpenTag));
// then, parse for URIs
numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
this,
curi,
sequence.subSequence(endOfOpenTag,sequence.length())));
}
/**
* Create a suitable XPath-like context from an element name and optional
* attribute name.
*
* @param element
* @param attribute
* @return CharSequence context
*/
public static CharSequence elementContext(CharSequence element, CharSequence attribute) {
return attribute == null? "": element + "/@" + attribute;
}
}
| true | true | protected void processGeneralTag(CrawlURI curi, CharSequence element,
CharSequence cs) {
Matcher attr = eachAttributeExtractor.matcher(cs);
// Just in case it's an OBJECT or APPLET tag
String codebase = null;
ArrayList<String> resources = null;
// Just in case it's a FORM
CharSequence action = null;
CharSequence actionContext = null;
CharSequence method = null;
// Just in case it's a VALUE whose interpretation depends on accompanying NAME
CharSequence valueVal = null;
CharSequence valueContext = null;
CharSequence nameVal = null;
final boolean framesAsEmbeds =
getTreatFramesAsEmbedLinks();
final boolean ignoreFormActions =
getIgnoreFormActionUrls();
final boolean extractValueAttributes =
getExtractValueAttributes();
final String elementStr = element.toString();
while (attr.find()) {
int valueGroup =
(attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
int start = attr.start(valueGroup);
int end = attr.end(valueGroup);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
CharSequence value = cs.subSequence(start, end);
CharSequence attrName = cs.subSequence(attr.start(1),attr.end(1));
value = TextUtils.unescapeHtml(value);
if (attr.start(2) > -1) {
// HREF
CharSequence context = elementContext(element, attr.group(2));
if(elementStr.equalsIgnoreCase(LINK)) {
// <LINK> elements treated as embeds (css, ico, etc)
processEmbed(curi, value, context);
} else {
// other HREFs treated as links
processLink(curi, value, context);
}
if (elementStr.equalsIgnoreCase(BASE)) {
try {
UURI base = UURIFactory.getInstance(value.toString());
curi.setBaseURI(base);
} catch (URIException e) {
logUriError(e, curi.getUURI(), value);
}
}
} else if (attr.start(3) > -1) {
// ACTION
if (!ignoreFormActions) {
action = value;
actionContext = elementContext(element, attr.group(3));
// handling finished only at end (after METHOD also collected)
}
} else if (attr.start(4) > -1) {
// ON____
processScriptCode(curi, value); // TODO: context?
} else if (attr.start(5) > -1) {
// SRC etc.
CharSequence context = elementContext(element, attr.group(5));
// true, if we expect another HTML page instead of an image etc.
final Hop hop;
if(!framesAsEmbeds
&& (elementStr.equalsIgnoreCase(FRAME) || elementStr
.equalsIgnoreCase(IFRAME))) {
hop = Hop.NAVLINK;
} else {
hop = Hop.EMBED;
}
processEmbed(curi, value, context, hop);
} else if (attr.start(6) > -1) {
// CODEBASE
codebase = (value instanceof String)?
(String)value: value.toString();
CharSequence context = elementContext(element,
attr.group(6));
processEmbed(curi, codebase, context);
} else if (attr.start(7) > -1) {
// CLASSID, DATA
if (resources == null) {
resources = new ArrayList<String>();
}
resources.add(value.toString());
} else if (attr.start(8) > -1) {
// ARCHIVE
if (resources==null) {
resources = new ArrayList<String>();
}
String[] multi = TextUtils.split(WHITESPACE, value);
for(int i = 0; i < multi.length; i++ ) {
resources.add(multi[i]);
}
} else if (attr.start(9) > -1) {
// CODE
if (resources==null) {
resources = new ArrayList<String>();
}
// If element is applet and code value does not end with
// '.class' then append '.class' to the code value.
if (elementStr.equalsIgnoreCase(APPLET) &&
!value.toString().toLowerCase().endsWith(CLASSEXT)) {
resources.add(value.toString() + CLASSEXT);
} else {
resources.add(value.toString());
}
} else if (attr.start(10) > -1) {
// VALUE, with possibility of URI
// store value, context for handling at end
valueVal = value;
valueContext = elementContext(element,attr.group(10));
} else if (attr.start(11) > -1) {
// STYLE inline attribute
// then, parse for URIs
numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
this, curi, value));
} else if (attr.start(12) > -1) {
// METHOD
method = value;
// form processing finished at end (after ACTION also collected)
} else if (attr.start(13) > -1) {
if("NAME".equalsIgnoreCase(attrName.toString())) {
// remember 'name' for end-analysis
nameVal = value;
}
if("FLASHVARS".equalsIgnoreCase(attrName.toString())) {
// consider FLASHVARS attribute immediately
valueContext = elementContext(element,attr.group(13));
considerQueryStringValues(curi, value, valueContext,Hop.SPECULATIVE);
}
// any other attribute
// ignore for now
// could probe for path- or script-looking strings, but
// those should be vanishingly rare in other attributes,
// and/or symptomatic of page bugs
}
}
TextUtils.recycleMatcher(attr);
// handle codebase/resources
if (resources != null) {
Iterator<String> iter = resources.iterator();
UURI codebaseURI = null;
String res = null;
try {
if (codebase != null) {
// TODO: Pass in the charset.
codebaseURI = UURIFactory.
getInstance(curi.getUURI(), codebase);
}
while(iter.hasNext()) {
res = iter.next().toString();
res = (String) TextUtils.unescapeHtml(res);
if (codebaseURI != null) {
res = codebaseURI.resolve(res).toString();
}
processEmbed(curi, res, element); // TODO: include attribute too
}
} catch (URIException e) {
curi.getNonFatalFailures().add(e);
} catch (IllegalArgumentException e) {
DevUtils.logger.log(Level.WARNING, "processGeneralTag()\n" +
"codebase=" + codebase + " res=" + res + "\n" +
DevUtils.extraInfo(), e);
}
}
// finish handling form action, now method is available
if(action != null) {
if(method == null || "GET".equalsIgnoreCase(method.toString())
|| ! getExtractOnlyFormGets()) {
processLink(curi, action, actionContext);
}
}
// finish handling VALUE
if(valueVal != null) {
if("PARAM".equalsIgnoreCase(elementStr) && "flashvars".equalsIgnoreCase(nameVal.toString())) {
// special handling for <PARAM NAME='flashvars" VALUE="">
String queryStringLike = valueVal.toString();
// treat value as query-string-like "key=value[;key=value]*" pairings
considerQueryStringValues(curi, queryStringLike, valueContext,Hop.SPECULATIVE);
} else {
// regular VALUE handling
if (extractValueAttributes) {
considerIfLikelyUri(curi,valueVal,valueContext,Hop.NAVLINK);
}
}
}
}
| protected void processGeneralTag(CrawlURI curi, CharSequence element,
CharSequence cs) {
Matcher attr = eachAttributeExtractor.matcher(cs);
// Just in case it's an OBJECT or APPLET tag
String codebase = null;
ArrayList<String> resources = null;
// Just in case it's a FORM
CharSequence action = null;
CharSequence actionContext = null;
CharSequence method = null;
// Just in case it's a VALUE whose interpretation depends on accompanying NAME
CharSequence valueVal = null;
CharSequence valueContext = null;
CharSequence nameVal = null;
final boolean framesAsEmbeds =
getTreatFramesAsEmbedLinks();
final boolean ignoreFormActions =
getIgnoreFormActionUrls();
final boolean extractValueAttributes =
getExtractValueAttributes();
final String elementStr = element.toString();
while (attr.find()) {
int valueGroup =
(attr.start(14) > -1) ? 14 : (attr.start(15) > -1) ? 15 : 16;
int start = attr.start(valueGroup);
int end = attr.end(valueGroup);
assert start >= 0: "Start is: " + start + ", " + curi;
assert end >= 0: "End is :" + end + ", " + curi;
CharSequence value = cs.subSequence(start, end);
CharSequence attrName = cs.subSequence(attr.start(1),attr.end(1));
value = TextUtils.unescapeHtml(value);
if (attr.start(2) > -1) {
// HREF
CharSequence context = elementContext(element, attr.group(2));
if(elementStr.equalsIgnoreCase(LINK)) {
// <LINK> elements treated as embeds (css, ico, etc)
processEmbed(curi, value, context);
} else {
// other HREFs treated as links
processLink(curi, value, context);
}
if (elementStr.equalsIgnoreCase(BASE)) {
try {
UURI base = UURIFactory.getInstance(value.toString());
curi.setBaseURI(base);
} catch (URIException e) {
logUriError(e, curi.getUURI(), value);
}
}
} else if (attr.start(3) > -1) {
// ACTION
if (!ignoreFormActions) {
action = value;
actionContext = elementContext(element, attr.group(3));
// handling finished only at end (after METHOD also collected)
}
} else if (attr.start(4) > -1) {
// ON____
processScriptCode(curi, value); // TODO: context?
} else if (attr.start(5) > -1) {
// SRC etc.
CharSequence context = elementContext(element, attr.group(5));
// true, if we expect another HTML page instead of an image etc.
final Hop hop;
if(!framesAsEmbeds
&& (elementStr.equalsIgnoreCase(FRAME) || elementStr
.equalsIgnoreCase(IFRAME))) {
hop = Hop.NAVLINK;
} else {
hop = Hop.EMBED;
}
processEmbed(curi, value, context, hop);
} else if (attr.start(6) > -1) {
// CODEBASE
codebase = (value instanceof String)?
(String)value: value.toString();
CharSequence context = elementContext(element,
attr.group(6));
processEmbed(curi, codebase, context);
} else if (attr.start(7) > -1) {
// CLASSID, DATA
if (resources == null) {
resources = new ArrayList<String>();
}
resources.add(value.toString());
} else if (attr.start(8) > -1) {
// ARCHIVE
if (resources==null) {
resources = new ArrayList<String>();
}
String[] multi = TextUtils.split(WHITESPACE, value);
for(int i = 0; i < multi.length; i++ ) {
resources.add(multi[i]);
}
} else if (attr.start(9) > -1) {
// CODE
if (resources==null) {
resources = new ArrayList<String>();
}
// If element is applet and code value does not end with
// '.class' then append '.class' to the code value.
if (elementStr.equalsIgnoreCase(APPLET) &&
!value.toString().toLowerCase().endsWith(CLASSEXT)) {
resources.add(value.toString() + CLASSEXT);
} else {
resources.add(value.toString());
}
} else if (attr.start(10) > -1) {
// VALUE, with possibility of URI
// store value, context for handling at end
valueVal = value;
valueContext = elementContext(element,attr.group(10));
} else if (attr.start(11) > -1) {
// STYLE inline attribute
// then, parse for URIs
numberOfLinksExtracted.addAndGet(ExtractorCSS.processStyleCode(
this, curi, value));
} else if (attr.start(12) > -1) {
// METHOD
method = value;
// form processing finished at end (after ACTION also collected)
} else if (attr.start(13) > -1) {
if("NAME".equalsIgnoreCase(attrName.toString())) {
// remember 'name' for end-analysis
nameVal = value;
}
if("FLASHVARS".equalsIgnoreCase(attrName.toString())) {
// consider FLASHVARS attribute immediately
valueContext = elementContext(element,attr.group(13));
considerQueryStringValues(curi, value, valueContext,Hop.SPECULATIVE);
}
// any other attribute
// ignore for now
// could probe for path- or script-looking strings, but
// those should be vanishingly rare in other attributes,
// and/or symptomatic of page bugs
}
}
TextUtils.recycleMatcher(attr);
// handle codebase/resources
if (resources != null) {
Iterator<String> iter = resources.iterator();
UURI codebaseURI = null;
String res = null;
try {
if (codebase != null) {
// TODO: Pass in the charset.
codebaseURI = UURIFactory.
getInstance(curi.getUURI(), codebase);
}
while(iter.hasNext()) {
res = iter.next().toString();
res = (String) TextUtils.unescapeHtml(res);
if (codebaseURI != null) {
res = codebaseURI.resolve(res).toString();
}
processEmbed(curi, res, element); // TODO: include attribute too
}
} catch (URIException e) {
curi.getNonFatalFailures().add(e);
} catch (IllegalArgumentException e) {
DevUtils.logger.log(Level.WARNING, "processGeneralTag()\n" +
"codebase=" + codebase + " res=" + res + "\n" +
DevUtils.extraInfo(), e);
}
}
// finish handling form action, now method is available
if(action != null) {
if(method == null || "GET".equalsIgnoreCase(method.toString())
|| ! getExtractOnlyFormGets()) {
processLink(curi, action, actionContext);
}
}
// finish handling VALUE
if(valueVal != null) {
if ("PARAM".equalsIgnoreCase(elementStr) && nameVal != null
&& "flashvars".equalsIgnoreCase(nameVal.toString())) {
// special handling for <PARAM NAME='flashvars" VALUE="">
String queryStringLike = valueVal.toString();
// treat value as query-string-like "key=value[;key=value]*" pairings
considerQueryStringValues(curi, queryStringLike, valueContext,Hop.SPECULATIVE);
} else {
// regular VALUE handling
if (extractValueAttributes) {
considerIfLikelyUri(curi,valueVal,valueContext,Hop.NAVLINK);
}
}
}
}
|
diff --git a/src/main/org/jboss/messaging/core/remoting/impl/netty/MessagingFrameDecoder.java b/src/main/org/jboss/messaging/core/remoting/impl/netty/MessagingFrameDecoder.java
index 4aa6e2c03..77d63b900 100644
--- a/src/main/org/jboss/messaging/core/remoting/impl/netty/MessagingFrameDecoder.java
+++ b/src/main/org/jboss/messaging/core/remoting/impl/netty/MessagingFrameDecoder.java
@@ -1,74 +1,74 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.messaging.core.remoting.impl.netty;
import static org.jboss.messaging.util.DataConstants.*;
import org.jboss.messaging.core.remoting.RemotingHandler;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
/**
* A Netty FrameDecoder used to decode messages.
*
* @author <a href="mailto:[email protected]">Tim Fox</a>
* @author <a href="[email protected]">Andy Taylor</a>
* @author <a href="[email protected]">Trustin Lee</a>
*
* @version $Revision$, $Date$
*/
public class MessagingFrameDecoder extends FrameDecoder
{
private final RemotingHandler handler;
public MessagingFrameDecoder(final RemotingHandler handler)
{
this.handler = handler;
}
// FrameDecoder overrides
// -------------------------------------------------------------------------------------
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer in) throws Exception
{
//TODO - we can avoid this entirely if we maintain fragmented packets in the handler
int start = in.readerIndex();
int length = handler.isReadyToHandle(new ChannelBufferWrapper(in));
if (length == -1)
{
in.readerIndex(start);
- return false;
+ return null;
}
in.readerIndex(start + SIZE_INT);
return in.readBytes(length);
}
}
| true | true | protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer in) throws Exception
{
//TODO - we can avoid this entirely if we maintain fragmented packets in the handler
int start = in.readerIndex();
int length = handler.isReadyToHandle(new ChannelBufferWrapper(in));
if (length == -1)
{
in.readerIndex(start);
return false;
}
in.readerIndex(start + SIZE_INT);
return in.readBytes(length);
}
| protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer in) throws Exception
{
//TODO - we can avoid this entirely if we maintain fragmented packets in the handler
int start = in.readerIndex();
int length = handler.isReadyToHandle(new ChannelBufferWrapper(in));
if (length == -1)
{
in.readerIndex(start);
return null;
}
in.readerIndex(start + SIZE_INT);
return in.readBytes(length);
}
|
diff --git a/org.amanzi.neo.loader/src/org/amanzi/neo/wizards/ETSIImportWizardPage.java b/org.amanzi.neo.loader/src/org/amanzi/neo/wizards/ETSIImportWizardPage.java
index 2e6f0668e..4dc0f94b0 100644
--- a/org.amanzi.neo.loader/src/org/amanzi/neo/wizards/ETSIImportWizardPage.java
+++ b/org.amanzi.neo.loader/src/org/amanzi/neo/wizards/ETSIImportWizardPage.java
@@ -1,181 +1,181 @@
/* AWE - Amanzi Wireless Explorer
* http://awe.amanzi.org
* (C) 2008-2009, AmanziTel AB
*
* This library is provided under the terms of the Eclipse Public License
* as described at http://www.eclipse.org/legal/epl-v10.html. Any use,
* reproduction or distribution of the library constitutes recipient's
* acceptance of this agreement.
*
* This library is distributed WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.amanzi.neo.wizards;
import java.util.ArrayList;
import org.amanzi.neo.core.INeoConstants;
import org.amanzi.neo.core.NeoCorePlugin;
import org.amanzi.neo.core.service.NeoServiceProvider;
import org.amanzi.neo.core.utils.NeoUtils;
import org.amanzi.neo.loader.dialogs.DriveDialog;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Transaction;
import org.neo4j.api.core.Traverser;
/**
* <p>
* Main page if ETSIImportWizard
* </p>
*
* @author Lagutko_n
* @since 1.0.0
*/
public class ETSIImportWizardPage extends WizardPage {
private class DirectoryEditor extends DirectoryFieldEditor {
/**
* Creates a directory field editor.
*
* @param name the name of the preference this field editor works on
* @param labelText the label text of the field editor
* @param parent the parent of the field editor's control
*/
public DirectoryEditor(String name, String labelText, Composite parent) {
super(name, labelText, parent);
}
/* (non-Javadoc)
* Method declared on StringButtonFieldEditor.
* Opens the directory chooser dialog and returns the selected directory.
*/
protected String changePressed() {
getTextControl().setText(DriveDialog.getDefaultDirectory());
return super.changePressed();
}
}
private String fileName;
private Composite main;
private Combo dataset;
private DirectoryFieldEditor editor;
private ArrayList<String> members;
private String datasetName;
/**
* Constructor
*
* @param pageName page name
* @param description page description
*/
public ETSIImportWizardPage(String pageName, String description) {
super(pageName);
setTitle(pageName);
setDescription(description);
setPageComplete(isValidPage());
}
/**
*check page
*
* @return true if page valid
*/
protected boolean isValidPage() {
return fileName != null;
}
@Override
public void createControl(Composite parent) {
main = new Group(parent, SWT.NULL);
main.setLayout(new GridLayout(3, false));
Label label = new Label(main, SWT.LEFT);
label.setText("Dataset:");
label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
- dataset = new Combo(main, SWT.DROP_DOWN | SWT.READ_ONLY);
+ dataset = new Combo(main, SWT.DROP_DOWN);
dataset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
dataset.setItems(getAllDatasets());
dataset.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
datasetName = dataset.getSelectionIndex() < 0 ? null : members.get(dataset.getSelectionIndex());
setPageComplete(isValidPage());
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
editor = new DirectoryEditor("fileSelectESTI", "Directory: ", main); // NON-NLS-1
editor.getTextControl(main).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setFileName(editor.getStringValue());
}
});
setControl(main);
}
/**
* Sets file name
*
* @param fileName file name
*/
protected void setFileName(String fileName) {
this.fileName = fileName;
setPageComplete(isValidPage());
DriveDialog.setDefaultDirectory(fileName);
}
/**
* Forms list of Datasets
*
* @return array of Datasets nodes
*/
private String[] getAllDatasets() {
Transaction tx = NeoUtils.beginTransaction();
try {
members = new ArrayList<String>();
Traverser allDatasetTraverser = NeoCorePlugin.getDefault().getProjectService().getAllDatasetTraverser(
NeoServiceProvider.getProvider().getService().getReferenceNode());
for (Node node : allDatasetTraverser) {
members.add((String)node.getProperty(INeoConstants.PROPERTY_NAME_NAME));
}
return members.toArray(new String[] {});
} finally {
tx.finish();
}
}
/**
* @return Returns the fileName.
*/
public String getFileName() {
return fileName;
}
/**
* @return Returns the selected Dataset name.
*/
public String getDatasetName() {
return datasetName;
}
}
| true | true | public void createControl(Composite parent) {
main = new Group(parent, SWT.NULL);
main.setLayout(new GridLayout(3, false));
Label label = new Label(main, SWT.LEFT);
label.setText("Dataset:");
label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
dataset = new Combo(main, SWT.DROP_DOWN | SWT.READ_ONLY);
dataset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
dataset.setItems(getAllDatasets());
dataset.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
datasetName = dataset.getSelectionIndex() < 0 ? null : members.get(dataset.getSelectionIndex());
setPageComplete(isValidPage());
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
editor = new DirectoryEditor("fileSelectESTI", "Directory: ", main); // NON-NLS-1
editor.getTextControl(main).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setFileName(editor.getStringValue());
}
});
setControl(main);
}
| public void createControl(Composite parent) {
main = new Group(parent, SWT.NULL);
main.setLayout(new GridLayout(3, false));
Label label = new Label(main, SWT.LEFT);
label.setText("Dataset:");
label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
dataset = new Combo(main, SWT.DROP_DOWN);
dataset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
dataset.setItems(getAllDatasets());
dataset.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
datasetName = dataset.getSelectionIndex() < 0 ? null : members.get(dataset.getSelectionIndex());
setPageComplete(isValidPage());
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
editor = new DirectoryEditor("fileSelectESTI", "Directory: ", main); // NON-NLS-1
editor.getTextControl(main).addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
setFileName(editor.getStringValue());
}
});
setControl(main);
}
|
diff --git a/server/src/JournalServer.java b/server/src/JournalServer.java
index 6dd4fc0..579bc7e 100644
--- a/server/src/JournalServer.java
+++ b/server/src/JournalServer.java
@@ -1,250 +1,247 @@
/*
* Documentation for Jessy:
* http://docs.oracle.com/javase/1.4.2/docs/api/javax/net/ssl/package-summary.html
*/
import java.security.*;
import javax.security.cert.X509Certificate;
import javax.net.*;
import javax.net.ssl.*;
import java.io.*;
import java.util.logging.*;
public class JournalServer {
private static final int LENGTH_LENGTH = 4; // length of the length field, bytes
private KeyStore keyStore;
private Logger log;
public static final int USER_PATIENT = 0;
public static final int USER_NURSE = 1;
public static final int USER_DOCTOR = 2;
public static final int USER_AGENCY = 3;
public static void main(String args[]) {
new JournalServer().start(8080);
}
public JournalServer() {
try {
keyStore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
trace("could not open keystore. exiting (" + e + ")");
}
FileHandler fileHandler = null;
try {
fileHandler = new FileHandler("logs/audit.log", 10*1024*1024, 100, true);
} catch (IOException ioe) {
trace("Could not open log file.");
}
fileHandler.setFormatter(new SimpleFormatter());
log = Logger.getLogger("auditLog");
log.addHandler(fileHandler);
}
private void trace(String msg) {
System.out.println("SERVER:\t" + msg);
}
private void log(String logmsg) {
log.info(logmsg);
}
public void start(int port) {
SSLServerSocketFactory ssf = null;
SSLServerSocket ss;
- // char[] keyStorePasswd = "password1".toCharArray();
- // char[] keyPasswd = "password2".toCharArray();
- // char[] trustPasswd = "password3".toCharArray();
String passwds[];
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks, ts;
TrustManagerFactory tmf;
- char[] keyStorePasswd = "password1".toCharArray();
- char[] keyPasswd = "password2".toCharArray();
- char[] trustPasswd = "password3".toCharArray();
+ String keyStorePasswd = null;
+ String keyPasswd = null;
+ String trustPasswd = null;
try {
passwds = this.readPassword();
- keyStorePasswd = passwds[0].toCharArray();
- keyPasswd = passwds[1].toCharArray();
- trustPasswd = passwds[2].toCharArray();
+ keyStorePasswd = passwds[0];
+ keyPasswd = passwds[1];
+ trustPasswd = passwds[2];
} catch (java.io.IOException e) {
this.trace("could not read passwords (" + e + ")");
System.exit(1);
}
try {
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
- ks.load(new FileInputStream("./keystore"), keyStorePasswd);
- kmf.init(ks, keyPasswd);
+ ks.load(new FileInputStream("./keystore"), keyStorePasswd.toCharArray());
+ kmf.init(ks, keyPasswd.toCharArray());
tmf = TrustManagerFactory.getInstance("SunX509");
ts = KeyStore.getInstance("JKS");
- ts.load(new FileInputStream("./truststore"), trustPasswd);
+ ts.load(new FileInputStream("./truststore"), trustPasswd.toCharArray());
tmf.init(ts);
ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
ssf = ctx.getServerSocketFactory();
} catch (Exception e) {
trace("shit went south, bailing. (" + e + ")");
System.exit(1);
}
try {
ss = (SSLServerSocket) ssf.createServerSocket(port);
} catch (Exception e) {
trace("could not bind to port. " + e);
return;
}
ss.setNeedClientAuth(true);
// accept clients, maybe sould be multithreaded later
while (true) {
trace("waiting for incomming connection");
SSLSocket sock;
try {
sock = (SSLSocket) ss.accept();
} catch (java.io.IOException e) {
trace("failed to accept connection");
continue;
}
trace("accepted incomming connection");
// String[] suites = {"TLS_DHE_DSS_WITH_AES_256_CBC_SHA"};
// sock.setEnabledCipherSuites(suites);
SSLSession sess = sock.getSession();
X509Certificate cert;
try {
cert = (X509Certificate)sess.getPeerCertificateChain()[0];
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
trace("client not verified");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
String subj = cert.getSubjectDN().getName();
trace("client DN: " + subj);
InputStream in;
try {
in = sock.getInputStream();
} catch (java.io.IOException e) {
trace("failed to get inputstream");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
boolean terminated = false;
while (!terminated) {
int readBytes = 0;
int tmp, tmp_shift;
int length = 0;
while (readBytes < LENGTH_LENGTH) {
try {
tmp = in.read();
} catch (java.io.IOException e) {
continue;
}
++readBytes;
tmp_shift = tmp << (LENGTH_LENGTH - readBytes);
length |= tmp_shift;
System.out.printf("raw:%s shifted:%d addedToLength:%d\n", Integer.toHexString(tmp), tmp_shift, length);
}
if (length < 0) {
trace("the client is fucking w/ us. Alternativly the connection died");
terminated = true;
continue;
} else if (readBytes == LENGTH_LENGTH) {
trace("the msg is " + length + " bytes long");
} else {
trace("failed to read length field");
continue;
}
// got length, do work.
InputStreamReader reader = new InputStreamReader(in);
char[] message = new char[length];
int ret;
int offset = 0;
while (offset < length) {
try {
ret = reader.read(message, offset, (length - offset));
} catch(Exception e) {
trace("got exception while reading message: " + e.toString());
break;
}
if (ret == -1) {
trace("fuck. something went south. breaking the parsing of message.");
break;
}
offset += ret;
}
if (offset < length) {
trace("could not read complete message");
terminated = true;
break;
}
Command command;
try {
// TODO get Journal.USER_XXX from db.getuserType(subj) or something
//command = CommandFactory.makeCommand(message, userType)
command = CommandFactory.makeCommand(message, JournalServer.USER_PATIENT);
} catch (UnknownCommandException uce) {
trace("Got unparsable command.");
terminated = true;
break;
}
}
if (terminated)
trace("terminated");
}
}
private void parseCmd(char[] cmd) {
System.out.println("---- cmd ----");
for (int i = 0; i < cmd.length; i++)
System.out.print(cmd[i]);
System.out.print('\n');
}
private String[] readPassword() throws IOException {
// while (keystorePassword == null || keystorePassword.length() == 0) {
// System.out.print("Server keystore password:");
// keystorePassword = new String(System.console().readPassword());
// }
// while (keyPassword == null || keyPassword.length() == 0) {
// System.out.print("Server keystore password:");
// keystorePassword = new String(System.console().readPassword());
// }
// while (truststorePassword == null || truststorePassword.length() == 0) {
// System.out.print("Server truststore password:");
// truststorePassword = new String(System.console().readPassword());
// }
String pws[] = new String[3];
pws[0] = "password1";
pws[1] = "password2";
pws[2] = "password3";
return pws;
}
}
| false | true | public void start(int port) {
SSLServerSocketFactory ssf = null;
SSLServerSocket ss;
// char[] keyStorePasswd = "password1".toCharArray();
// char[] keyPasswd = "password2".toCharArray();
// char[] trustPasswd = "password3".toCharArray();
String passwds[];
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks, ts;
TrustManagerFactory tmf;
char[] keyStorePasswd = "password1".toCharArray();
char[] keyPasswd = "password2".toCharArray();
char[] trustPasswd = "password3".toCharArray();
try {
passwds = this.readPassword();
keyStorePasswd = passwds[0].toCharArray();
keyPasswd = passwds[1].toCharArray();
trustPasswd = passwds[2].toCharArray();
} catch (java.io.IOException e) {
this.trace("could not read passwords (" + e + ")");
System.exit(1);
}
try {
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("./keystore"), keyStorePasswd);
kmf.init(ks, keyPasswd);
tmf = TrustManagerFactory.getInstance("SunX509");
ts = KeyStore.getInstance("JKS");
ts.load(new FileInputStream("./truststore"), trustPasswd);
tmf.init(ts);
ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
ssf = ctx.getServerSocketFactory();
} catch (Exception e) {
trace("shit went south, bailing. (" + e + ")");
System.exit(1);
}
try {
ss = (SSLServerSocket) ssf.createServerSocket(port);
} catch (Exception e) {
trace("could not bind to port. " + e);
return;
}
ss.setNeedClientAuth(true);
// accept clients, maybe sould be multithreaded later
while (true) {
trace("waiting for incomming connection");
SSLSocket sock;
try {
sock = (SSLSocket) ss.accept();
} catch (java.io.IOException e) {
trace("failed to accept connection");
continue;
}
trace("accepted incomming connection");
// String[] suites = {"TLS_DHE_DSS_WITH_AES_256_CBC_SHA"};
// sock.setEnabledCipherSuites(suites);
SSLSession sess = sock.getSession();
X509Certificate cert;
try {
cert = (X509Certificate)sess.getPeerCertificateChain()[0];
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
trace("client not verified");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
String subj = cert.getSubjectDN().getName();
trace("client DN: " + subj);
InputStream in;
try {
in = sock.getInputStream();
} catch (java.io.IOException e) {
trace("failed to get inputstream");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
boolean terminated = false;
while (!terminated) {
int readBytes = 0;
int tmp, tmp_shift;
int length = 0;
while (readBytes < LENGTH_LENGTH) {
try {
tmp = in.read();
} catch (java.io.IOException e) {
continue;
}
++readBytes;
tmp_shift = tmp << (LENGTH_LENGTH - readBytes);
length |= tmp_shift;
System.out.printf("raw:%s shifted:%d addedToLength:%d\n", Integer.toHexString(tmp), tmp_shift, length);
}
if (length < 0) {
trace("the client is fucking w/ us. Alternativly the connection died");
terminated = true;
continue;
} else if (readBytes == LENGTH_LENGTH) {
trace("the msg is " + length + " bytes long");
} else {
trace("failed to read length field");
continue;
}
// got length, do work.
InputStreamReader reader = new InputStreamReader(in);
char[] message = new char[length];
int ret;
int offset = 0;
while (offset < length) {
try {
ret = reader.read(message, offset, (length - offset));
} catch(Exception e) {
trace("got exception while reading message: " + e.toString());
break;
}
if (ret == -1) {
trace("fuck. something went south. breaking the parsing of message.");
break;
}
offset += ret;
}
if (offset < length) {
trace("could not read complete message");
terminated = true;
break;
}
Command command;
try {
// TODO get Journal.USER_XXX from db.getuserType(subj) or something
//command = CommandFactory.makeCommand(message, userType)
command = CommandFactory.makeCommand(message, JournalServer.USER_PATIENT);
} catch (UnknownCommandException uce) {
trace("Got unparsable command.");
terminated = true;
break;
}
}
if (terminated)
trace("terminated");
}
}
| public void start(int port) {
SSLServerSocketFactory ssf = null;
SSLServerSocket ss;
String passwds[];
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks, ts;
TrustManagerFactory tmf;
String keyStorePasswd = null;
String keyPasswd = null;
String trustPasswd = null;
try {
passwds = this.readPassword();
keyStorePasswd = passwds[0];
keyPasswd = passwds[1];
trustPasswd = passwds[2];
} catch (java.io.IOException e) {
this.trace("could not read passwords (" + e + ")");
System.exit(1);
}
try {
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("./keystore"), keyStorePasswd.toCharArray());
kmf.init(ks, keyPasswd.toCharArray());
tmf = TrustManagerFactory.getInstance("SunX509");
ts = KeyStore.getInstance("JKS");
ts.load(new FileInputStream("./truststore"), trustPasswd.toCharArray());
tmf.init(ts);
ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
ssf = ctx.getServerSocketFactory();
} catch (Exception e) {
trace("shit went south, bailing. (" + e + ")");
System.exit(1);
}
try {
ss = (SSLServerSocket) ssf.createServerSocket(port);
} catch (Exception e) {
trace("could not bind to port. " + e);
return;
}
ss.setNeedClientAuth(true);
// accept clients, maybe sould be multithreaded later
while (true) {
trace("waiting for incomming connection");
SSLSocket sock;
try {
sock = (SSLSocket) ss.accept();
} catch (java.io.IOException e) {
trace("failed to accept connection");
continue;
}
trace("accepted incomming connection");
// String[] suites = {"TLS_DHE_DSS_WITH_AES_256_CBC_SHA"};
// sock.setEnabledCipherSuites(suites);
SSLSession sess = sock.getSession();
X509Certificate cert;
try {
cert = (X509Certificate)sess.getPeerCertificateChain()[0];
} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
trace("client not verified");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
String subj = cert.getSubjectDN().getName();
trace("client DN: " + subj);
InputStream in;
try {
in = sock.getInputStream();
} catch (java.io.IOException e) {
trace("failed to get inputstream");
try {
sock.close();
} catch (java.io.IOException e2) {
trace("failed closing socket, w/e");
}
continue;
}
boolean terminated = false;
while (!terminated) {
int readBytes = 0;
int tmp, tmp_shift;
int length = 0;
while (readBytes < LENGTH_LENGTH) {
try {
tmp = in.read();
} catch (java.io.IOException e) {
continue;
}
++readBytes;
tmp_shift = tmp << (LENGTH_LENGTH - readBytes);
length |= tmp_shift;
System.out.printf("raw:%s shifted:%d addedToLength:%d\n", Integer.toHexString(tmp), tmp_shift, length);
}
if (length < 0) {
trace("the client is fucking w/ us. Alternativly the connection died");
terminated = true;
continue;
} else if (readBytes == LENGTH_LENGTH) {
trace("the msg is " + length + " bytes long");
} else {
trace("failed to read length field");
continue;
}
// got length, do work.
InputStreamReader reader = new InputStreamReader(in);
char[] message = new char[length];
int ret;
int offset = 0;
while (offset < length) {
try {
ret = reader.read(message, offset, (length - offset));
} catch(Exception e) {
trace("got exception while reading message: " + e.toString());
break;
}
if (ret == -1) {
trace("fuck. something went south. breaking the parsing of message.");
break;
}
offset += ret;
}
if (offset < length) {
trace("could not read complete message");
terminated = true;
break;
}
Command command;
try {
// TODO get Journal.USER_XXX from db.getuserType(subj) or something
//command = CommandFactory.makeCommand(message, userType)
command = CommandFactory.makeCommand(message, JournalServer.USER_PATIENT);
} catch (UnknownCommandException uce) {
trace("Got unparsable command.");
terminated = true;
break;
}
}
if (terminated)
trace("terminated");
}
}
|
diff --git a/src/com/parent/management/monitor/BrowserHistoryMonitor.java b/src/com/parent/management/monitor/BrowserHistoryMonitor.java
index fd4c203..ff698aa 100644
--- a/src/com/parent/management/monitor/BrowserHistoryMonitor.java
+++ b/src/com/parent/management/monitor/BrowserHistoryMonitor.java
@@ -1,129 +1,132 @@
package com.parent.management.monitor;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.provider.Browser;
import android.util.Log;
import com.parent.management.ManagementApplication;
import com.parent.management.db.ManagementProvider;
public class BrowserHistoryMonitor extends Monitor {
private static final String TAG = ManagementApplication.getApplicationTag() + "." +
BrowserHistoryMonitor.class.getSimpleName();
private BrowserHistoryObserver contentObserver = null;
public BrowserHistoryMonitor(Context context) {
super(context);
this.contentUri = Browser.BOOKMARKS_URI;
this.contentObserver = new BrowserHistoryObserver(new Handler());
}
@Override
public void startMonitoring() {
this.contentResolver.registerContentObserver(this.contentUri, true, this.contentObserver);
this.monitorStatus = true;
Log.d(TAG, "----> startMonitoring");
}
@Override
public void stopMonitoring() {
this.contentResolver.unregisterContentObserver(this.contentObserver);
this.monitorStatus = false;
Log.d(TAG, "----> stopMonitoring");
}
private class BrowserHistoryObserver extends ContentObserver {
public BrowserHistoryObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
String[] browserProj = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
String browserSel = Browser.BookmarkColumns.BOOKMARK + " = 0"; // 0 = history, 1 = bookmark
Cursor browserCur = ManagementApplication.getContext().getContentResolver().query(
Browser.BOOKMARKS_URI, null, browserSel, null, null);
- browserCur.moveToFirst();
String title = "";
String url = "";
String id = "";
String count = "";
String last_visit = "";
+ if (browserCur == null) {
+ Log.v(TAG, "open browserHistory native failed");
+ return;
+ }
if (browserCur.moveToFirst() && browserCur.getCount() > 0) {
while (browserCur.isAfterLast() == false) {
title = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.TITLE));
url = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.URL));
id = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns._ID));
count = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.VISITS));
last_visit = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.DATE));
// Do something with title and url
Log.v(TAG, "id=" + id + ";title=" + title + ";url=" + url + ";count=" + count);
String[] browserHistoryProj = new String[] { ManagementProvider.BrowserHistory.ID,
ManagementProvider.BrowserHistory.VISIT_COUNT};
String browserHistorySel = ManagementProvider.BrowserHistory.ID + " = " + id;
Cursor browserHistoryCur = ManagementApplication.getContext().getContentResolver().query(
ManagementProvider.BrowserHistory.CONTENT_URI,
browserHistoryProj, browserHistorySel, null, null);
if (browserHistoryCur == null) {
Log.v(TAG, "open browserHistory failed");
browserCur.close();
return;
}
if (browserHistoryCur.moveToFirst() && browserHistoryCur.getCount() > 0) {
String logged_visit_count = browserHistoryCur.getString(
browserHistoryCur.getColumnIndex(
ManagementProvider.BrowserHistory.VISIT_COUNT));
if (!logged_visit_count.equals(count)) {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
values.put(ManagementProvider.BrowserHistory.IS_SENT,
ManagementProvider.IS_SENT_NO);
ManagementApplication.getContext().getContentResolver().update(
ManagementProvider.BrowserHistory.CONTENT_URI,
values,
ManagementProvider.BrowserHistory.ID + "=\"" + id +"\"",
null);
Log.v(TAG, "update one");
}
} else {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.ID, id);
values.put(ManagementProvider.BrowserHistory.URL, url);
values.put(ManagementProvider.BrowserHistory.TITLE, title);
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
ManagementApplication.getContext().getContentResolver().insert(
ManagementProvider.BrowserHistory.CONTENT_URI, values);
Log.v(TAG, "insert one");
}
browserHistoryCur.close();
browserCur.moveToNext();
}
}
browserCur.close();
}
}
@Override
public Cursor extraData() {
// TODO Auto-generated method stub
return null;
}
}
| false | true | public void onChange(boolean selfChange) {
String[] browserProj = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
String browserSel = Browser.BookmarkColumns.BOOKMARK + " = 0"; // 0 = history, 1 = bookmark
Cursor browserCur = ManagementApplication.getContext().getContentResolver().query(
Browser.BOOKMARKS_URI, null, browserSel, null, null);
browserCur.moveToFirst();
String title = "";
String url = "";
String id = "";
String count = "";
String last_visit = "";
if (browserCur.moveToFirst() && browserCur.getCount() > 0) {
while (browserCur.isAfterLast() == false) {
title = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.TITLE));
url = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.URL));
id = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns._ID));
count = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.VISITS));
last_visit = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.DATE));
// Do something with title and url
Log.v(TAG, "id=" + id + ";title=" + title + ";url=" + url + ";count=" + count);
String[] browserHistoryProj = new String[] { ManagementProvider.BrowserHistory.ID,
ManagementProvider.BrowserHistory.VISIT_COUNT};
String browserHistorySel = ManagementProvider.BrowserHistory.ID + " = " + id;
Cursor browserHistoryCur = ManagementApplication.getContext().getContentResolver().query(
ManagementProvider.BrowserHistory.CONTENT_URI,
browserHistoryProj, browserHistorySel, null, null);
if (browserHistoryCur == null) {
Log.v(TAG, "open browserHistory failed");
browserCur.close();
return;
}
if (browserHistoryCur.moveToFirst() && browserHistoryCur.getCount() > 0) {
String logged_visit_count = browserHistoryCur.getString(
browserHistoryCur.getColumnIndex(
ManagementProvider.BrowserHistory.VISIT_COUNT));
if (!logged_visit_count.equals(count)) {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
values.put(ManagementProvider.BrowserHistory.IS_SENT,
ManagementProvider.IS_SENT_NO);
ManagementApplication.getContext().getContentResolver().update(
ManagementProvider.BrowserHistory.CONTENT_URI,
values,
ManagementProvider.BrowserHistory.ID + "=\"" + id +"\"",
null);
Log.v(TAG, "update one");
}
} else {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.ID, id);
values.put(ManagementProvider.BrowserHistory.URL, url);
values.put(ManagementProvider.BrowserHistory.TITLE, title);
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
ManagementApplication.getContext().getContentResolver().insert(
ManagementProvider.BrowserHistory.CONTENT_URI, values);
Log.v(TAG, "insert one");
}
browserHistoryCur.close();
browserCur.moveToNext();
}
}
browserCur.close();
}
| public void onChange(boolean selfChange) {
String[] browserProj = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
String browserSel = Browser.BookmarkColumns.BOOKMARK + " = 0"; // 0 = history, 1 = bookmark
Cursor browserCur = ManagementApplication.getContext().getContentResolver().query(
Browser.BOOKMARKS_URI, null, browserSel, null, null);
String title = "";
String url = "";
String id = "";
String count = "";
String last_visit = "";
if (browserCur == null) {
Log.v(TAG, "open browserHistory native failed");
return;
}
if (browserCur.moveToFirst() && browserCur.getCount() > 0) {
while (browserCur.isAfterLast() == false) {
title = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.TITLE));
url = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.URL));
id = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns._ID));
count = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.VISITS));
last_visit = browserCur.getString(browserCur.getColumnIndex(Browser.BookmarkColumns.DATE));
// Do something with title and url
Log.v(TAG, "id=" + id + ";title=" + title + ";url=" + url + ";count=" + count);
String[] browserHistoryProj = new String[] { ManagementProvider.BrowserHistory.ID,
ManagementProvider.BrowserHistory.VISIT_COUNT};
String browserHistorySel = ManagementProvider.BrowserHistory.ID + " = " + id;
Cursor browserHistoryCur = ManagementApplication.getContext().getContentResolver().query(
ManagementProvider.BrowserHistory.CONTENT_URI,
browserHistoryProj, browserHistorySel, null, null);
if (browserHistoryCur == null) {
Log.v(TAG, "open browserHistory failed");
browserCur.close();
return;
}
if (browserHistoryCur.moveToFirst() && browserHistoryCur.getCount() > 0) {
String logged_visit_count = browserHistoryCur.getString(
browserHistoryCur.getColumnIndex(
ManagementProvider.BrowserHistory.VISIT_COUNT));
if (!logged_visit_count.equals(count)) {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
values.put(ManagementProvider.BrowserHistory.IS_SENT,
ManagementProvider.IS_SENT_NO);
ManagementApplication.getContext().getContentResolver().update(
ManagementProvider.BrowserHistory.CONTENT_URI,
values,
ManagementProvider.BrowserHistory.ID + "=\"" + id +"\"",
null);
Log.v(TAG, "update one");
}
} else {
final ContentValues values = new ContentValues();
values.put(ManagementProvider.BrowserHistory.ID, id);
values.put(ManagementProvider.BrowserHistory.URL, url);
values.put(ManagementProvider.BrowserHistory.TITLE, title);
values.put(ManagementProvider.BrowserHistory.VISIT_COUNT, count);
values.put(ManagementProvider.BrowserHistory.LAST_VISIT, last_visit);
ManagementApplication.getContext().getContentResolver().insert(
ManagementProvider.BrowserHistory.CONTENT_URI, values);
Log.v(TAG, "insert one");
}
browserHistoryCur.close();
browserCur.moveToNext();
}
}
browserCur.close();
}
|
diff --git a/app/Sketch.java b/app/Sketch.java
index 721983e0b..8c9da3335 100644
--- a/app/Sketch.java
+++ b/app/Sketch.java
@@ -1,2520 +1,2524 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-05 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import processing.app.preproc.*;
import processing.core.*;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import javax.swing.JOptionPane;
import com.oroinc.text.regex.*;
/**
* Stores information about files in the current sketch
*/
public class Sketch {
static File tempBuildFolder;
Editor editor;
/**
* Name of sketch, which is the name of main file
* (without .pde or .java extension)
*/
String name;
/**
* Name of 'main' file, used by load(), such as sketch_04040.pde
*/
String mainFilename;
/**
* true if any of the files have been modified.
*/
boolean modified;
public File folder;
public File dataFolder;
public File codeFolder;
static final int PDE = 0;
static final int JAVA = 1;
public SketchCode current;
int codeCount;
SketchCode code[];
int hiddenCount;
SketchCode hidden[];
Hashtable zipFileContents;
// all these set each time build() is called
String mainClassName;
String classPath;
String libraryPath;
boolean externalRuntime;
Vector importedLibraries; // vec of File objects
/**
* path is location of the main .pde file, because this is also
* simplest to use when opening the file from the finder/explorer.
*/
public Sketch(Editor editor, String path) throws IOException {
this.editor = editor;
File mainFile = new File(path);
//System.out.println("main file is " + mainFile);
mainFilename = mainFile.getName();
//System.out.println("main file is " + mainFilename);
// get the name of the sketch by chopping .pde or .java
// off of the main file name
if (mainFilename.endsWith(".pde")) {
name = mainFilename.substring(0, mainFilename.length() - 4);
} else if (mainFilename.endsWith(".java")) {
name = mainFilename.substring(0, mainFilename.length() - 5);
}
// lib/build must exist when the application is started
// it is added to the CLASSPATH by default, but if it doesn't
// exist when the application is started, then java will remove
// the entry from the CLASSPATH, causing Runner to fail.
//
/*
tempBuildFolder = new File(TEMP_BUILD_PATH);
if (!tempBuildFolder.exists()) {
tempBuildFolder.mkdirs();
Base.showError("Required folder missing",
"A required folder was missing from \n" +
"from your installation of Processing.\n" +
"It has now been replaced, please restart \n" +
"the application to complete the repair.", null);
}
*/
tempBuildFolder = Base.getBuildFolder();
//Base.addBuildFolderToClassPath();
folder = new File(new File(path).getParent());
//System.out.println("sketch dir is " + folder);
load();
}
/**
* Build the list of files.
* <P>
* Generally this is only done once, rather than
* each time a change is made, because otherwise it gets to be
* a nightmare to keep track of what files went where, because
* not all the data will be saved to disk.
* <P>
* This also gets called when the main sketch file is renamed,
* because the sketch has to be reloaded from a different folder.
* <P>
* Another exception is when an external editor is in use,
* in which case the load happens each time "run" is hit.
*/
public void load() {
codeFolder = new File(folder, "code");
dataFolder = new File(folder, "data");
// get list of files in the sketch folder
String list[] = folder.list();
for (int i = 0; i < list.length; i++) {
if (list[i].endsWith(".pde")) codeCount++;
else if (list[i].endsWith(".java")) codeCount++;
else if (list[i].endsWith(".pde.x")) hiddenCount++;
else if (list[i].endsWith(".java.x")) hiddenCount++;
}
code = new SketchCode[codeCount];
hidden = new SketchCode[hiddenCount];
int codeCounter = 0;
int hiddenCounter = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].endsWith(".pde")) {
code[codeCounter++] =
new SketchCode(list[i].substring(0, list[i].length() - 4),
new File(folder, list[i]),
PDE);
} else if (list[i].endsWith(".java")) {
code[codeCounter++] =
new SketchCode(list[i].substring(0, list[i].length() - 5),
new File(folder, list[i]),
JAVA);
} else if (list[i].endsWith(".pde.x")) {
hidden[hiddenCounter++] =
new SketchCode(list[i].substring(0, list[i].length() - 6),
new File(folder, list[i]),
PDE);
} else if (list[i].endsWith(".java.x")) {
hidden[hiddenCounter++] =
new SketchCode(list[i].substring(0, list[i].length() - 7),
new File(folder, list[i]),
JAVA);
}
}
// remove any entries that didn't load properly
int index = 0;
while (index < codeCount) {
if ((code[index] == null) ||
(code[index].program == null)) {
for (int i = index+1; i < codeCount; i++) {
code[i-1] = code[i];
}
codeCount--;
} else {
index++;
}
}
// move the main class to the first tab
// start at 1, if it's at zero, don't bother
for (int i = 1; i < codeCount; i++) {
if (code[i].file.getName().equals(mainFilename)) {
SketchCode temp = code[0];
code[0] = code[i];
code[i] = temp;
break;
}
}
// sort the entries at the top
sortCode();
// set the main file to be the current tab
setCurrent(0);
}
protected void insertCode(SketchCode newCode) {
// make sure the user didn't hide the sketch folder
ensureExistence();
// add file to the code/codeCount list, resort the list
if (codeCount == code.length) {
SketchCode temp[] = new SketchCode[codeCount+1];
System.arraycopy(code, 0, temp, 0, codeCount);
code = temp;
}
code[codeCount++] = newCode;
}
protected void sortCode() {
// cheap-ass sort of the rest of the files
// it's a dumb, slow sort, but there shouldn't be more than ~5 files
for (int i = 1; i < codeCount; i++) {
int who = i;
for (int j = i + 1; j < codeCount; j++) {
if (code[j].name.compareTo(code[who].name) < 0) {
who = j; // this guy is earlier in the alphabet
}
}
if (who != i) { // swap with someone if changes made
SketchCode temp = code[who];
code[who] = code[i];
code[i] = temp;
}
}
}
boolean renamingCode;
public void newCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is Read-Only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save the sketch in another location,\n" +
"and try again.");
return;
}
renamingCode = false;
editor.status.edit("Name for new file:", "");
}
public void renameCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is Read-Only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save the sketch in another location,\n" +
"and try again.");
return;
}
// ask for new name of file (internal to window)
// TODO maybe just popup a text area?
renamingCode = true;
String prompt = (current == code[0]) ?
"New name for sketch:" : "New name for file:";
String oldName =
(current.flavor == PDE) ? current.name : current.name + ".java";
editor.status.edit(prompt, oldName);
}
/**
* This is called upon return from entering a new file name.
* (that is, from either newCode or renameCode after the prompt)
* This code is almost identical for both the newCode and renameCode
* cases, so they're kept merged except for right in the middle
* where they diverge.
*/
public void nameCode(String newName) {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if renaming to the same thing as before, just ignore.
// also ignoring case here, because i don't want to write
// a bunch of special stuff for each platform
// (osx is case insensitive but preserving, windows insensitive,
// *nix is sensitive and preserving.. argh)
if (renamingCode && newName.equalsIgnoreCase(current.name)) {
// exit quietly for the 'rename' case.
// if it's a 'new' then an error will occur down below
return;
}
// don't allow blank names
if (newName.trim().equals("")) {
return;
}
if (newName.trim().equals(".java") ||
newName.trim().equals(".pde")) {
return;
}
String newFilename = null;
int newFlavor = 0;
// separate into newName (no extension) and newFilename (with ext)
// add .pde to file if it has no extension
if (newName.endsWith(".pde")) {
newFilename = newName;
newName = newName.substring(0, newName.length() - 4);
newFlavor = PDE;
} else if (newName.endsWith(".java")) {
// don't show this error if creating a new tab
if (renamingCode && (code[0] == current)) {
Base.showWarning("Problem with rename",
"The main .pde file cannot be .java file.\n" +
"(It may be time for your to graduate to a\n" +
"\"real\" programming environment)", null);
return;
}
newFilename = newName;
newName = newName.substring(0, newName.length() - 5);
newFlavor = JAVA;
} else {
newFilename = newName + ".pde";
newFlavor = PDE;
}
// dots are allowed for the .pde and .java, but not in the name
// make sure the user didn't name things poo.time.pde
// or something like that (nothing against poo time)
if (newName.indexOf('.') != -1) {
newName = Sketchbook.sanitizedName(newName);
newFilename = newName + ((newFlavor == PDE) ? ".pde" : ".java");
}
// create the new file, new SketchCode object and load it
File newFile = new File(folder, newFilename);
if (newFile.exists()) { // yay! users will try anything
Base.showMessage("Nope",
"A file named \"" + newFile + "\" already exists\n" +
"in \"" + folder.getAbsolutePath() + "\"");
return;
}
File newFileHidden = new File(folder, newFilename + ".x");
if (newFileHidden.exists()) {
// don't let them get away with it if they try to create something
// with the same name as something hidden
Base.showMessage("No Way",
"A hidden tab with the same name already exists.\n" +
"Use \"Unhide\" to bring it back.");
return;
}
if (renamingCode) {
if (current == code[0]) {
// get the new folder name/location
File newFolder = new File(folder.getParentFile(), newName);
if (newFolder.exists()) {
Base.showWarning("Cannot Rename",
"Sorry, a sketch (or folder) named " +
"\"" + newName + "\" already exists.", null);
return;
}
// unfortunately this can't be a "save as" because that
// only copies the sketch files and the data folder
// however this *will* first save the sketch, then rename
// first get the contents of the editor text area
if (current.modified) {
current.program = editor.getText();
try {
// save this new SketchCode
current.save();
} catch (Exception e) {
Base.showWarning("Error", "Could not rename the sketch. (0)", e);
return;
}
}
if (!current.file.renameTo(newFile)) {
Base.showWarning("Error",
"Could not rename \"" + current.file.getName() +
"\" to \"" + newFile.getName() + "\"", null);
return;
}
// save each of the other tabs because this is gonna be re-opened
try {
for (int i = 1; i < codeCount; i++) {
//if (code[i].modified) code[i].save();
code[i].save();
}
} catch (Exception e) {
Base.showWarning("Error", "Could not rename the sketch. (1)", e);
return;
}
// now rename the sketch folder and re-open
boolean success = folder.renameTo(newFolder);
if (!success) {
Base.showWarning("Error", "Could not rename the sketch. (2)", null);
return;
}
// if successful, set base properties for the sketch
File mainFile = new File(newFolder, newName + ".pde");
mainFilename = mainFile.getAbsolutePath();
// having saved everything and renamed the folder and the main .pde,
// use the editor to re-open the sketch to re-init state
// (unfortunately this will kill positions for carets etc)
editor.handleOpenUnchecked(mainFilename);
/*
// backtrack and don't rename the sketch folder
success = newFolder.renameTo(folder);
if (!success) {
String msg =
"Started renaming sketch and then ran into\n" +
"nasty trouble. Try to salvage with Copy & Paste\n" +
"or attempt a \"Save As\" to see if that works.";
Base.showWarning("Serious Error", msg, null);
}
return;
}
*/
/*
// set the sketch name... used by the pde and whatnot.
// the name is only set in the sketch constructor,
// so it's important here
name = newName;
code[0].name = newName;
code[0].file = mainFile;
code[0].program = editor.getText();
code[0].save();
folder = newFolder;
// get the changes into the sketchbook menu
editor.sketchbook.rebuildMenus();
// reload the sketch
load();
*/
} else {
if (!current.file.renameTo(newFile)) {
Base.showWarning("Error",
"Could not rename \"" + current.file.getName() +
"\" to \"" + newFile.getName() + "\"", null);
return;
}
// just reopen the class itself
current.name = newName;
current.file = newFile;
current.flavor = newFlavor;
}
} else { // creating a new file
try {
newFile.createNewFile(); // TODO returns a boolean
} catch (IOException e) {
Base.showWarning("Error",
"Could not create the file \"" + newFile + "\"\n" +
"in \"" + folder.getAbsolutePath() + "\"", e);
return;
}
SketchCode newCode = new SketchCode(newName, newFile, newFlavor);
insertCode(newCode);
}
// sort the entries
sortCode();
// set the new guy as current
setCurrent(newName);
// update the tabs
//editor.header.repaint();
editor.header.rebuild();
// force the update on the mac?
Toolkit.getDefaultToolkit().sync();
//editor.header.getToolkit().sync();
}
/**
* Remove a piece of code from the sketch and from the disk.
*/
public void deleteCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is Read-Only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save the sketch in another location,\n" +
"and try again.");
return;
}
// confirm deletion with user, yes/no
Object[] options = { "OK", "Cancel" };
String prompt = (current == code[0]) ?
"Are you sure you want to delete this sketch?" :
"Are you sure you want to delete \"" + current.name + "\"?";
int result = JOptionPane.showOptionDialog(editor,
prompt,
"Delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (result == JOptionPane.YES_OPTION) {
if (current == code[0]) {
// need to unset all the modified flags, otherwise tries
// to do a save on the handleNew()
// delete the entire sketch
Base.removeDir(folder);
// get the changes into the sketchbook menu
//sketchbook.rebuildMenus();
// make a new sketch, and i think this will rebuild the sketch menu
editor.handleNewUnchecked();
} else {
// delete the file
if (!current.file.delete()) {
Base.showMessage("Couldn't do it",
"Could not delete \"" + current.name + "\".");
return;
}
// remove code from the list
removeCode(current);
// just set current tab to the main tab
setCurrent(0);
// update the tabs
editor.header.repaint();
}
}
}
protected void removeCode(SketchCode which) {
// remove it from the internal list of files
// resort internal list of files
for (int i = 0; i < codeCount; i++) {
if (code[i] == which) {
for (int j = i; j < codeCount-1; j++) {
code[j] = code[j+1];
}
codeCount--;
return;
}
}
System.err.println("removeCode: internal error.. could not find code");
}
public void hideCode() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is Read-Only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save the sketch in another location,\n" +
"and try again.");
return;
}
// don't allow hide of the main code
// TODO maybe gray out the menu on setCurrent(0)
if (current == code[0]) {
Base.showMessage("Can't do that",
"You cannot hide the main " +
".pde file from a sketch\n");
return;
}
// rename the file
File newFile = new File(current.file.getAbsolutePath() + ".x");
if (!current.file.renameTo(newFile)) {
Base.showWarning("Error",
"Could not hide " +
"\"" + current.file.getName() + "\".", null);
return;
}
current.file = newFile;
// move it to the hidden list
if (hiddenCount == hidden.length) {
SketchCode temp[] = new SketchCode[hiddenCount+1];
System.arraycopy(hidden, 0, temp, 0, hiddenCount);
hidden = temp;
}
hidden[hiddenCount++] = current;
// remove it from the main list
removeCode(current);
// update the tabs
setCurrent(0);
editor.header.repaint();
//editor.header.rebuild();
}
public void unhideCode(String what) {
SketchCode unhideCode = null;
for (int i = 0; i < hiddenCount; i++) {
if (hidden[i].name.equals(what)) {
//unhideIndex = i;
unhideCode = hidden[i];
// remove from the 'hidden' list
for (int j = i; j < hiddenCount-1; j++) {
hidden[j] = hidden[j+1];
}
hiddenCount--;
break;
}
}
//if (unhideIndex == -1) {
if (unhideCode == null) {
System.err.println("internal error: could find " + what + " to unhide.");
return;
}
if (!unhideCode.file.exists()) {
Base.showMessage("Can't unhide",
"The file \"" + what + "\" no longer exists.");
//System.out.println(unhideCode.file);
return;
}
String unhidePath = unhideCode.file.getAbsolutePath();
File unhideFile =
new File(unhidePath.substring(0, unhidePath.length() - 2));
if (!unhideCode.file.renameTo(unhideFile)) {
Base.showMessage("Can't unhide",
"The file \"" + what + "\" could not be" +
"renamed and unhidden.");
return;
}
unhideCode.file = unhideFile;
insertCode(unhideCode);
sortCode();
setCurrent(unhideCode.name);
editor.header.repaint();
}
/**
* Sets the modified value for the code in the frontmost tab.
*/
public void setModified() {
current.modified = true;
calcModified();
}
public void calcModified() {
modified = false;
for (int i = 0; i < codeCount; i++) {
if (code[i].modified) {
modified = true;
break;
}
}
editor.header.repaint();
}
/**
* Save all code in the current sketch.
*/
public boolean save() throws IOException {
// make sure the user didn't hide the sketch folder
ensureExistence();
// first get the contents of the editor text area
if (current.modified) {
current.program = editor.getText();
}
// don't do anything if not actually modified
//if (!modified) return false;
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is read-only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save this sketch to another location.");
// if the user cancels, give up on the save()
if (!saveAs()) return false;
}
for (int i = 0; i < codeCount; i++) {
if (code[i].modified) code[i].save();
}
calcModified();
return true;
}
/**
* Handles 'Save As' for a sketch.
* <P>
* This basically just duplicates the current sketch folder to
* a new location, and then calls 'Save'. (needs to take the current
* state of the open files and save them to the new folder..
* but not save over the old versions for the old sketch..)
* <P>
* Also removes the previously-generated .class and .jar files,
* because they can cause trouble.
*/
public boolean saveAs() throws IOException {
// get new name for folder
FileDialog fd = new FileDialog(editor,
"Save sketch folder as...",
FileDialog.SAVE);
if (isReadOnly()) {
// default to the sketchbook folder
fd.setDirectory(Preferences.get("sketchbook.path"));
} else {
// default to the parent folder of where this was
fd.setDirectory(folder.getParent());
}
fd.setFile(folder.getName());
fd.show();
String newParentDir = fd.getDirectory();
String newName = fd.getFile();
// user cancelled selection
if (newName == null) return false;
newName = Sketchbook.sanitizeName(newName);
// make sure there doesn't exist a tab with that name already
// (but allow it if it's just the main tab resaving itself.. oops)
File codeAlready = new File(folder, newName + ".pde");
if (codeAlready.exists() && (!newName.equals(name))) {
Base.showMessage("Nope",
"You can't save the sketch as \"" + newName + "\"\n" +
"because the sketch already has a tab with that name.");
return false;
}
// make sure there doesn't exist a tab with that name already
File hiddenAlready = new File(folder, newName + ".pde.x");
if (hiddenAlready.exists()) {
Base.showMessage("Nope",
"You can't save the sketch as \"" + newName + "\"\n" +
"because the sketch already has a " +
"hidden tab with that name.");
return false;
}
// new sketch folder
File newFolder = new File(newParentDir, newName);
// make sure the paths aren't the same
if (newFolder.equals(folder)) {
Base.showWarning("You can't fool me",
"The new sketch name and location are the same as\n" +
"the old. I ain't not doin nuthin' not now.", null);
return false;
}
// check to see if the user is trying to save this sketch
// inside the same sketch
try {
String newPath = newFolder.getCanonicalPath() + File.separator;
String oldPath = folder.getCanonicalPath() + File.separator;
if (newPath.indexOf(oldPath) == 0) {
Base.showWarning("How very Borges of you",
"You cannot save the sketch into a folder\n" +
"inside itself. This would go on forever.", null);
return false;
}
} catch (IOException e) { }
// if the new folder already exists, then need to remove
// its contents before copying everything over
// (user will have already been warned)
if (newFolder.exists()) {
Base.removeDir(newFolder);
}
// in fact, you can't do this on windows because the file dialog
// will instead put you inside the folder, but it happens on osx a lot.
// now make a fresh copy of the folder
newFolder.mkdirs();
// grab the contents of the current tab before saving
// first get the contents of the editor text area
if (current.modified) {
current.program = editor.getText();
}
// save the other tabs to their new location
for (int i = 1; i < codeCount; i++) {
File newFile = new File(newFolder, code[i].file.getName());
code[i].saveAs(newFile);
}
// save the hidden code to its new location
for (int i = 0; i < hiddenCount; i++) {
File newFile = new File(newFolder, hidden[i].file.getName());
hidden[i].saveAs(newFile);
}
// re-copy the data folder (this may take a while.. add progress bar?)
if (dataFolder.exists()) {
File newDataFolder = new File(newFolder, "data");
Base.copyDir(dataFolder, newDataFolder);
}
// re-copy the code folder
if (codeFolder.exists()) {
File newCodeFolder = new File(newFolder, "code");
Base.copyDir(codeFolder, newCodeFolder);
}
// save the main tab with its new name
File newFile = new File(newFolder, newName + ".pde");
code[0].saveAs(newFile);
editor.handleOpenUnchecked(newFile.getPath());
/*
// copy the entire contents of the sketch folder
Base.copyDir(folder, newFolder);
// change the references to the dir location in SketchCode files
for (int i = 0; i < codeCount; i++) {
code[i].file = new File(newFolder, code[i].file.getName());
}
for (int i = 0; i < hiddenCount; i++) {
hidden[i].file = new File(newFolder, hidden[i].file.getName());
}
// remove the old sketch file from the new dir
code[0].file.delete();
// name for the new main .pde file
code[0].file = new File(newFolder, newName + ".pde");
code[0].name = newName;
// write the contents to the renamed file
// (this may be resaved if the code is modified)
code[0].modified = true;
//code[0].save();
//System.out.println("modified is " + modified);
// change the other paths
String oldName = name;
name = newName;
File oldFolder = folder;
folder = newFolder;
dataFolder = new File(folder, "data");
codeFolder = new File(folder, "code");
// remove the 'applet', 'application', 'library' folders
// from the copied version.
// otherwise their .class and .jar files can cause conflicts.
Base.removeDir(new File(folder, "applet"));
Base.removeDir(new File(folder, "application"));
//Base.removeDir(new File(folder, "library"));
// do a "save"
// this will take care of the unsaved changes in each of the tabs
save();
// get the changes into the sketchbook menu
//sketchbook.rebuildMenu();
// done inside Editor instead
// update the tabs for the name change
editor.header.repaint();
*/
// let Editor know that the save was successful
return true;
}
/**
* Prompt the user for a new file to the sketch, then call the
* other addFile() function to actually add it.
*/
public void addFile() {
// make sure the user didn't hide the sketch folder
ensureExistence();
// if read-only, give an error
if (isReadOnly()) {
// if the files are read-only, need to first do a "save as".
Base.showMessage("Sketch is Read-Only",
"Some files are marked \"read-only\", so you'll\n" +
"need to re-save the sketch in another location,\n" +
"and try again.");
return;
}
// get a dialog, select a file to add to the sketch
String prompt =
"Select an image or other data file to copy to your sketch";
//FileDialog fd = new FileDialog(new Frame(), prompt, FileDialog.LOAD);
FileDialog fd = new FileDialog(editor, prompt, FileDialog.LOAD);
fd.show();
String directory = fd.getDirectory();
String filename = fd.getFile();
if (filename == null) return;
// copy the file into the folder. if people would rather
// it move instead of copy, they can do it by hand
File sourceFile = new File(directory, filename);
// now do the work of adding the file
addFile(sourceFile);
}
/**
* Add a file to the sketch.
* <p/>
* .pde or .java files will be added to the sketch folder. <br/>
* .jar, .class, .dll, .jnilib, and .so files will all
* be added to the "code" folder. <br/>
* All other files will be added to the "data" folder.
* <p/>
* If they don't exist already, the "code" or "data" folder
* will be created.
* <p/>
* @return true if successful.
*/
public boolean addFile(File sourceFile) {
String filename = sourceFile.getName();
File destFile = null;
boolean addingCode = false;
// if the file appears to be code related, drop it
// into the code folder, instead of the data folder
if (filename.toLowerCase().endsWith(".class") ||
filename.toLowerCase().endsWith(".jar") ||
filename.toLowerCase().endsWith(".dll") ||
filename.toLowerCase().endsWith(".jnilib") ||
filename.toLowerCase().endsWith(".so")) {
if (!codeFolder.exists()) codeFolder.mkdirs();
destFile = new File(codeFolder, filename);
} else if (filename.toLowerCase().endsWith(".pde") ||
filename.toLowerCase().endsWith(".java")) {
destFile = new File(this.folder, filename);
addingCode = true;
} else {
//File dataFolder = new File(this.folder, "data");
if (!dataFolder.exists()) dataFolder.mkdirs();
destFile = new File(dataFolder, filename);
}
// make sure they aren't the same file
if (!addingCode && sourceFile.equals(destFile)) {
Base.showWarning("You can't fool me",
"This file has already been copied to the\n" +
"location where you're trying to add it.\n" +
"I ain't not doin nuthin'.", null);
return false;
}
// in case the user is "adding" the code in an attempt
// to update the sketch's tabs
if (!sourceFile.equals(destFile)) {
try {
Base.copyFile(sourceFile, destFile);
} catch (IOException e) {
Base.showWarning("Error adding file",
"Could not add '" + filename + "' to the sketch.", e);
return false;
}
}
// make the tabs update after this guy is added
if (addingCode) {
String newName = destFile.getName();
int newFlavor = -1;
if (newName.toLowerCase().endsWith(".pde")) {
newName = newName.substring(0, newName.length() - 4);
newFlavor = PDE;
} else {
newName = newName.substring(0, newName.length() - 5);
newFlavor = JAVA;
}
// see also "nameCode" for identical situation
SketchCode newCode = new SketchCode(newName, destFile, newFlavor);
insertCode(newCode);
sortCode();
setCurrent(newName);
editor.header.repaint();
}
return true;
}
public void importLibrary(String jarPath) {
// make sure the user didn't hide the sketch folder
ensureExistence();
String list[] = Compiler.packageListFromClassPath(jarPath);
// import statements into the main sketch file (code[0])
// if the current code is a .java file, insert into current
if (current.flavor == PDE) {
setCurrent(0);
}
// could also scan the text in the file to see if each import
// statement is already in there, but if the user has the import
// commented out, then this will be a problem.
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < list.length; i++) {
buffer.append("import ");
buffer.append(list[i]);
buffer.append(".*;\n");
}
buffer.append('\n');
buffer.append(editor.getText());
editor.setText(buffer.toString(), 0, 0); // scroll to start
setModified();
}
/**
* Change what file is currently being edited.
* <OL>
* <LI> store the String for the text of the current file.
* <LI> retrieve the String for the text of the new file.
* <LI> change the text that's visible in the text area
* </OL>
*/
public void setCurrent(int which) {
if (current == code[which]) {
//System.out.println("already current, ignoring");
return;
}
// get the text currently being edited
if (current != null) {
current.program = editor.getText();
current.selectionStart = editor.textarea.getSelectionStart();
current.selectionStop = editor.textarea.getSelectionEnd();
current.scrollPosition = editor.textarea.getScrollPosition();
}
current = code[which];
editor.setCode(current);
//editor.setDocument(current.document,
// current.selectionStart, current.selectionStop,
// current.scrollPosition, current.undo);
// set to the text for this file
// 'true' means to wipe out the undo buffer
// (so they don't undo back to the other file.. whups!)
/*
editor.setText(current.program,
current.selectionStart, current.selectionStop,
current.undo);
*/
// set stored caret and scroll positions
//editor.textarea.setScrollPosition(current.scrollPosition);
//editor.textarea.select(current.selectionStart, current.selectionStop);
//editor.textarea.setSelectionStart(current.selectionStart);
//editor.textarea.setSelectionEnd(current.selectionStop);
editor.header.rebuild();
}
/**
* Internal helper function to set the current tab
* based on a name (used by codeNew and codeRename).
*/
protected void setCurrent(String findName) {
for (int i = 0; i < codeCount; i++) {
if (findName.equals(code[i].name)) {
setCurrent(i);
return;
}
}
}
/**
* Cleanup temporary files used during a build/run.
*/
protected void cleanup() {
// if the java runtime is holding onto any files in the build dir, we
// won't be able to delete them, so we need to force a gc here
System.gc();
// note that we can't remove the builddir itself, otherwise
// the next time we start up, internal runs using Runner won't
// work because the build dir won't exist at startup, so the classloader
// will ignore the fact that that dir is in the CLASSPATH in run.sh
Base.removeDescendants(tempBuildFolder);
}
/**
* Preprocess, Compile, and Run the current code.
* <P>
* There are three main parts to this process:
* <PRE>
* (0. if not java, then use another 'engine'.. i.e. python)
*
* 1. do the p5 language preprocessing
* this creates a working .java file in a specific location
* better yet, just takes a chunk of java code and returns a
* new/better string editor can take care of saving this to a
* file location
*
* 2. compile the code from that location
* catching errors along the way
* placing it in a ready classpath, or .. ?
*
* 3. run the code
* needs to communicate location for window
* and maybe setup presentation space as well
* run externally if a code folder exists,
* or if more than one file is in the project
*
* X. afterwards, some of these steps need a cleanup function
* </PRE>
*/
public boolean handleRun() throws RunnerException {
// make sure the user didn't hide the sketch folder
ensureExistence();
current.program = editor.getText();
// TODO record history here
//current.history.record(program, SketchHistory.RUN);
// if an external editor is being used, need to grab the
// latest version of the code from the file.
if (Preferences.getBoolean("editor.external")) {
// history gets screwed by the open..
//String historySaved = history.lastRecorded;
//handleOpen(sketch);
//history.lastRecorded = historySaved;
// nuke previous files and settings, just get things loaded
load();
}
// in case there were any boogers left behind
// do this here instead of after exiting, since the exit
// can happen so many different ways.. and this will be
// better connected to the dataFolder stuff below.
cleanup();
// make up a temporary class name to suggest.
// name will only be used if the code is not in ADVANCED mode.
String suggestedClassName =
("Temporary_" + String.valueOf((int) (Math.random() * 10000)) +
"_" + String.valueOf((int) (Math.random() * 10000)));
// handle preprocessing the main file's code
//mainClassName = build(TEMP_BUILD_PATH, suggestedClassName);
mainClassName =
build(tempBuildFolder.getAbsolutePath(), suggestedClassName);
// externalPaths is magically set by build()
if (!externalRuntime) { // only if not running externally already
// copy contents of data dir into lib/build
if (dataFolder.exists()) {
// just drop the files in the build folder (pre-68)
//Base.copyDir(dataDir, buildDir);
// drop the files into a 'data' subfolder of the build dir
try {
Base.copyDir(dataFolder, new File(tempBuildFolder, "data"));
} catch (IOException e) {
e.printStackTrace();
throw new RunnerException("Problem copying files from data folder");
}
}
}
return (mainClassName != null);
}
/**
* Build all the code for this sketch.
*
* In an advanced program, the returned classname could be different,
* which is why the className is set based on the return value.
* A compilation error will burp up a RunnerException.
*
* @return null if compilation failed, main class name if not
*/
protected String build(String buildPath, String suggestedClassName)
throws RunnerException {
// make sure the user didn't hide the sketch folder
ensureExistence();
String codeFolderPackages[] = null;
String javaClassPath = System.getProperty("java.class.path");
// remove quotes if any.. this is an annoying thing on windows
if (javaClassPath.startsWith("\"") && javaClassPath.endsWith("\"")) {
javaClassPath = javaClassPath.substring(1, javaClassPath.length() - 1);
}
//PApplet.println(PApplet.split(Sketchbook.librariesClassPath, ';'));
//PApplet.println(PApplet.split(buildPath, ';'));
//PApplet.println(PApplet.split(javaClassPath, ';'));
classPath = buildPath +
File.pathSeparator + Sketchbook.librariesClassPath +
File.pathSeparator + javaClassPath;
//System.out.println("cp = " + classPath);
// figure out the contents of the code folder to see if there
// are files that need to be added to the imports
//File codeFolder = new File(folder, "code");
if (codeFolder.exists()) {
externalRuntime = true;
//classPath += File.pathSeparator +
//Compiler.contentsToClassPath(codeFolder);
classPath =
Compiler.contentsToClassPath(codeFolder) +
File.pathSeparator + classPath;
//codeFolderPackages = Compiler.packageListFromClassPath(classPath);
//codeFolderPackages = Compiler.packageListFromClassPath(codeFolder);
libraryPath = codeFolder.getAbsolutePath();
// get a list of .jar files in the "code" folder
// (class files in subfolders should also be picked up)
String codeFolderClassPath =
Compiler.contentsToClassPath(codeFolder);
// get list of packages found in those jars
codeFolderPackages =
Compiler.packageListFromClassPath(codeFolderClassPath);
//PApplet.println(libraryPath);
//PApplet.println("packages:");
//PApplet.printarr(codeFolderPackages);
} else {
// since using the special classloader,
// run externally whenever there are extra classes defined
//externalRuntime = (codeCount > 1);
// this no longer appears to be true.. so scrapping for 0088
// check to see if multiple files that include a .java file
externalRuntime = false;
for (int i = 0; i < codeCount; i++) {
if (code[i].flavor == JAVA) {
externalRuntime = true;
break;
}
}
//codeFolderPackages = null;
libraryPath = "";
}
// if 'data' folder is large, set to external runtime
if (dataFolder.exists() &&
Base.calcFolderSize(dataFolder) > 768 * 1024) { // if > 768k
externalRuntime = true;
}
// 1. concatenate all .pde files to the 'main' pde
// store line number for starting point of each code bit
StringBuffer bigCode = new StringBuffer(code[0].program);
int bigCount = countLines(code[0].program);
for (int i = 1; i < codeCount; i++) {
if (code[i].flavor == PDE) {
code[i].preprocOffset = ++bigCount;
bigCode.append('\n');
bigCode.append(code[i].program);
bigCount += countLines(code[i].program);
code[i].preprocName = null; // don't compile me
}
}
// since using the special classloader,
// run externally whenever there are extra classes defined
if ((bigCode.indexOf(" class ") != -1) ||
(bigCode.indexOf("\nclass ") != -1)) {
externalRuntime = true;
}
// if running in opengl mode, this is gonna be external
//if (Preferences.get("renderer").equals("opengl")) {
//externalRuntime = true;
//}
// 2. run preproc on that code using the sugg class name
// to create a single .java file and write to buildpath
String primaryClassName = null;
PdePreprocessor preprocessor = new PdePreprocessor();
try {
// if (i != 0) preproc will fail if a pde file is not
// java mode, since that's required
String className =
preprocessor.write(bigCode.toString(), buildPath,
suggestedClassName, codeFolderPackages);
if (className == null) {
throw new RunnerException("Could not find main class");
// this situation might be perfectly fine,
// (i.e. if the file is empty)
//System.out.println("No class found in " + code[i].name);
//System.out.println("(any code in that file will be ignored)");
//System.out.println();
} else {
code[0].preprocName = className + ".java";
}
// store this for the compiler and the runtime
primaryClassName = className;
//System.out.println("primary class " + primaryClassName);
// check if the 'main' file is in java mode
if ((PdePreprocessor.programType == PdePreprocessor.JAVA) ||
(preprocessor.extraImports.length != 0)) {
externalRuntime = true; // we in advanced mode now, boy
}
} catch (antlr.RecognitionException re) {
// this even returns a column
int errorFile = 0;
int errorLine = re.getLine() - 1;
for (int i = 1; i < codeCount; i++) {
if ((code[i].flavor == PDE) &&
(code[i].preprocOffset < errorLine)) {
errorFile = i;
}
}
errorLine -= code[errorFile].preprocOffset;
throw new RunnerException(re.getMessage(), errorFile,
errorLine, re.getColumn());
} catch (antlr.TokenStreamRecognitionException tsre) {
// while this seems to store line and column internally,
// there doesn't seem to be a method to grab it..
// so instead it's done using a regexp
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
// line 3:1: unexpected char: 0xA0
String mess = "^line (\\d+):(\\d+):\\s";
Pattern pattern = null;
try {
pattern = compiler.compile(mess);
} catch (MalformedPatternException e) {
Base.showWarning("Internal Problem",
"An internal error occurred while trying\n" +
"to compile the sketch. Please report\n" +
"this online at http://processing.org/bugs", e);
}
PatternMatcherInput input =
new PatternMatcherInput(tsre.toString());
if (matcher.contains(input, pattern)) {
MatchResult result = matcher.getMatch();
int errorLine = Integer.parseInt(result.group(1).toString()) - 1;
int errorColumn = Integer.parseInt(result.group(2).toString());
int errorFile = 0;
for (int i = 1; i < codeCount; i++) {
if ((code[i].flavor == PDE) &&
(code[i].preprocOffset < errorLine)) {
errorFile = i;
}
}
errorLine -= code[errorFile].preprocOffset;
throw new RunnerException(tsre.getMessage(),
errorFile, errorLine, errorColumn);
} else {
// this is bad, defaults to the main class.. hrm.
throw new RunnerException(tsre.toString(), 0, -1, -1);
}
} catch (RunnerException pe) {
// RunnerExceptions are caught here and re-thrown, so that they don't
// get lost in the more general "Exception" handler below.
throw pe;
} catch (Exception ex) {
// TODO better method for handling this?
System.err.println("Uncaught exception type:" + ex.getClass());
ex.printStackTrace();
throw new RunnerException(ex.toString());
}
// grab the imports from the code just preproc'd
importedLibraries = new Vector();
String imports[] = preprocessor.extraImports;
for (int i = 0; i < imports.length; i++) {
// remove things up to the last dot
String entry = imports[i].substring(0, imports[i].lastIndexOf('.'));
//System.out.println("found package " + entry);
File libFolder = (File) Sketchbook.importToLibraryTable.get(entry);
if (libFolder == null) {
//throw new RunnerException("Could not find library for " + entry);
continue;
}
importedLibraries.add(libFolder);
libraryPath += File.pathSeparator + libFolder.getAbsolutePath();
/*
String list[] = libFolder.list();
if (list != null) {
for (int j = 0; j < list.length; j++) {
// this might have a dll/jnilib/so packed,
// so add it to the library path
if (list[j].toLowerCase().endsWith(".jar")) {
libraryPath += File.pathSeparator +
libFolder.getAbsolutePath() + File.separator + list[j];
}
}
}
*/
}
// 3. then loop over the code[] and save each .java file
for (int i = 0; i < codeCount; i++) {
if (code[i].flavor == JAVA) {
// no pre-processing services necessary for java files
// just write the the contents of 'program' to a .java file
// into the build directory. uses byte stream and reader/writer
// shtuff so that unicode bunk is properly handled
String filename = code[i].name + ".java";
try {
Base.saveFile(code[i].program, new File(buildPath, filename));
} catch (IOException e) {
e.printStackTrace();
throw new RunnerException("Problem moving " + filename +
" to the build folder");
}
code[i].preprocName = filename;
}
}
// compile the program. errors will happen as a RunnerException
// that will bubble up to whomever called build().
//
Compiler compiler = new Compiler();
boolean success = compiler.compile(this, buildPath);
//System.out.println("success = " + success + " ... " + primaryClassName);
return success ? primaryClassName : null;
}
protected int countLines(String what) {
char c[] = what.toCharArray();
int count = 0;
for (int i = 0; i < c.length; i++) {
if (c[i] == '\n') count++;
}
return count;
}
/**
* Initiate export to applet.
* <PRE>
* +-------------------------------------------------------+
* + +
* + Export to: [ Applet (for the web) + ] [ OK ] +
* + +
* + > Advanced +
* + +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Version: [ Java 1.1 + ] +
* + +
* + Recommended version of Java when exporting applets. +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Version: [ Java 1.3 + ] +
* + +
* + Java 1.3 is not recommended for applets, +
* + unless you are using features that require it. +
* + Using a version of Java other than 1.1 will require +
* + your Windows users to install the Java Plug-In, +
* + and your Macintosh users to be running OS X. +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Version: [ Java 1.4 + ] +
* + +
* + identical message as 1.3 above... +
* + +
* +-------------------------------------------------------+
* </PRE>
*/
public boolean exportApplet() throws Exception {
// make sure the user didn't hide the sketch folder
ensureExistence();
zipFileContents = new Hashtable();
// nuke the old applet folder because it can cause trouble
File appletFolder = new File(folder, "applet");
Base.removeDir(appletFolder);
appletFolder.mkdirs();
// build the sketch
String foundName = build(appletFolder.getPath(), name);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// if name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!name.equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + name + " but the sketch\n" +
"name in the code was " + foundName, null);
return false;
}
int wide = PApplet.DEFAULT_WIDTH;
int high = PApplet.DEFAULT_HEIGHT;
PatternMatcher matcher = new Perl5Matcher();
PatternCompiler compiler = new Perl5Compiler();
// this matches against any uses of the size() function,
// whether they contain numbers of variables or whatever.
// this way, no warning is shown if size() isn't actually
// used in the applet, which is the case especially for
// beginners that are cutting/pasting from the reference.
// modified for 83 to match size(XXX, ddd so that it'll
// properly handle size(200, 200) and size(200, 200, P3D)
String sizing =
"[\\s\\;]size\\s*\\(\\s*(\\S+)\\s*,\\s*(\\d+)";
Pattern pattern = compiler.compile(sizing);
// adds a space at the beginning, in case size() is the very
// first thing in the program (very common), since the regexp
// needs to check for things in front of it.
PatternMatcherInput input =
new PatternMatcherInput(" " + code[0].program);
if (matcher.contains(input, pattern)) {
MatchResult result = matcher.getMatch();
try {
wide = Integer.parseInt(result.group(1).toString());
high = Integer.parseInt(result.group(2).toString());
} catch (NumberFormatException e) {
// found a reference to size, but it didn't
// seem to contain numbers
final String message =
"The size of this applet could not automatically be\n" +
"determined from your code. You'll have to edit the\n" +
"HTML file to set the size of the applet.";
Base.showWarning("Could not find applet size", message, null);
}
} // else no size() command found
// originally tried to grab this with a regexp matcher,
// but it wouldn't span over multiple lines for the match.
// this could prolly be forced, but since that's the case
// better just to parse by hand.
StringBuffer dbuffer = new StringBuffer();
String lines[] = PApplet.split(code[0].program, '\n');
for (int i = 0; i < lines.length; i++) {
if (lines[i].trim().startsWith("/**")) { // this is our comment
// some smartass put the whole thing on the same line
//if (lines[j].indexOf("*/") != -1) break;
for (int j = i+1; j < lines.length; j++) {
if (lines[j].trim().endsWith("*/")) {
// remove the */ from the end, and any extra *s
// in case there's also content on this line
// nah, don't bother.. make them use the three lines
break;
}
int offset = 0;
while ((offset < lines[j].length()) &&
((lines[j].charAt(offset) == '*') ||
(lines[j].charAt(offset) == ' '))) {
offset++;
}
// insert the return into the html to help w/ line breaks
dbuffer.append(lines[j].substring(offset) + "\n");
}
}
}
String description = dbuffer.toString();
StringBuffer sources = new StringBuffer();
for (int i = 0; i < codeCount; i++) {
sources.append("<a href=\"" + code[i].file.getName() + "\">" +
code[i].name + "</a> ");
}
//
// convert the applet template
// @@sketch@@, @@width@@, @@height@@, @@archive@@, @@source@@
// and now @@description@@
File htmlOutputFile = new File(appletFolder, "index.html");
FileOutputStream fos = new FileOutputStream(htmlOutputFile);
PrintStream ps = new PrintStream(fos);
InputStream is = null;
// if there is an applet.html file in the sketch folder, use that
File customHtml = new File(folder, "applet.html");
if (customHtml.exists()) {
is = new FileInputStream(customHtml);
}
if (is == null) {
is = Base.getStream("export/applet.html");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(line);
int index = 0;
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
name);
}
while ((index = sb.indexOf("@@source@@")) != -1) {
sb.replace(index, index + "@@source@@".length(),
sources.toString());
}
while ((index = sb.indexOf("@@archive@@")) != -1) {
sb.replace(index, index + "@@archive@@".length(),
name + ".jar");
}
while ((index = sb.indexOf("@@width@@")) != -1) {
sb.replace(index, index + "@@width@@".length(),
String.valueOf(wide));
}
while ((index = sb.indexOf("@@height@@")) != -1) {
sb.replace(index, index + "@@height@@".length(),
String.valueOf(high));
}
while ((index = sb.indexOf("@@description@@")) != -1) {
sb.replace(index, index + "@@description@@".length(),
description);
}
line = sb.toString();
}
ps.println(line);
}
reader.close();
ps.flush();
ps.close();
//
// copy the loading gif to the applet
String LOADING_IMAGE = "loading.gif";
File loadingImage = new File(folder, LOADING_IMAGE);
if (!loadingImage.exists()) {
loadingImage = new File("lib", LOADING_IMAGE);
}
Base.copyFile(loadingImage, new File(appletFolder, LOADING_IMAGE));
// copy the source files to the target, since we like
// to encourage people to share their code
for (int i = 0; i < codeCount; i++) {
try {
Base.copyFile(code[i].file,
new File(appletFolder, code[i].file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// create new .jar file
FileOutputStream zipOutputFile =
new FileOutputStream(new File(appletFolder, name + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
ZipEntry entry;
// add the manifest file
addManifest(zos);
// add the contents of the code folder to the jar
// unpacks all jar files
//File codeFolder = new File(folder, "code");
if (codeFolder.exists()) {
String includes = Compiler.contentsToClassPath(codeFolder);
packClassPathIntoZipFile(includes, zos);
}
// add contents of 'library' folders to the jar file
// if a file called 'export.txt' is in there, it contains
// a list of the files that should be exported.
// otherwise, all files are exported.
Enumeration en = importedLibraries.elements();
while (en.hasMoreElements()) {
// in the list is a File object that points the
// library sketch's "library" folder
File libraryFolder = (File)en.nextElement();
File exportSettings = new File(libraryFolder, "export.txt");
Hashtable exportTable = readSettings(exportSettings);
String appletList = (String) exportTable.get("applet");
String exportList[] = null;
if (appletList != null) {
exportList = PApplet.split(appletList, ", ");
} else {
exportList = libraryFolder.list();
}
for (int i = 0; i < exportList.length; i++) {
if (exportList[i].equals(".") ||
exportList[i].equals("..")) continue;
exportList[i] = PApplet.trim(exportList[i]);
if (exportList[i].equals("")) continue;
File exportFile = new File(libraryFolder, exportList[i]);
if (!exportFile.exists()) {
System.err.println("File " + exportList[i] + " does not exist");
} else if (exportFile.isDirectory()) {
System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
} else if (exportFile.getName().toLowerCase().endsWith(".zip") ||
exportFile.getName().toLowerCase().endsWith(".jar")) {
packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos);
} else { // just copy the file over.. prolly a .dll or something
Base.copyFile(exportFile,
new File(appletFolder, exportFile.getName()));
}
}
}
String bagelJar = "lib/core.jar";
packClassPathIntoZipFile(bagelJar, zos);
if (dataFolder.exists()) {
//String dataFiles[] = dataFolder.list();
String dataFiles[] = Base.listFiles(dataFolder, false);
int offset = folder.getAbsolutePath().length() + 1;
//int offset = dataFolder.getAbsolutePath().length() + 1;
for (int i = 0; i < dataFiles.length; i++) {
if (PApplet.platform == PApplet.WINDOWS) {
dataFiles[i] = dataFiles[i].replace('\\', '/');
}
File dataFile = new File(dataFiles[i]);
if (dataFile.isDirectory()) continue;
// don't export hidden files
// skipping dot prefix removes all: . .. .DS_Store
//if (dataFiles[i].charAt(0) == '.') continue;
if (dataFile.getName().charAt(0) == '.') continue;
//System.out.println("placing " + dataFiles[i].substring(offset));
//if (dataFile.isDirectory()) {
//entry = new ZipEntry(dataFiles[i].substring(offset) + "/");
//} else {
entry = new ZipEntry(dataFiles[i].substring(offset));
//}
//if (entry.isDirectory()) {
//System.out.println(entry + " is a dir");
//}
zos.putNextEntry(entry);
//zos.write(Base.grabFile(new File(dataFolder, dataFiles[i])));
//if (!dataFile.isDirectory()) {
zos.write(Base.grabFile(dataFile));
//}
zos.closeEntry();
}
}
// add the project's .class files to the jar
// just grabs everything from the build directory
// since there may be some inner classes
// (add any .class files from the applet dir, then delete them)
// TODO this needs to be recursive (for packages)
String classfiles[] = appletFolder.list();
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
entry = new ZipEntry(classfiles[i]);
zos.putNextEntry(entry);
zos.write(Base.grabFile(new File(appletFolder, classfiles[i])));
zos.closeEntry();
}
}
// remove the .class files from the applet folder. if they're not
// removed, the msjvm will complain about an illegal access error,
// since the classes are outside the jar file.
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
File deadguy = new File(appletFolder, classfiles[i]);
if (!deadguy.delete()) {
Base.showWarning("Could not delete",
classfiles[i] + " could not \n" +
"be deleted from the applet folder. \n" +
"You'll need to remove it by hand.", null);
}
}
}
// close up the jar file
zos.flush();
zos.close();
return true;
}
/**
* Export to application.
* <PRE>
* +-------------------------------------------------------+
* + +
* + Export to: [ Application + ] [ OK ] +
* + +
* + > Advanced +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Version: [ Java 1.1 + ] +
* + +
* + Not much point to using Java 1.1 for applications. +
* + To run applications, all users will have to +
* + install Java, in which case they'll most likely +
* + have version 1.3 or later. +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Version: [ Java 1.3 + ] +
* + +
* + Java 1.3 is the recommended setting for exporting +
* + applications. Applications will run on any Windows +
* + or Unix machine with Java installed. Mac OS X has +
* + Java installed with the operation system, so there +
* + is no additional installation will be required. +
* + +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + +
* + Platform: [ Mac OS X + ] <-- defaults to current platform
* + +
* + Exports the application as a double-clickable +
* + .app package, compatible with Mac OS X. +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Platform: [ Windows + ] +
* + +
* + Exports the application as a double-clickable +
* + .exe and a handful of supporting files. +
* + - - - - - - - - - - - - - - - - - - - - - - - - - - - +
* + Platform: [ jar file + ] +
* + +
* + A jar file can be used on any platform that has +
* + Java installed. Simply doube-click the jar (or type +
* + "java -jar sketch.jar" at a command prompt) to run +
* + the application. It is the least fancy method for +
* + exporting. +
* + +
* +-------------------------------------------------------+
* </PRE>
*/
public boolean exportApplication(int exportPlatform) throws Exception {
// make sure the user didn't hide the sketch folder
ensureExistence();
//int exportPlatform = PApplet.platform; //PConstants.MACOSX;
String exportPlatformStr = null;
if (exportPlatform == PConstants.WINDOWS) {
exportPlatformStr = "windows";
} else if (exportPlatform == PConstants.MACOSX) {
exportPlatformStr = "macosx";
} else if (exportPlatform == PConstants.LINUX) {
exportPlatformStr = "linux";
} else {
exportPlatform = -1;
}
String folderName = "application";
if (exportPlatform != -1) {
folderName += "." + exportPlatformStr;
}
// nuke the old folder because it can cause trouble
File destFolder = new File(folder, folderName);
Base.removeDir(destFolder);
destFolder.mkdirs();
// build the sketch
String foundName = build(destFolder.getPath(), name);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// if name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!name.equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + name + " but the sketch\n" +
"name in the code was " + foundName, null);
return false;
}
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, name + ".app");
String APP_SKELETON = "skeleton.app";
//File dotAppSkeleton = new File(folder, APP_SKELETON);
File dotAppSkeleton = new File("lib/export/" + APP_SKELETON);
Base.copyDir(dotAppSkeleton, dotAppFolder);
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (PApplet.platform == PConstants.WINDOWS) {
File warningFile = new File(destFolder, "readme.txt");
PrintStream ps = new PrintStream(new FileOutputStream(warningFile));
ps.println("This application was created on Windows, which doesn't");
ps.println("properly support setting files as \"executable\",");
ps.println("a necessity for applications on Mac OS X.");
ps.println();
ps.println("To fix this, use the Terminal on Mac OS X, and from this");
ps.println("directory, type the following:");
ps.println();
ps.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
ps.flush();
ps.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
// set the jar folder to a different location than windows/linux
jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
}
/// make the jar folder (windows and linux)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
Base.copyFile(new File("lib/export/application.exe"),
new File(destFolder, this.name + ".exe"));
}
/// start copying all jar files
Vector jarListVector = new Vector();
/// create the main .jar file
zipFileContents = new Hashtable();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, name + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
String classfiles[] = destFolder.list();
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
entry = new ZipEntry(classfiles[i]);
zos.putNextEntry(entry);
zos.write(Base.grabFile(new File(destFolder, classfiles[i])));
zos.closeEntry();
}
}
// add the data folder to the main jar file
if (dataFolder.exists()) {
String dataFiles[] = Base.listFiles(dataFolder, false);
int offset = folder.getAbsolutePath().length() + 1;
for (int i = 0; i < dataFiles.length; i++) {
if (PApplet.platform == PApplet.WINDOWS) {
dataFiles[i] = dataFiles[i].replace('\\', '/');
}
File dataFile = new File(dataFiles[i]);
if (dataFile.isDirectory()) continue;
// don't export hidden files
// skipping dot prefix removes all: . .. .DS_Store
if (dataFile.getName().charAt(0) == '.') continue;
entry = new ZipEntry(dataFiles[i].substring(offset));
zos.putNextEntry(entry);
zos.write(Base.grabFile(dataFile));
zos.closeEntry();
}
}
// add the contents of the code folder to the jar
// (will unpack all jar files in the code folder)
if (codeFolder.exists()) {
String includes = Compiler.contentsToClassPath(codeFolder);
packClassPathIntoZipFile(includes, zos);
}
zos.flush();
zos.close();
jarListVector.add(name + ".jar");
/// add core.jar to the jar destination folder
//System.out.println(jarFolder);
Base.copyFile(new File("lib/core.jar"), new File(jarFolder, "core.jar"));
jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
// if a file called 'export.txt' is in there, it contains
// a list of the files that should be exported.
// otherwise, all files are exported.
Enumeration en = importedLibraries.elements();
while (en.hasMoreElements()) {
File libraryFolder = (File)en.nextElement();
// in the list is a File object that points the
// library sketch's "library" folder
File exportSettings = new File(libraryFolder, "export.txt");
Hashtable exportTable = readSettings(exportSettings);
String commaList = null;
String exportList[] = null;
if (exportPlatform != -1) {
// first check to see if there's something like application.macosx
commaList = (String)
exportTable.get("application." + exportPlatformStr);
}
if (commaList == null) {
// next check to see if something for 'application' is specified
commaList = (String) exportTable.get("application");
}
if (commaList == null) {
// otherwise just dump the whole folder
exportList = libraryFolder.list();
+ } else {
+ exportList = PApplet.split(commaList, ", ");
}
// add each item from the library folder / export list to the output
for (int i = 0; i < exportList.length; i++) {
if (exportList[i].equals(".") ||
exportList[i].equals("..")) continue;
exportList[i] = PApplet.trim(exportList[i]);
if (exportList[i].equals("")) continue;
File exportFile = new File(libraryFolder, exportList[i]);
if (!exportFile.exists()) {
System.err.println("File " + exportList[i] + " does not exist");
} else if (exportFile.isDirectory()) {
System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
} else if (exportFile.getName().toLowerCase().endsWith(".zip") ||
exportFile.getName().toLowerCase().endsWith(".jar")) {
//packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos);
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
jarListVector.add(exportList[i]);
} else if ((exportPlatform == PConstants.MACOSX) &&
(exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// jnilib files can be placed in Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
} else {
// copy the file to the main directory.. prolly a .dll or something
Base.copyFile(exportFile,
new File(destFolder, exportFile.getName()));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("lib/" + jarList[i]);
}
}
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
String PLIST_TEMPLATE = "template.plist";
File plistTemplate = new File(folder, PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
plistTemplate = new File("lib/export/" + PLIST_TEMPLATE);
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintStream ps = new PrintStream(new FileOutputStream(plistFile));
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
name);
}
while ((index = sb.indexOf("@@classpath@@")) != -1) {
sb.replace(index, index + "@@classpath@@".length(),
exportClassPath.toString());
}
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
ps.print(lines[i] + "\n");
}
ps.flush();
ps.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintStream ps = new PrintStream(new FileOutputStream(argsFile));
ps.println(Preferences.get("run.options"));
ps.println(this.name);
ps.println(exportClassPath);
ps.flush();
ps.close();
} else {
File shellScript = new File(destFolder, this.name);
PrintStream ps = new PrintStream(new FileOutputStream(shellScript));
// do the newlines explicitly so that windows CRLF
// isn't used when exporting for unix
ps.print("#!/bin/sh\n\n");
ps.print("java " + Preferences.get("run.options") +
" -cp " + exportClassPath +
" " + this.name + "\n");
ps.flush();
ps.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
- Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
+ if (PApplet.platform != PConstants.WINDOWS) {
+ Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
+ }
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (int i = 0; i < codeCount; i++) {
try {
Base.copyFile(code[i].file,
new File(sourceFolder, code[i].file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = this.name + ".java";
File preprocFile = new File(destFolder, preprocFilename);
if (preprocFile.exists()) {
preprocFile.renameTo(new File(sourceFolder, preprocFilename));
}
/// remove the .class files from the export folder.
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
File deadguy = new File(destFolder, classfiles[i]);
if (!deadguy.delete()) {
Base.showWarning("Could not delete",
classfiles[i] + " could not \n" +
"be deleted from the applet folder. \n" +
"You'll need to remove it by hand.", null);
}
}
}
/// goodbye
return true;
}
public void addManifest(ZipOutputStream zos) throws IOException {
ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
zos.putNextEntry(entry);
String contents =
"Manifest-Version: 1.0\n" +
"Created-By: Processing " + Base.VERSION_NAME + "\n" +
"Main-Class: " + name + "\n"; // TODO not package friendly
zos.write(contents.getBytes());
zos.closeEntry();
}
/**
* Read from a file with a bunch of attribute/value pairs
* that are separated by = and ignore comments with #.
*/
protected Hashtable readSettings(File inputFile) {
Hashtable outgoing = new Hashtable();
if (!inputFile.exists()) return outgoing; // return empty hash
String lines[] = PApplet.loadStrings(inputFile);
for (int i = 0; i < lines.length; i++) {
int hash = lines[i].indexOf('#');
String line = (hash == -1) ?
lines[i].trim() : lines[i].substring(hash).trim();
if (line.length() == 0) continue;
int equals = line.indexOf('=');
if (equals == -1) {
System.err.println("ignoring illegal line in " + inputFile);
System.err.println(" " + line);
continue;
}
String attr = line.substring(0, equals).trim();
String valu = line.substring(equals + 1).trim();
outgoing.put(attr, valu);
}
return outgoing;
}
/**
* Slurps up .class files from a colon (or semicolon on windows)
* separated list of paths and adds them to a ZipOutputStream.
*/
public void packClassPathIntoZipFile(String path,
ZipOutputStream zos)
throws IOException {
String pieces[] = PApplet.split(path, File.pathSeparatorChar);
for (int i = 0; i < pieces.length; i++) {
if (pieces[i].length() == 0) continue;
//System.out.println("checking piece " + pieces[i]);
// is it a jar file or directory?
if (pieces[i].toLowerCase().endsWith(".jar") ||
pieces[i].toLowerCase().endsWith(".zip")) {
try {
ZipFile file = new ZipFile(pieces[i]);
Enumeration entries = file.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.isDirectory()) {
// actually 'continue's for all dir entries
} else {
String entryName = entry.getName();
// ignore contents of the META-INF folders
if (entryName.indexOf("META-INF") == 0) continue;
// don't allow duplicate entries
if (zipFileContents.get(entryName) != null) continue;
zipFileContents.put(entryName, new Object());
ZipEntry entree = new ZipEntry(entryName);
zos.putNextEntry(entree);
byte buffer[] = new byte[(int) entry.getSize()];
InputStream is = file.getInputStream(entry);
int offset = 0;
int remaining = buffer.length;
while (remaining > 0) {
int count = is.read(buffer, offset, remaining);
offset += count;
remaining -= count;
}
zos.write(buffer);
zos.flush();
zos.closeEntry();
}
}
} catch (IOException e) {
System.err.println("Error in file " + pieces[i]);
e.printStackTrace();
}
} else { // not a .jar or .zip, prolly a directory
File dir = new File(pieces[i]);
// but must be a dir, since it's one of several paths
// just need to check if it exists
if (dir.exists()) {
packClassPathIntoZipFileRecursive(dir, null, zos);
}
}
}
}
/**
* Continue the process of magical exporting. This function
* can be called recursively to walk through folders looking
* for more goodies that will be added to the ZipOutputStream.
*/
static public void packClassPathIntoZipFileRecursive(File dir,
String sofar,
ZipOutputStream zos)
throws IOException {
String files[] = dir.list();
for (int i = 0; i < files.length; i++) {
// ignore . .. and .DS_Store
if (files[i].charAt(0) == '.') continue;
File sub = new File(dir, files[i]);
String nowfar = (sofar == null) ?
files[i] : (sofar + "/" + files[i]);
if (sub.isDirectory()) {
packClassPathIntoZipFileRecursive(sub, nowfar, zos);
} else {
// don't add .jar and .zip files, since they only work
// inside the root, and they're unpacked
if (!files[i].toLowerCase().endsWith(".jar") &&
!files[i].toLowerCase().endsWith(".zip") &&
files[i].charAt(0) != '.') {
ZipEntry entry = new ZipEntry(nowfar);
zos.putNextEntry(entry);
zos.write(Base.grabFile(sub));
zos.closeEntry();
}
}
}
}
/**
* Make sure the sketch hasn't been moved or deleted by some
* nefarious user. If they did, try to re-create it and save.
* Only checks to see if the main folder is still around,
* but not its contents.
*/
protected void ensureExistence() {
if (folder.exists()) return;
Base.showWarning("Sketch Disappeared",
"The sketch folder has disappeared.\n " +
"Will attempt to re-save in the same location,\n" +
"but anything besides the code will be lost.", null);
try {
folder.mkdirs();
modified = true;
for (int i = 0; i < codeCount; i++) {
code[i].save(); // this will force a save
}
for (int i = 0; i < hiddenCount; i++) {
hidden[i].save(); // this will force a save
}
calcModified();
} catch (Exception e) {
Base.showWarning("Could not re-save sketch",
"Could not properly re-save the sketch. " +
"You may be in trouble at this point,\n" +
"and it might be time to copy and paste " +
"your code to another text editor.", e);
}
}
/**
* Returns true if this is a read-only sketch. Used for the
* examples directory, or when sketches are loaded from read-only
* volumes or folders without appropriate permissions.
*/
public boolean isReadOnly() {
String apath = folder.getAbsolutePath();
if (apath.startsWith(Sketchbook.examplesPath) ||
apath.startsWith(Sketchbook.librariesPath)) {
return true;
// canWrite() doesn't work on directories
//} else if (!folder.canWrite()) {
} else {
// check to see if each modified code file can be written to
for (int i = 0; i < codeCount; i++) {
if (code[i].modified &&
!code[i].file.canWrite() &&
code[i].file.exists()) {
//System.err.println("found a read-only file " + code[i].file);
return true;
}
}
//return true;
}
return false;
}
/**
* Returns path to the main .pde file for this sketch.
*/
public String getMainFilePath() {
return code[0].file.getAbsolutePath();
}
}
| false | true | public boolean exportApplication(int exportPlatform) throws Exception {
// make sure the user didn't hide the sketch folder
ensureExistence();
//int exportPlatform = PApplet.platform; //PConstants.MACOSX;
String exportPlatformStr = null;
if (exportPlatform == PConstants.WINDOWS) {
exportPlatformStr = "windows";
} else if (exportPlatform == PConstants.MACOSX) {
exportPlatformStr = "macosx";
} else if (exportPlatform == PConstants.LINUX) {
exportPlatformStr = "linux";
} else {
exportPlatform = -1;
}
String folderName = "application";
if (exportPlatform != -1) {
folderName += "." + exportPlatformStr;
}
// nuke the old folder because it can cause trouble
File destFolder = new File(folder, folderName);
Base.removeDir(destFolder);
destFolder.mkdirs();
// build the sketch
String foundName = build(destFolder.getPath(), name);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// if name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!name.equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + name + " but the sketch\n" +
"name in the code was " + foundName, null);
return false;
}
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, name + ".app");
String APP_SKELETON = "skeleton.app";
//File dotAppSkeleton = new File(folder, APP_SKELETON);
File dotAppSkeleton = new File("lib/export/" + APP_SKELETON);
Base.copyDir(dotAppSkeleton, dotAppFolder);
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (PApplet.platform == PConstants.WINDOWS) {
File warningFile = new File(destFolder, "readme.txt");
PrintStream ps = new PrintStream(new FileOutputStream(warningFile));
ps.println("This application was created on Windows, which doesn't");
ps.println("properly support setting files as \"executable\",");
ps.println("a necessity for applications on Mac OS X.");
ps.println();
ps.println("To fix this, use the Terminal on Mac OS X, and from this");
ps.println("directory, type the following:");
ps.println();
ps.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
ps.flush();
ps.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
// set the jar folder to a different location than windows/linux
jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
}
/// make the jar folder (windows and linux)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
Base.copyFile(new File("lib/export/application.exe"),
new File(destFolder, this.name + ".exe"));
}
/// start copying all jar files
Vector jarListVector = new Vector();
/// create the main .jar file
zipFileContents = new Hashtable();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, name + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
String classfiles[] = destFolder.list();
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
entry = new ZipEntry(classfiles[i]);
zos.putNextEntry(entry);
zos.write(Base.grabFile(new File(destFolder, classfiles[i])));
zos.closeEntry();
}
}
// add the data folder to the main jar file
if (dataFolder.exists()) {
String dataFiles[] = Base.listFiles(dataFolder, false);
int offset = folder.getAbsolutePath().length() + 1;
for (int i = 0; i < dataFiles.length; i++) {
if (PApplet.platform == PApplet.WINDOWS) {
dataFiles[i] = dataFiles[i].replace('\\', '/');
}
File dataFile = new File(dataFiles[i]);
if (dataFile.isDirectory()) continue;
// don't export hidden files
// skipping dot prefix removes all: . .. .DS_Store
if (dataFile.getName().charAt(0) == '.') continue;
entry = new ZipEntry(dataFiles[i].substring(offset));
zos.putNextEntry(entry);
zos.write(Base.grabFile(dataFile));
zos.closeEntry();
}
}
// add the contents of the code folder to the jar
// (will unpack all jar files in the code folder)
if (codeFolder.exists()) {
String includes = Compiler.contentsToClassPath(codeFolder);
packClassPathIntoZipFile(includes, zos);
}
zos.flush();
zos.close();
jarListVector.add(name + ".jar");
/// add core.jar to the jar destination folder
//System.out.println(jarFolder);
Base.copyFile(new File("lib/core.jar"), new File(jarFolder, "core.jar"));
jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
// if a file called 'export.txt' is in there, it contains
// a list of the files that should be exported.
// otherwise, all files are exported.
Enumeration en = importedLibraries.elements();
while (en.hasMoreElements()) {
File libraryFolder = (File)en.nextElement();
// in the list is a File object that points the
// library sketch's "library" folder
File exportSettings = new File(libraryFolder, "export.txt");
Hashtable exportTable = readSettings(exportSettings);
String commaList = null;
String exportList[] = null;
if (exportPlatform != -1) {
// first check to see if there's something like application.macosx
commaList = (String)
exportTable.get("application." + exportPlatformStr);
}
if (commaList == null) {
// next check to see if something for 'application' is specified
commaList = (String) exportTable.get("application");
}
if (commaList == null) {
// otherwise just dump the whole folder
exportList = libraryFolder.list();
}
// add each item from the library folder / export list to the output
for (int i = 0; i < exportList.length; i++) {
if (exportList[i].equals(".") ||
exportList[i].equals("..")) continue;
exportList[i] = PApplet.trim(exportList[i]);
if (exportList[i].equals("")) continue;
File exportFile = new File(libraryFolder, exportList[i]);
if (!exportFile.exists()) {
System.err.println("File " + exportList[i] + " does not exist");
} else if (exportFile.isDirectory()) {
System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
} else if (exportFile.getName().toLowerCase().endsWith(".zip") ||
exportFile.getName().toLowerCase().endsWith(".jar")) {
//packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos);
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
jarListVector.add(exportList[i]);
} else if ((exportPlatform == PConstants.MACOSX) &&
(exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// jnilib files can be placed in Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
} else {
// copy the file to the main directory.. prolly a .dll or something
Base.copyFile(exportFile,
new File(destFolder, exportFile.getName()));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("lib/" + jarList[i]);
}
}
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
String PLIST_TEMPLATE = "template.plist";
File plistTemplate = new File(folder, PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
plistTemplate = new File("lib/export/" + PLIST_TEMPLATE);
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintStream ps = new PrintStream(new FileOutputStream(plistFile));
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
name);
}
while ((index = sb.indexOf("@@classpath@@")) != -1) {
sb.replace(index, index + "@@classpath@@".length(),
exportClassPath.toString());
}
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
ps.print(lines[i] + "\n");
}
ps.flush();
ps.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintStream ps = new PrintStream(new FileOutputStream(argsFile));
ps.println(Preferences.get("run.options"));
ps.println(this.name);
ps.println(exportClassPath);
ps.flush();
ps.close();
} else {
File shellScript = new File(destFolder, this.name);
PrintStream ps = new PrintStream(new FileOutputStream(shellScript));
// do the newlines explicitly so that windows CRLF
// isn't used when exporting for unix
ps.print("#!/bin/sh\n\n");
ps.print("java " + Preferences.get("run.options") +
" -cp " + exportClassPath +
" " + this.name + "\n");
ps.flush();
ps.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (int i = 0; i < codeCount; i++) {
try {
Base.copyFile(code[i].file,
new File(sourceFolder, code[i].file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = this.name + ".java";
File preprocFile = new File(destFolder, preprocFilename);
if (preprocFile.exists()) {
preprocFile.renameTo(new File(sourceFolder, preprocFilename));
}
/// remove the .class files from the export folder.
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
File deadguy = new File(destFolder, classfiles[i]);
if (!deadguy.delete()) {
Base.showWarning("Could not delete",
classfiles[i] + " could not \n" +
"be deleted from the applet folder. \n" +
"You'll need to remove it by hand.", null);
}
}
}
/// goodbye
return true;
}
| public boolean exportApplication(int exportPlatform) throws Exception {
// make sure the user didn't hide the sketch folder
ensureExistence();
//int exportPlatform = PApplet.platform; //PConstants.MACOSX;
String exportPlatformStr = null;
if (exportPlatform == PConstants.WINDOWS) {
exportPlatformStr = "windows";
} else if (exportPlatform == PConstants.MACOSX) {
exportPlatformStr = "macosx";
} else if (exportPlatform == PConstants.LINUX) {
exportPlatformStr = "linux";
} else {
exportPlatform = -1;
}
String folderName = "application";
if (exportPlatform != -1) {
folderName += "." + exportPlatformStr;
}
// nuke the old folder because it can cause trouble
File destFolder = new File(folder, folderName);
Base.removeDir(destFolder);
destFolder.mkdirs();
// build the sketch
String foundName = build(destFolder.getPath(), name);
// (already reported) error during export, exit this function
if (foundName == null) return false;
// if name != exportSketchName, then that's weirdness
// BUG unfortunately, that can also be a bug in the preproc :(
if (!name.equals(foundName)) {
Base.showWarning("Error during export",
"Sketch name is " + name + " but the sketch\n" +
"name in the code was " + foundName, null);
return false;
}
/// figure out where the jar files will be placed
File jarFolder = new File(destFolder, "lib");
/// on macosx, need to copy .app skeleton since that's
/// also where the jar files will be placed
File dotAppFolder = null;
if (exportPlatform == PConstants.MACOSX) {
dotAppFolder = new File(destFolder, name + ".app");
String APP_SKELETON = "skeleton.app";
//File dotAppSkeleton = new File(folder, APP_SKELETON);
File dotAppSkeleton = new File("lib/export/" + APP_SKELETON);
Base.copyDir(dotAppSkeleton, dotAppFolder);
String stubName = "Contents/MacOS/JavaApplicationStub";
// need to set the stub to executable
// will work on osx or *nix, but just dies on windows, oh well..
if (PApplet.platform == PConstants.WINDOWS) {
File warningFile = new File(destFolder, "readme.txt");
PrintStream ps = new PrintStream(new FileOutputStream(warningFile));
ps.println("This application was created on Windows, which doesn't");
ps.println("properly support setting files as \"executable\",");
ps.println("a necessity for applications on Mac OS X.");
ps.println();
ps.println("To fix this, use the Terminal on Mac OS X, and from this");
ps.println("directory, type the following:");
ps.println();
ps.println("chmod +x " + dotAppFolder.getName() + "/" + stubName);
ps.flush();
ps.close();
} else {
File stubFile = new File(dotAppFolder, stubName);
String stubPath = stubFile.getAbsolutePath();
Runtime.getRuntime().exec(new String[] { "chmod", "+x", stubPath });
}
// set the jar folder to a different location than windows/linux
jarFolder = new File(dotAppFolder, "Contents/Resources/Java");
}
/// make the jar folder (windows and linux)
if (!jarFolder.exists()) jarFolder.mkdirs();
/// on windows, copy the exe file
if (exportPlatform == PConstants.WINDOWS) {
Base.copyFile(new File("lib/export/application.exe"),
new File(destFolder, this.name + ".exe"));
}
/// start copying all jar files
Vector jarListVector = new Vector();
/// create the main .jar file
zipFileContents = new Hashtable();
FileOutputStream zipOutputFile =
new FileOutputStream(new File(jarFolder, name + ".jar"));
ZipOutputStream zos = new ZipOutputStream(zipOutputFile);
ZipEntry entry;
// add the manifest file so that the .jar can be double clickable
addManifest(zos);
// add the project's .class files to the jar
// (just grabs everything from the build directory,
// since there may be some inner classes)
// TODO this needs to be recursive (for packages)
String classfiles[] = destFolder.list();
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
entry = new ZipEntry(classfiles[i]);
zos.putNextEntry(entry);
zos.write(Base.grabFile(new File(destFolder, classfiles[i])));
zos.closeEntry();
}
}
// add the data folder to the main jar file
if (dataFolder.exists()) {
String dataFiles[] = Base.listFiles(dataFolder, false);
int offset = folder.getAbsolutePath().length() + 1;
for (int i = 0; i < dataFiles.length; i++) {
if (PApplet.platform == PApplet.WINDOWS) {
dataFiles[i] = dataFiles[i].replace('\\', '/');
}
File dataFile = new File(dataFiles[i]);
if (dataFile.isDirectory()) continue;
// don't export hidden files
// skipping dot prefix removes all: . .. .DS_Store
if (dataFile.getName().charAt(0) == '.') continue;
entry = new ZipEntry(dataFiles[i].substring(offset));
zos.putNextEntry(entry);
zos.write(Base.grabFile(dataFile));
zos.closeEntry();
}
}
// add the contents of the code folder to the jar
// (will unpack all jar files in the code folder)
if (codeFolder.exists()) {
String includes = Compiler.contentsToClassPath(codeFolder);
packClassPathIntoZipFile(includes, zos);
}
zos.flush();
zos.close();
jarListVector.add(name + ".jar");
/// add core.jar to the jar destination folder
//System.out.println(jarFolder);
Base.copyFile(new File("lib/core.jar"), new File(jarFolder, "core.jar"));
jarListVector.add("core.jar");
/// add contents of 'library' folders to the export
// if a file called 'export.txt' is in there, it contains
// a list of the files that should be exported.
// otherwise, all files are exported.
Enumeration en = importedLibraries.elements();
while (en.hasMoreElements()) {
File libraryFolder = (File)en.nextElement();
// in the list is a File object that points the
// library sketch's "library" folder
File exportSettings = new File(libraryFolder, "export.txt");
Hashtable exportTable = readSettings(exportSettings);
String commaList = null;
String exportList[] = null;
if (exportPlatform != -1) {
// first check to see if there's something like application.macosx
commaList = (String)
exportTable.get("application." + exportPlatformStr);
}
if (commaList == null) {
// next check to see if something for 'application' is specified
commaList = (String) exportTable.get("application");
}
if (commaList == null) {
// otherwise just dump the whole folder
exportList = libraryFolder.list();
} else {
exportList = PApplet.split(commaList, ", ");
}
// add each item from the library folder / export list to the output
for (int i = 0; i < exportList.length; i++) {
if (exportList[i].equals(".") ||
exportList[i].equals("..")) continue;
exportList[i] = PApplet.trim(exportList[i]);
if (exportList[i].equals("")) continue;
File exportFile = new File(libraryFolder, exportList[i]);
if (!exportFile.exists()) {
System.err.println("File " + exportList[i] + " does not exist");
} else if (exportFile.isDirectory()) {
System.err.println("Ignoring sub-folder \"" + exportList[i] + "\"");
} else if (exportFile.getName().toLowerCase().endsWith(".zip") ||
exportFile.getName().toLowerCase().endsWith(".jar")) {
//packClassPathIntoZipFile(exportFile.getAbsolutePath(), zos);
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
jarListVector.add(exportList[i]);
} else if ((exportPlatform == PConstants.MACOSX) &&
(exportFile.getName().toLowerCase().endsWith(".jnilib"))) {
// jnilib files can be placed in Contents/Resources/Java
Base.copyFile(exportFile, new File(jarFolder, exportList[i]));
} else {
// copy the file to the main directory.. prolly a .dll or something
Base.copyFile(exportFile,
new File(destFolder, exportFile.getName()));
}
}
}
/// create platform-specific CLASSPATH based on included jars
String jarList[] = new String[jarListVector.size()];
jarListVector.copyInto(jarList);
StringBuffer exportClassPath = new StringBuffer();
if (exportPlatform == PConstants.MACOSX) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("$JAVAROOT/" + jarList[i]);
}
} else if (exportPlatform == PConstants.WINDOWS) {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(",");
exportClassPath.append(jarList[i]);
}
} else {
for (int i = 0; i < jarList.length; i++) {
if (i != 0) exportClassPath.append(":");
exportClassPath.append("lib/" + jarList[i]);
}
}
/// macosx: write out Info.plist (template for classpath, etc)
if (exportPlatform == PConstants.MACOSX) {
String PLIST_TEMPLATE = "template.plist";
File plistTemplate = new File(folder, PLIST_TEMPLATE);
if (!plistTemplate.exists()) {
plistTemplate = new File("lib/export/" + PLIST_TEMPLATE);
}
File plistFile = new File(dotAppFolder, "Contents/Info.plist");
PrintStream ps = new PrintStream(new FileOutputStream(plistFile));
String lines[] = PApplet.loadStrings(plistTemplate);
for (int i = 0; i < lines.length; i++) {
if (lines[i].indexOf("@@") != -1) {
StringBuffer sb = new StringBuffer(lines[i]);
int index = 0;
while ((index = sb.indexOf("@@sketch@@")) != -1) {
sb.replace(index, index + "@@sketch@@".length(),
name);
}
while ((index = sb.indexOf("@@classpath@@")) != -1) {
sb.replace(index, index + "@@classpath@@".length(),
exportClassPath.toString());
}
lines[i] = sb.toString();
}
// explicit newlines to avoid Windows CRLF
ps.print(lines[i] + "\n");
}
ps.flush();
ps.close();
} else if (exportPlatform == PConstants.WINDOWS) {
File argsFile = new File(destFolder + "/lib/args.txt");
PrintStream ps = new PrintStream(new FileOutputStream(argsFile));
ps.println(Preferences.get("run.options"));
ps.println(this.name);
ps.println(exportClassPath);
ps.flush();
ps.close();
} else {
File shellScript = new File(destFolder, this.name);
PrintStream ps = new PrintStream(new FileOutputStream(shellScript));
// do the newlines explicitly so that windows CRLF
// isn't used when exporting for unix
ps.print("#!/bin/sh\n\n");
ps.print("java " + Preferences.get("run.options") +
" -cp " + exportClassPath +
" " + this.name + "\n");
ps.flush();
ps.close();
String shellPath = shellScript.getAbsolutePath();
// will work on osx or *nix, but just dies on windows, oh well..
if (PApplet.platform != PConstants.WINDOWS) {
Runtime.getRuntime().exec(new String[] { "chmod", "+x", shellPath });
}
}
/// copy the source files to the target
/// (we like to encourage people to share their code)
File sourceFolder = new File(destFolder, "source");
sourceFolder.mkdirs();
for (int i = 0; i < codeCount; i++) {
try {
Base.copyFile(code[i].file,
new File(sourceFolder, code[i].file.getName()));
} catch (IOException e) {
e.printStackTrace();
}
}
// move the .java file from the preproc there too
String preprocFilename = this.name + ".java";
File preprocFile = new File(destFolder, preprocFilename);
if (preprocFile.exists()) {
preprocFile.renameTo(new File(sourceFolder, preprocFilename));
}
/// remove the .class files from the export folder.
for (int i = 0; i < classfiles.length; i++) {
if (classfiles[i].endsWith(".class")) {
File deadguy = new File(destFolder, classfiles[i]);
if (!deadguy.delete()) {
Base.showWarning("Could not delete",
classfiles[i] + " could not \n" +
"be deleted from the applet folder. \n" +
"You'll need to remove it by hand.", null);
}
}
}
/// goodbye
return true;
}
|
diff --git a/src/de/ueller/midlet/gps/Trace.java b/src/de/ueller/midlet/gps/Trace.java
index da1f451f..66fe6527 100644
--- a/src/de/ueller/midlet/gps/Trace.java
+++ b/src/de/ueller/midlet/gps/Trace.java
@@ -1,2175 +1,2175 @@
package de.ueller.midlet.gps;
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See Copying
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import de.ueller.gps.data.Configuration;
import de.ueller.gps.data.Position;
import de.ueller.gps.data.Satelit;
import de.ueller.gps.nmea.NmeaInput;
import de.ueller.gps.sirf.SirfInput;
import de.ueller.gps.tools.HelperRoutines;
import de.ueller.gps.tools.intTree;
import de.ueller.gpsMid.mapData.DictReader;
import de.ueller.gpsMid.mapData.QueueDataReader;
import de.ueller.gpsMid.mapData.QueueDictReader;
import de.ueller.gpsMid.mapData.Tile;
import de.ueller.midlet.gps.data.ProjFactory;
import de.ueller.midlet.gps.data.ProjMath;
import de.ueller.midlet.gps.data.Gpx;
import de.ueller.midlet.gps.data.IntPoint;
import de.ueller.midlet.gps.data.MoreMath;
import de.ueller.midlet.gps.data.Node;
import de.ueller.midlet.gps.data.PositionMark;
import de.ueller.midlet.gps.names.Names;
import de.ueller.midlet.gps.routing.ConnectionWithNode;
import de.ueller.midlet.gps.routing.RouteHelper;
import de.ueller.midlet.gps.routing.RouteNode;
import de.ueller.midlet.gps.routing.Routing;
import de.ueller.midlet.gps.tile.C;
import de.ueller.midlet.gps.GuiMapFeatures;
import de.ueller.midlet.gps.tile.Images;
import de.ueller.midlet.gps.tile.PaintContext;
import de.ueller.midlet.gps.GpsMidDisplayable;
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends Canvas implements CommandListener, LocationMsgReceiver,
Runnable , GpsMidDisplayable{
/** Soft button for exiting the map screen */
private final Command EXIT_CMD = new Command("Back", Command.BACK, 5);
private final Command REFRESH_CMD = new Command("Refresh", Command.ITEM, 4);
private final Command SEARCH_CMD = new Command("Search", Command.OK, 1);
private final Command CONNECT_GPS_CMD = new Command("Start gps",Command.ITEM, 2);
private final Command DISCONNECT_GPS_CMD = new Command("Stop gps",Command.ITEM, 2);
private final Command START_RECORD_CMD = new Command("Start record",Command.ITEM, 4);
private final Command STOP_RECORD_CMD = new Command("Stop record",Command.ITEM, 4);
private final Command MANAGE_TRACKS_CMD = new Command("Manage tracks",Command.ITEM, 5);
private final Command SAVE_WAYP_CMD = new Command("Save waypoint",Command.ITEM, 7);
private final Command ENTER_WAYP_CMD = new Command("Enter waypoint",Command.ITEM, 7);
private final Command MAN_WAYP_CMD = new Command("Manage waypoints",Command.ITEM, 7);
private final Command ROUTE_TO_CMD = new Command("Route",Command.ITEM, 3);
private final Command CAMERA_CMD = new Command("Camera",Command.ITEM, 9);
private final Command CLEARTARGET_CMD = new Command("Clear Target",Command.ITEM, 10);
private final Command SETTARGET_CMD = new Command("As Target",Command.ITEM, 11);
private final Command MAPFEATURES_CMD = new Command("Map Features",Command.ITEM, 12);
private final Command RECORDINGS_CMD = new Command("Recordings...",Command.ITEM, 4);
private final Command ROUTINGS_CMD = new Command("Routing...",Command.ITEM, 3);
private final Command OK_CMD = new Command("OK",Command.OK, 14);
private final Command BACK_CMD = new Command("Back",Command.BACK, 15);
private final Command ZOOM_IN_CMD = new Command("Zoom in",Command.ITEM, 100);
private final Command ZOOM_OUT_CMD = new Command("Zoom out",Command.ITEM, 100);
private final Command ROTATE_COUNTERCLOCKWISE_CMD = new Command("Rotate counterclockwise",Command.ITEM, 100);
private final Command ROTATE_CLOCKWISE_CMD = new Command("Rotate clockwise",Command.ITEM, 100);
private final Command TOGGLE_OVERLAY_CMD = new Command("Next overlay",Command.ITEM, 100);
private final Command TOGGLE_BACKLIGHT_CMD = new Command("Keep backlight on/off",Command.ITEM, 100);
private final Command TOGGLE_FULLSCREEN_CMD = new Command("Switch to fullscreen",Command.ITEM, 100);
private final Command TOGGLE_MAP_PROJ_CMD = new Command("Next map projection",Command.ITEM, 100);
private final Command TOGGLE_KEY_LOCK_CMD = new Command("(De)Activate Keylock",Command.ITEM, 100);
private final Command TOGGLE_RECORDING_CMD = new Command("(De)Activate recording",Command.ITEM, 100);
private final Command TOGGLE_RECORDING_SUSP_CMD = new Command("Suspend recording",Command.ITEM, 100);
private final Command RECENTER_GPS_CMD = new Command("Recenter on GPS",Command.ITEM, 100);
private final Command TACHO_CMD = new Command("Tacho",Command.ITEM, 100);
private final Command OVERVIEW_MAP_CMD = new Command("Overview/Filter Map",Command.ITEM, 200);
private InputStream btGpsInputStream;
private OutputStream btGpsOutputStream;
private StreamConnection conn;
// private SirfInput si;
private LocationMsgProducer locationProducer;
public String solution = "NoFix";
private boolean gpsRecenter = true;
private Position pos = new Position(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1,
new Date());
Node center = new Node(49.328010f, 11.352556f);
// Projection projection;
private final GpsMid parent;
private String lastMsg;
private String currentMsg;
private Calendar lastMsgTime = Calendar.getInstance();
private long collected = 0;
public PaintContext pc;
public float scale = 15000f;
int showAddons = 0;
private int fontHeight = 0;
private int compassRectHeight = 0;
private static long pressedKeyTime = 0;
private static int pressedKeyCode = 0;
private static volatile long releasedKeyCode = 0;
private static int ignoreKeyCode = 0;
private boolean rootCalc=false;
Tile t[] = new Tile[6];
PositionMark source;
// this is only for visual debugging of the routing engine
Vector routeNodes=new Vector();
private List recordingsMenu;
private List routingsMenu;
private intTree singleKeyPressCommand = new intTree();
private intTree doubleKeyPressCommand = new intTree();
private intTree longKeyPressCommand = new intTree();
private final static Logger logger = Logger.getInstance(Trace.class,Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
private Satelit[] sat;
private Image satelit;
/**
* Current speed from GPS in km/h.
*/
private int speed;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course=0;
private Names namesThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private Runtime runtime = Runtime.getRuntime();
private PositionMark target;
private Vector route=null;
private final Configuration config;
private boolean running=false;
private static final int CENTERPOS = Graphics.HCENTER|Graphics.VCENTER;
public Gpx gpx;
private AudioRecorder audioRec;
private static Trace traceInstance=null;
private Routing routeEngine;
private byte arrow;
private Image scaledPict = null;
private int iPassedRouteArrow=0;
private static Font routeFont;
private static int routeFontHeight;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
private static final String[] directions = { "mark",
"hard right", "right", "half right",
"straight on",
"half left", "left", "hard left", "Target reached"};
private static final String[] soundDirections = { "",
"HARD;RIGHT", "RIGHT", "HALF;RIGHT",
"STRAIGHTON",
"HALF;LEFT", "LEFT", "HARD;LEFT"};
private static final String[] compassDirections =
{ "N", "NNE", "NE", "NEE", "E", "SEE", "SE", "SSE",
"S", "SSW", "SW", "SWW", "W", "NWW", "NW", "NNW",
"N"};
private boolean keyboardLocked=false;
private boolean movedAwayFromTarget=true;
private long oldRecalculationTime;
private boolean atTarget=false;
private int sumWrongDirection=0;
private int oldAwayFromNextArrow=0;
private int oldRouteInstructionColor=0x00E6E6E6;
private boolean prepareInstructionSaid=false;
private boolean routeRecalculationRequired=false;
// private int routerecalculations=0;
public Vector locationUpdateListeners;
public Trace(GpsMid parent, Configuration config) throws Exception {
//#debug
logger.info("init Trace");
this.config = config;
this.parent = parent;
addCommand(EXIT_CMD);
addCommand(SEARCH_CMD);
addCommand(CONNECT_GPS_CMD);
addCommand(MANAGE_TRACKS_CMD);
addCommand(MAN_WAYP_CMD);
addCommand(MAPFEATURES_CMD);
addCommand(RECORDINGS_CMD);
addCommand(ROUTINGS_CMD);
addCommand(TACHO_CMD);
setCommandListener(this);
singleKeyPressCommand.put(KEY_NUM1, ZOOM_OUT_CMD);
singleKeyPressCommand.put(KEY_NUM3, ZOOM_IN_CMD);
singleKeyPressCommand.put(KEY_NUM5, RECENTER_GPS_CMD);
singleKeyPressCommand.put(KEY_NUM7, TOGGLE_OVERLAY_CMD);
singleKeyPressCommand.put(KEY_NUM9, ROTATE_COUNTERCLOCKWISE_CMD);
singleKeyPressCommand.put(KEY_NUM0, TOGGLE_FULLSCREEN_CMD);
singleKeyPressCommand.put(KEY_STAR, MAPFEATURES_CMD);
singleKeyPressCommand.put(KEY_POUND, TOGGLE_BACKLIGHT_CMD);
singleKeyPressCommand.put(Configuration.KEYCODE_CAMERA_COVER_OPEN, CAMERA_CMD);
singleKeyPressCommand.put(-8, ROUTE_TO_CMD);
doubleKeyPressCommand.put(KEY_NUM5, TOGGLE_MAP_PROJ_CMD);
doubleKeyPressCommand.put(KEY_NUM0, TOGGLE_RECORDING_SUSP_CMD);
doubleKeyPressCommand.put(KEY_STAR, OVERVIEW_MAP_CMD);
longKeyPressCommand.put(KEY_NUM5, SAVE_WAYP_CMD);
longKeyPressCommand.put(KEY_NUM9, TOGGLE_KEY_LOCK_CMD);
longKeyPressCommand.put(KEY_NUM0, TOGGLE_RECORDING_CMD);
longKeyPressCommand.put(KEY_STAR, MAN_WAYP_CMD);
longKeyPressCommand.put(KEY_POUND, MANAGE_TRACKS_CMD);
try {
satelit = Image.createImage("/satelit.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
startup();
} catch (Exception e) {
logger.fatal("Got an exception during startup: " + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
public static Trace getInstance() {
return traceInstance;
}
// start the LocationProvider in background
public void run() {
try {
if (running){
receiveMessage("GPS starter already running");
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null){
receiveMessage("Location provider already running");
return;
}
if (config.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE){
receiveMessage("No location provider");
return;
}
running=true;
receiveMessage("Connect to "+Configuration.LOCATIONPROVIDER[config.getLocationProvider()]);
// System.out.println(config.getBtUrl());
// System.out.println(config.getRender());
switch (config.getLocationProvider()){
case Configuration.LOCATIONPROVIDER_SIRF:
case Configuration.LOCATIONPROVIDER_NMEA:
//#debug debug
logger.debug("Connect to "+config.getBtUrl());
if (! openBtConnection(config.getBtUrl())){
running=false;
return;
}
receiveMessage("BT Connected");
}
if (config.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
parent.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CONNECT_GPS_CMD);
addCommand(DISCONNECT_GPS_CMD);
switch (config.getLocationProvider()){
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
/**
* Some phones throw exceptions if trying to access properties that don't
* exist, so we have to catch these and just ignore them.
*/
} catch (Exception e) {
/**
* See above
*/
}
if (jsr179Version != null && jsr179Version.length() > 0) {
Class jsr179Class = Class.forName("de.ueller.gps.jsr179.JSR179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
}
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception("Your phone does not support JSR179, please use a different location provider", cnfe);
running = false;
return;
}
//#else
// keep eclipse happy
if (true){
logger.error("JSR179 is not compiled in this version of GpsMid");
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = config.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (config.getGpsRawLoggerEnable() && (url != null)) {
try {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
javax.microedition.io.Connection logCon = Connector.open(url);
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists())
fileCon.create();
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Trying to perform raw logging of NMEA on anything else than filesystem is currently not supported");
}
} catch (IOException ioe) {
logger.exception("Couldn't open file for raw logging of Gps data",ioe);
} catch (SecurityException se) {
logger.error("Permission to write data for NMEA raw logging was denied");
}
}
//#endif
if (locationProducer == null) {
logger.error("Your phone does not seem to support this method of location input, please choose a different one");
running = false;
return;
}
locationProducer.init(btGpsInputStream, btGpsOutputStream, this);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+config.getLocationProvider() + " " + config.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal("Trace thread crashed as out of memory: " + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal("Trace thread crashed unexpectadly with error " + e.getMessage());
e.printStackTrace();
} finally {
running = false;
}
running = false;
}
public synchronized void pause(){
logger.debug("Pausing application");
if (imageCollector != null) {
imageCollector.suspend();
}
if (locationProducer != null){
locationProducer.close();
} else {
return;
}
while (locationProducer != null){
try {
wait(200);
} catch (InterruptedException e) {
}
}
}
public void resume(){
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this);
thread.start();
}
private boolean openBtConnection(String url){
if (btGpsInputStream != null){
return true;
}
if (url == null)
return false;
try {
conn = (StreamConnection) Connector.open(url);
btGpsInputStream = conn.openInputStream();
/**
* There is at least one, perhaps more BT gps receivers, that
* seem to kill the bluetooth connection if we don't send it
* something for some reason. Perhaps due to poor powermanagment?
* We don't have anything to send, so send an arbitrary 0.
*/
if (getConfig().getBtKeepAlive()) {
btGpsOutputStream = conn.openOutputStream();
}
} catch (SecurityException se) {
/**
* The application was not permitted to connect to bluetooth
*/
receiveMessage("Connectiong to BT not permitted");
return false;
} catch (IOException e) {
receiveMessage("err BT:"+e.getMessage());
return false;
}
return true;
}
private void closeBtConnection() {
if (btGpsInputStream != null){
try {
btGpsInputStream.close();
} catch (IOException e) {
}
btGpsInputStream=null;
}
if (btGpsOutputStream != null){
try {
btGpsOutputStream.close();
} catch (IOException e) {
}
btGpsOutputStream=null;
}
if (conn != null){
try {
conn.close();
} catch (IOException e) {
}
conn=null;
}
}
/**
* This function tries to reconnect to the bluetooth
* it retries for up to 40 seconds and blocks in the
* mean time, so this function has to be called from
* within a separate thread. If successful, it will
* reinitialise the location producer with the new
* streams.
*
* @return whether the reconnect was successful
*/
public boolean autoReconnectBtConnection() {
if (!getConfig().getBtAutoRecon()) {
logger.info("Not trying to reconnect");
return false;
}
if (config.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
parent.mNoiseMaker.playSound("DISCONNECT");
}
/**
* If there are still parts of the old connection
* left over, close these cleanly.
*/
closeBtConnection();
int reconnectFailures = 0;
while ((reconnectFailures < 4) && (! openBtConnection(config.getBtUrl()))){
reconnectFailures++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
return false;
}
}
if (reconnectFailures < 4) {
if (locationProducer != null) {
if (config.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
parent.mNoiseMaker.playSound("CONNECT");
}
locationProducer.init(btGpsInputStream, btGpsOutputStream, this);
return true;
}
}
return false;
}
public void commandAction(Command c, Displayable d) {
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if (c == EXIT_CMD) {
// FIXME: This is a workaround. It would be better if recording would not be stopped when returning to map
if (gpx.isRecordingTrk()) {
parent.alert("Record Mode", "Please stop recording before returning to the main screen." , 2000);
return;
}
if (locationProducer != null){
locationProducer.close();
}
// shutdown();
pause();
parent.show();
return;
}
if (! rootCalc){
if (c == START_RECORD_CMD){
try {
gpx.newTrk();
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
}
if (c == STOP_RECORD_CMD){
gpx.saveTrk();
addCommand(MANAGE_TRACKS_CMD);
}
if (c == MANAGE_TRACKS_CMD){
if (gpx.isRecordingTrk()) {
parent.alert("Record Mode", "You need to stop recording before managing tracks." , 2000);
return;
}
GuiGpx gpx = new GuiGpx(this);
gpx.show();
}
if (c == REFRESH_CMD) {
repaint(0, 0, getWidth(), getHeight());
}
if (c == CONNECT_GPS_CMD){
if (locationProducer == null){
Thread thread = new Thread(this);
thread.start();
}
}
if (c == SEARCH_CMD){
GuiSearch search = new GuiSearch(this);
search.show();
}
if (c == DISCONNECT_GPS_CMD){
if (locationProducer != null){
locationProducer.close();
}
}
if (c == ROUTE_TO_CMD){
if (config.isStopAllWhileRouteing()){
stopImageCollector();
}
logger.info("Routing source: " + source);
// route recalculation is required until route calculation successful
routeRecalculationRequired=true;
routeNodes=new Vector();
routeEngine = new Routing(t,this);
routeEngine.solve(source, pc.target);
// resume();
}
if (c == SAVE_WAYP_CMD) {
GuiWaypointSave gwps = new GuiWaypointSave(this, new PositionMark(center.radlat, center.radlon));
gwps.show();
}
if (c == ENTER_WAYP_CMD) {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
if (c == MAN_WAYP_CMD) {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
if (c == MAPFEATURES_CMD) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint(0, 0, getWidth(), getHeight());
}
if (c == OVERVIEW_MAP_CMD) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint(0, 0, getWidth(), getHeight());
}
if (c == RECORDINGS_CMD) {
int noElements = 3;
//#if polish.api.mmapi
noElements = 5;
//#endif
String[] elements = new String[noElements];
if (gpx.isRecordingTrk()) {
elements[0] = "Stop Gpx tracklog";
} else {
elements[0] = "Start Gpx tracklog";
}
elements[1] = "Add waypoint";
elements[2] = "Enter waypoint";
//#if polish.api.mmapi
elements[3] = "Take pictures";
if (audioRec.isRecording()) {
elements[4] = "Stop audio recording";
} else {
elements[4] = "Start audio recording";
}
//#endif
recordingsMenu = new List("Recordings..",Choice.IMPLICIT,elements,null);
recordingsMenu.addCommand(OK_CMD);
recordingsMenu.addCommand(BACK_CMD);
recordingsMenu.setSelectCommand(OK_CMD);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (c == ROUTINGS_CMD) {
String[] elements = {"Calculate route", "Set target" , "Clear target"};
routingsMenu = new List("Routing..",Choice.IMPLICIT,elements,null);
routingsMenu.addCommand(OK_CMD);
routingsMenu.addCommand(BACK_CMD);
routingsMenu.setSelectCommand(OK_CMD);
parent.show(routingsMenu);
routingsMenu.setCommandListener(this);
}
if (c == BACK_CMD) {
show();
}
if (c == OK_CMD) {
if (d == recordingsMenu) {
switch (recordingsMenu.getSelectedIndex()) {
case 0: {
if (!gpx.isRecordingTrk()){
gpx.newTrk();
} else {
gpx.saveTrk();
}
show();
break;
}
case 1: {
commandAction(SAVE_WAYP_CMD, null);
break;
}
case 2: {
commandAction(ENTER_WAYP_CMD, null);
break;
}
//#if polish.api.mmapi
case 3: {
commandAction(CAMERA_CMD, null);
break;
}
case 4: {
show();
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
break;
}
//#endif
}
}
if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
commandAction(ROUTE_TO_CMD, null);
break;
}
case 1: {
commandAction(SETTARGET_CMD, null);
break;
}
case 2: {
commandAction(CLEARTARGET_CMD, null);
break;
}
}
}
}
//#if polish.api.mmapi
if (c == CAMERA_CMD){
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this, getConfig());
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception("Your phone does not support the necessary JSRs to use the camera", cnfe);
}
}
//#endif
if (c == CLEARTARGET_CMD) {
setTarget(null);
} else if (c == SETTARGET_CMD) {
if (source != null) {
setTarget(source);
}
} else if (c == ZOOM_IN_CMD) {
scale = scale / 1.5f;
} else if (c == ZOOM_OUT_CMD) {
scale = scale * 1.5f;
} else if (c == ROTATE_COUNTERCLOCKWISE_CMD) {
course += 5;
} else if (c == ROTATE_CLOCKWISE_CMD) {
course -= 5;
} else if (c == TOGGLE_OVERLAY_CMD) {
showAddons++;
} else if (c == TOGGLE_BACKLIGHT_CMD) {
// toggle Backlight
config.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(config.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
if ( config.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, false) ) {
parent.alert("Backlight", "Backlight ON" , 750);
} else {
parent.alert("Backlight", "Backlight off" , 750);
}
parent.stopBackLightTimer();
parent.startBackLightTimer();
} else if (c == TOGGLE_FULLSCREEN_CMD) {
boolean fullScreen = !config.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
config.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
} else if (c == TOGGLE_MAP_PROJ_CMD) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP ) {
ProjFactory.setProj(ProjFactory.MOVE_UP);
parent.alert("Map Rotation", "Rotate to Driving Direction" , 500);
} else {
ProjFactory.setProj(ProjFactory.NORTH_UP);
parent.alert("Map Rotation", "NORTH UP" , 500);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
} else if (c == TOGGLE_KEY_LOCK_CMD) {
keyboardLocked=!keyboardLocked;
if(keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
parent.alert("GpsMid", "Keys unlocked",750);
}
} else if (c == TOGGLE_RECORDING_CMD) {
if ( gpx.isRecordingTrk() ) {
parent.alert("Gps track recording", "Stopping to record" , 750);
commandAction(STOP_RECORD_CMD,(Displayable) null);
} else {
parent.alert("Gps track recording", "Starting to record" , 750);
commandAction(START_RECORD_CMD,(Displayable) null);
}
} else if (c == TOGGLE_RECORDING_SUSP_CMD) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
parent.alert("Gps track recording", "Resuming recording" , 750);
gpx.resumTrk();
} else {
parent.alert("Gps track recording", "Suspending recording" , 750);
gpx.suspendTrk();
}
}
} else if (c == RECENTER_GPS_CMD) {
gpsRecenter = true;
} else if (c == TACHO_CMD) {
GuiTacho tacho = new GuiTacho(this);
tacho.show();
}
} else {
logger.error(" currently in route Caclulation");
}
} catch (RuntimeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void startImageCollector() throws Exception {
Images i;
i = new Images();
pc = new PaintContext(this, i);
pc.c = new C();
imageCollector = new ImageCollector(t, this.getWidth(), this.getHeight(), this,
i, pc.c);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.clone();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
new DictReader(this);
// Thread thread = new Thread(this);
// thread.start();
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
}
public void shutdown() {
try {
stopImageCollector();
if (btGpsInputStream != null) {
btGpsInputStream.close();
btGpsInputStream = null;
}
if (namesThread != null) {
namesThread.stop();
namesThread = null;
}
if (dictReader != null) {
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
tileReader.shutdown();
tileReader = null;
}
} catch (IOException e) {
}
if (locationProducer != null){
locationProducer.close();
}
}
protected void sizeChanged(int w, int h) {
if (imageCollector != null){
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception("Could not reinitialise Image Collector after size change", e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(C.BACKGROUND_COLOR);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null){
imageCollector.paint(pc);
}
switch (showAddons) {
case 1:
showScale(pc);
break;
case 2:
yc = showSpeed(g, yc, la);
yc = showDistanceToTarget(g, yc, la);
break;
case 3:
showSatelite(g);
break;
case 4:
yc = showConnectStatistics(g, yc, la);
break;
case 5:
yc = showMemory(g, yc, la);
break;
default:
showAddons = 0;
if (ProjFactory.getProj() == ProjFactory.MOVE_UP
&& config.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)
) {
showPointOfTheCompass(pc);
}
}
showMovement(g);
g.setColor(0, 0, 0);
if (locationProducer != null){
if (gpx.isRecordingTrk()) {// we are recording tracklogs
if(fontHeight==0) {
fontHeight=g.getFont().getHeight();
}
if (gpx.isRecordingTrkSuspended()) {
g.setColor(0, 0, 255);
} else {
g.setColor(255, 0, 0);
}
g.drawString(gpx.recorded+"r", getWidth() - 1, 1+fontHeight, Graphics.TOP
| Graphics.RIGHT);
g.setColor(0);
}
g.drawString(solution, getWidth() - 1, 1, Graphics.TOP
| Graphics.RIGHT);
} else {
g.drawString("Off", getWidth() - 1, 1, Graphics.TOP
| Graphics.RIGHT);
}
if (pc != null){
showTarget(pc);
}
if (currentMsg != null) {
if (compassRectHeight == 0) {
compassRectHeight = g.getFont().getHeight()-2;
}
g.setColor(255,255,255);
g.fillRect(0,0, getWidth(), compassRectHeight + 2);
g.setColor(0,0,0);
if (g.getFont().stringWidth(currentMsg) < getWidth()) {
g.drawString(currentMsg,
getWidth()/2, 0, Graphics.TOP|Graphics.HCENTER);
} else {
g.drawString(currentMsg,
0, 0, Graphics.TOP|Graphics.LEFT);
}
if (System.currentTimeMillis()
> (lastMsgTime.getTime().getTime() + 5000)) {
logger.info("Setting title back to null");
lastMsg = currentMsg;
currentMsg = null;
}
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
/**
*
*/
private void getPC() {
pc.course=course;
pc.scale=scale;
pc.center=center.clone();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.target=target;
}
public void cleanup() {
namesThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
public void searchElement(PositionMark pm) throws Exception{
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
pc.searchLD=nld;
pc.searchRU=nru;
pc.target=pm;
for (int i=0; i<4; i++){
t[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// t[i].walk(nld,nru, Tile.OPT_WAIT_FOR_LOAD);
}
}
private void showPointOfTheCompass(PaintContext pc) {
if (compassRectHeight == 0) {
compassRectHeight = pc.g.getFont().getHeight()-2;
}
String c = compassDirections[(int) ((float) ((course%360 + 11.25f) / 22.5f)) ];
int compassRectWidth = pc.g.getFont().stringWidth(c);
pc.g.setColor(255, 255, 150);
pc.g.fillRect(getWidth()/2 - compassRectWidth / 2 , 0,
compassRectWidth, compassRectHeight);
pc.g.setColor(0, 0, 0);
pc.g.drawString( compassDirections[(int) ((float) ((course%360 + 11.25f) / 22.5f)) ], getWidth()/2, 0 , Graphics.HCENTER | Graphics.TOP);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
g.setColor(0, 0, 0);
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
private void showSatelite(Graphics g) {
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int dia = Math.min(getWidth(), getHeight()) - 6;
int r = dia / 2;
g.setColor(255, 50, 50);
g.drawArc(centerX - r, centerY - r, dia, dia, 0, 360);
if (sat == null) return;
for (byte i = 0; i < sat.length; i++) {
Satelit s = sat[i];
if (s == null)
continue; //This array may be sparsely filled.
if (s.id != 0) {
double el = s.elev / 180d * Math.PI;
double az = s.azimut / 180 * Math.PI;
double sr = r * Math.cos(el);
if (s.isLocked())
g.setColor(0, 255, 0);
else
g.setColor(255, 0, 0);
int px = centerX + (int) (Math.sin(az) * sr);
int py = centerY - (int) (Math.cos(az) * sr);
// g.drawString(""+s.id, px, py,
// Graphics.BASELINE|Graphics.HCENTER);
g.drawImage(satelit, px, py, Graphics.HCENTER
| Graphics.VCENTER);
py += 9;
// draw a bar under image that indicates green/red status and
// signal strength
g.fillRect(px - 9, py, (int)(s.snr*18.0/100.0), 2);
}
}
// g.drawImage(satelit, 5, 5, 0);
}
public void showTarget(PaintContext pc){
if (target != null){
pc.getP().forward(target.lat, target.lon, pc.lineP2);
// System.out.println(target.toString());
pc.g.drawImage(pc.images.IMG_TARGET,pc.lineP2.x,pc.lineP2.y,CENTERPOS);
pc.g.setColor(0,0,0);
if (target.displayName != null)
pc.g.drawString(target.displayName, pc.lineP2.x, pc.lineP2.y+8,
Graphics.TOP | Graphics.HCENTER);
pc.g.setColor(255,50,50);
pc.g.setStrokeStyle(Graphics.DOTTED);
pc.g.drawLine(pc.lineP2.x,pc.lineP2.y,pc.xSize/2,pc.ySize/2);
float distance = ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon);
atTarget = (distance < 25);
if (atTarget) {
if (movedAwayFromTarget && config.getCfgBitState(Configuration.CFGBIT_SND_TARGETREACHED)) {
parent.mNoiseMaker.playSound("TARGET_REACHED", (byte) 7, (byte) 1);
}
} else if (!movedAwayFromTarget) {
movedAwayFromTarget=true;
// wait with possible route recalculation until we've got a new source
// as current source might still contain an old position
source = null;
}
if (route != null)
showRoute(pc);
}
}
/**
* Draws a map scale onto screen.
* This calculation is currently horribly
* inefficient. There must be a better way
* than this.
*
* @param pc
*/
public void showScale(PaintContext pc) {
Node n1 = new Node();
Node n2 = new Node();
float scale;
int scalePx;
//Calculate the lat and lon coordinates of two
//points that are 35 pixels apart
pc.getP().inverse(10, 10, n1);
pc.getP().inverse(45, 10, n2);
//Calculate the distance between them in meters
float d = ProjMath.getDistance(n1, n2);
//round this distance up to the nearest 5 or 10
int ordMag = (int)(MoreMath.log(d)/MoreMath.log(10.0f));
if (d < 2.5*MoreMath.pow(10,ordMag)) {
scale = 2.5f*MoreMath.pow(10,ordMag);
} else if (d < 5*MoreMath.pow(10,ordMag)) {
scale = 5*MoreMath.pow(10,ordMag);
} else {
scale = 10*MoreMath.pow(10,ordMag);
}
//Calculate how many pixels this distance is apart
scalePx = (int)(35.0f*scale/d);
//Draw the scale bar
pc.g.setColor(0x00000000);
pc.g.drawLine(10,10, 10 + scalePx, 10);
pc.g.drawLine(10,11, 10 + scalePx, 11); //double line width
pc.g.drawLine(10, 8, 10, 13);
pc.g.drawLine(10 + scalePx, 8, 10 + scalePx, 13);
if (scale > 1000) {
pc.g.drawString(Integer.toString((int)(scale/1000.0f)) + "km", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP);
} else {
pc.g.drawString(Integer.toString((int)scale) + "m", 10 + scalePx/2 ,12, Graphics.HCENTER | Graphics.TOP);
}
}
/**
* @param pc
*/
private void showRoute(PaintContext pc) {
/* PASSINGDISTANCE is the distance when a routing arrow
is considered to match to the current position.
We currently can't adjust this value according to the speed
because if we would be slowing down during approaching the arrow,
then PASSINGDISTANCE could become smaller than the distance
to the arrow due and thus the routines would already use the
next arrow for routing assistance
*/
final int PASSINGDISTANCE=25;
StringBuffer soundToPlay = new StringBuffer();
String routeInstruction = null;
// backgound colour for standard routing instructions
int routeInstructionColor=0x00E6E6E6;
int diffArrowDist=0;
byte soundRepeatDelay=3;
byte soundRepeatTimes=2;
float nearestLat=0.0f;
float nearestLon=0.0f;
// this makes the distance when prepare-sound is played depending on the speed
int PREPAREDISTANCE=100;
if (speed>100) {
PREPAREDISTANCE=500;
} else if (speed>80) {
PREPAREDISTANCE=300;
} else if (speed>55) {
PREPAREDISTANCE=200;
} else if (speed>45) {
PREPAREDISTANCE=150;
} else if (speed>35) {
PREPAREDISTANCE=125;
}
ConnectionWithNode c;
// Show helper nodes for Routing
for (int x=0; x<routeNodes.size();x++){
RouteHelper n=(RouteHelper) routeNodes.elementAt(x);
pc.getP().forward(n.node.radlat, n.node.radlon, pc.lineP2);
pc.g.drawRect(pc.lineP2.x-5, pc.lineP2.y-5, 10, 10);
pc.g.drawString(n.name, pc.lineP2.x+7, pc.lineP2.y+5, Graphics.BOTTOM | Graphics.LEFT);
}
synchronized(this) {
if (route != null && route.size() > 0){
// there's a route so no calculation required
routeRecalculationRequired = false;
RouteNode lastTo;
// find nearest routing arrow (to center of screen)
int iNearest=0;
if (config.getCfgBitState(Configuration.CFGBIT_ROUTING_HELP)) {
c = (ConnectionWithNode) route.elementAt(0);
lastTo=c.to;
float minimumDistance=99999;
float distance=99999;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c!=null && c.to!=null && lastTo!=null) {
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
continue;
}
distance = ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
if (distance<minimumDistance) {
minimumDistance=distance;
iNearest=i;
}
lastTo=c.to;
}
}
//System.out.println("iNearest "+ iNearest + "dist: " + minimumDistance);
// if nearest route arrow is closer than PASSINGDISTANCE meters we're currently passing this route arrow
if (minimumDistance<PASSINGDISTANCE) {
if (iPassedRouteArrow != iNearest) {
iPassedRouteArrow = iNearest;
// if there's i.e. a 2nd left arrow in row "left" must be repeated
parent.mNoiseMaker.resetSoundRepeatTimes();
}
// after passing an arrow saying "in xxx metres" is allowed again
prepareInstructionSaid = false;
//System.out.println("iPassedRouteArrow "+ iPassedRouteArrow);
} else {
c = (ConnectionWithNode) route.elementAt(iPassedRouteArrow);
// if we got away more than PASSINGDISTANCE m of the previously passed routing arrow
if (ProjMath.getDistance(center.radlat, center.radlon, c.to.lat, c.to.lon) >= PASSINGDISTANCE) {
// assume we should start to emphasize the next routing arrow now
iNearest=iPassedRouteArrow+1;
}
}
}
c = (ConnectionWithNode) route.elementAt(0);
- byte lastEndBearing=c.endBearing;
+ int lastEndBearing=c.endBearing;
lastTo=c.to;
byte a=0;
byte aNearest=0;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c == null){
logger.error("show Route got null connection");
break;
}
if (c.to == null){
logger.error("show Route got connection with NULL as target");
break;
}
if (lastTo == null){
logger.error("show Route strange lastTo is null");
break;
}
if (pc == null){
logger.error("show Route strange pc is null");
break;
}
// if (pc.screenLD == null){
// System.out.println("show Route strange pc.screenLD is null");
// }
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
// draw small circle for left out connection
pc.g.setColor(0x00FDDF9F);
pc.getP().forward(c.to.lat, c.to.lon, pc.lineP2);
final byte radius=6;
pc.g.fillArc(pc.lineP2.x-radius/2,pc.lineP2.y-radius/2,radius,radius,0,359);
//System.out.println("Skipped routing arrow " + i);
// if this would have been our iNearest, use next one as iNearest
if(i==iNearest) iNearest++;
continue;
}
if(i!=iNearest) {
if (lastTo.lat < pc.getP().getMinLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon < pc.getP().getMinLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lat > pc.getP().getMaxLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon > pc.getP().getMaxLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
}
Image pict = pc.images.IMG_MARK; a=0;
// make bearing relative to current course for the first route arrow
if (i==1) {
- lastEndBearing = (byte) (course%360 / 2);
+ lastEndBearing = (course%360) / 2;
}
int turn=(c.startBearing-lastEndBearing) * 2;
if (turn > 180) turn -= 360;
if (turn < -180) turn += 360;
// System.out.println("from: " + lastEndBearing*2 + " to:" +c.startBearing*2+ " turn " + turn);
if (turn > 110) {
pict=pc.images.IMG_HARDRIGHT; a=1;
} else if (turn > 70){
pict=pc.images.IMG_RIGHT; a=2;
} else if (turn > 20){
pict=pc.images.IMG_HALFRIGHT; a=3;
} else if (turn >= -20){
pict=pc.images.IMG_STRAIGHTON; a=4;
} else if (turn >= -70){
pict=pc.images.IMG_HALFLEFT; a=5;
} else if (turn >= -110){
pict=pc.images.IMG_LEFT; a=6;
} else {
pict=pc.images.IMG_HARDLEFT; a=7;
}
if (atTarget) {
a=8;
}
pc.getP().forward(lastTo.lat, lastTo.lon, pc.lineP2);
// optionally scale nearest arrow
if (i==iNearest) {
nearestLat=lastTo.lat;
nearestLon=lastTo.lon;
aNearest=a;
double distance=ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
int intDistance=new Double(distance).intValue();
routeInstruction=directions[a] + ((intDistance<PASSINGDISTANCE)?"":" in " + intDistance + "m");
if(intDistance<PASSINGDISTANCE) {
if (!atTarget) {
soundToPlay.append (soundDirections[a]);
}
soundRepeatTimes=1;
sumWrongDirection = -1;
diffArrowDist = 0;
oldRouteInstructionColor=0x00E6E6E6;
} else if (sumWrongDirection == -1) {
oldAwayFromNextArrow = intDistance;
sumWrongDirection=0;
diffArrowDist = 0;
} else {
diffArrowDist = (intDistance - oldAwayFromNextArrow);
}
if ( diffArrowDist == 0 ) {
routeInstructionColor=oldRouteInstructionColor;
} else if (intDistance < PASSINGDISTANCE) {
// background colour if currently passing
routeInstructionColor=0x00E6E6E6;
} else if ( diffArrowDist > 0) {
// background colour if distance to next arrow has just increased
routeInstructionColor=0x00FFCD9B;
} else {
// background colour if distance to next arrow has just decreased
routeInstructionColor=0x00B7FBBA;
}
sumWrongDirection += diffArrowDist;
//System.out.println("Sum wrong direction: " + sumWrongDirection);
oldAwayFromNextArrow = intDistance;
if (intDistance>=PASSINGDISTANCE) {
if (intDistance <= PREPAREDISTANCE) {
soundToPlay.append( (a==4 ? "CONTINUE" : "PREPARE") + ";" + soundDirections[a]);
soundRepeatDelay=5;
// Because of adaptive-to-speed distances for "prepare"-instructions
// GpsMid could fall back from "prepare"-instructions to "in xxx metres" voice instructions
// Remembering and checking if the prepare instruction already was given since the latest passing of an arrow avoids this
prepareInstructionSaid = true;
} else if (intDistance < 900 && !prepareInstructionSaid) {
soundRepeatDelay=60;
soundToPlay.append("IN;" + Integer.toString(intDistance / 100)+ "00;METERS;" + soundDirections[a]);
}
}
if (a!=arrow) {
arrow=a;
scaledPict=doubleImage(pict);
}
pict=scaledPict;
}
if (i == iNearest + 1) {
double distance=ProjMath.getDistance(nearestLat, nearestLon, lastTo.lat, lastTo.lon);
// if there is a close direction arrow after the current one
// inform the user about its direction
if (distance <= PREPAREDISTANCE &&
// only if not both arrows are STRAIGHT_ON
!(a==4 && aNearest == 4) &&
// and only as continuation of instruction
soundToPlay.length()!=0
) {
soundToPlay.append(";THEN;");
if (distance > PASSINGDISTANCE) {
soundToPlay.append("SOON;");
}
soundToPlay.append(soundDirections[a]);
// same arrow as currently nearest arrow?
if (a==aNearest) {
soundToPlay.append(";AGAIN");
}
//System.out.println(soundToPlay.toString());
}
}
// if the sum of movement away from the next arrow
// is much too high then recalculate route
if ( sumWrongDirection >= PREPAREDISTANCE * 2 / 3
|| sumWrongDirection >= 300) {
routeRecalculationRequired = true;
// if the sum of movement away from the next arrow is high
} else if ( sumWrongDirection >= PREPAREDISTANCE / 3
|| sumWrongDirection >= 150) {
// if distance to next arrow is high
// and moving away from next arrow
// ask user to check direction
if (diffArrowDist > 0) {
soundToPlay.setLength(0);
soundToPlay.append ("CHECK_DIRECTION");
soundRepeatDelay=5;
routeInstructionColor=0x00E6A03C;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
pc.g.drawImage(pict,pc.lineP2.x,pc.lineP2.y,CENTERPOS);
/*
Font originalFont = pc.g.getFont();
if (smallBoldFont==null) {
smallBoldFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
smallBoldFontHeight=smallBoldFont.getHeight();
}
pc.g.setFont(smallBoldFont);
pc.g.setColor(0,0,0);
int turnOrg=(c.startBearing - lastEndBearing)*2;
- pc.g.drawString("S: " + c.startBearing*2 + " E: " + lastEndBearing*2 + " T: " + turn + "(" + turnOrg + ")",
+ pc.g.drawString("S: " + c.startBearing*2 + " E: " + lastEndBearing*2 + " C: " + course + " T: " + turn + "(" + turnOrg + ")",
pc.lineP2.x,
pc.lineP2.y-smallBoldFontHeight / 2,
Graphics.HCENTER | Graphics.TOP
);
pc.g.setFont(originalFont);
*/
lastEndBearing=c.endBearing;
lastTo=c.to;
}
}
/* if we just moved away from target,
* and the map is gpscentered
* and there's only one or no route arrow
* ==> auto recalculation
*/
if (movedAwayFromTarget
&& gpsRecenter
&& (route != null && route.size()==2)
&& ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon) > PREPAREDISTANCE
) {
routeRecalculationRequired=true;
}
if ( routeRecalculationRequired && !atTarget ) {
long recalculationTime=System.currentTimeMillis();
if ( source != null
&& gpsRecenter
&& config.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC)
// do not recalculate route more often than every 7 seconds
&& Math.abs(recalculationTime-oldRecalculationTime) >= 7000
) {
// if map is gps-centered recalculate route
soundToPlay.setLength(0);
if (config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound("ROUTE_RECALCULATION", (byte) 5, (byte) 1 );
}
commandAction(ROUTE_TO_CMD,(Displayable) null);
// set source to null to not recalculate
// route again before map was drawn
source=null;
oldRecalculationTime = recalculationTime;
// routerecalculations++;
}
if (diffArrowDist > 0) {
// use red background color if moving away
routeInstructionColor=0x00FF5402;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
}
// Route instruction text output
if ((routeInstruction != null) && (imageCollector != null)) {
Font originalFont = pc.g.getFont();
if (routeFont==null) {
routeFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
routeFontHeight=routeFont.getHeight();
}
pc.g.setFont(routeFont);
pc.g.setColor(routeInstructionColor);
oldRouteInstructionColor=routeInstructionColor;
pc.g.fillRect(0,pc.ySize-imageCollector.statusFontHeight-routeFontHeight, pc.xSize, routeFontHeight);
pc.g.setColor(0,0,0);
// pc.g.drawString(""+routerecalculations,
// 0,
// pc.ySize-imageCollector.statusFontHeight,
// Graphics.LEFT | Graphics.BOTTOM
// );
pc.g.drawString(routeInstruction,
pc.xSize/2,
pc.ySize-imageCollector.statusFontHeight,
Graphics.HCENTER | Graphics.BOTTOM
);
pc.g.setFont(originalFont);
}
// Route instruction sound output
if (soundToPlay.length()!=0 && config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound(soundToPlay.toString(), (byte) soundRepeatDelay, (byte) soundRepeatTimes);
}
}
public static Image doubleImage(Image original)
{
int w=original.getWidth();
int h=original.getHeight();
int[] rawInput = new int[w * h];
original.getRGB(rawInput, 0, w, 0, 0, h, h);
int[] rawOutput = new int[w*h*4];
int outOffset= 1;
int inOffset= 0;
int lineInOffset=0;
int val=0;
for (int y=0;y<h*2;y++) {
if((y&1)==1) {
outOffset++;
inOffset=lineInOffset;
} else {
outOffset--;
lineInOffset=inOffset;
}
for (int x=0; x<w; x++) {
/* unfortunately many devices can draw semitransparent
pictures but only support transparent and opaque
in their graphics routines. So we just keep full transparency
as otherwise the device will convert semitransparent from the png
to full transparent pixels making the new picture much too bright
*/
val=rawInput[inOffset];
if( (val & 0xFF000000) != 0 ) {
val|=0xFF000000;
}
rawOutput[outOffset]=val;
/// as a workaround for semitransparency we only draw every 2nd pixel
outOffset+=2;
inOffset++;
}
}
return Image.createRGBImage(rawOutput, w*2, h*2, true);
}
public void showMovement(Graphics g) {
g.setColor(0, 0, 0);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0,0);
pc.getP().forward((float)(pos.latitude/360.0*2*Math.PI), (float)(pos.longitude/360.0*2*Math.PI),p1);
posX = p1.getX();
posY = p1.getY();
} else {
posX = centerX;
posY = centerY;
}
float radc = (float) (course * Math.PI / 180d);
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
g.drawRect(posX - 2, posY - 2, 4, 4);
g.drawLine(posX, posY, px, py);
g.drawLine(centerX-2, centerY - 2, centerX + 2, centerY + 2);
g.drawLine(centerX-2, centerY + 2, centerX + 2, centerY - 2);
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0, 0, 0);
g.drawString("Freemem: " + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("Totmem: " + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("Percent: "
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Threads running: "
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Names: " + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Single T: " + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("File T: " + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LastMsg: " + lastMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( "at " + lastMsgTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(lastMsgTime.get(Calendar.MINUTE)) + ":"
+ HelperRoutines.formatInt2(lastMsgTime.get(Calendar.SECOND)), 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
public int showSpeed(Graphics g, int yc, int la) {
g.setColor(0, 0, 0);
g.drawString("speed : " + speed, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("course : " + course, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("height : " + pos.altitude, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public int showDistanceToTarget(Graphics g, int yc, int la) {
g.setColor(0, 0, 0);
String text;
if (target == null) {
text = "Distance: N/A";
} else {
float distance = ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon);
if (distance > 10000) {
text = "Distance: " + Integer.toString((int)(distance/1000.0f)) + "km";
} else if (distance > 1000) {
text = "Distance: " + Float.toString(((int)(distance/100.0f))/10.0f) + "km";
} else {
text = "Distance: " + Integer.toString((int)distance) + "m";
}
}
g.drawString(text , 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
return yc;
}
private void updatePosition() {
if (pc != null){
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.clone();
pc.scale = scale;
pc.course=course;
repaint(0, 0, getWidth(), getHeight());
if (locationUpdateListeners != null) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosItion(float lat, float lon, float scale) {
logger.debug("Now displaying: " + (lat*MoreMath.FAC_RADTODEC) + "|" + (lon*MoreMath.FAC_RADTODEC));
center.setLatLon(lat, lon,true);
this.scale = scale;
updatePosition();
}
public synchronized void receivePosItion(Position pos) {
//#debug info
logger.info("New position: " + pos);
this.pos = pos;
collected++;
if (gpsRecenter) {
center.setLatLon(pos.latitude, pos.longitude);
}
speed = (int) (pos.speed * 3.6f);
if (gpx.isRecordingTrk()){
try {
gpx.addTrkPt(pos);
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
// don't rotate to fast
if (speed > 2) {
course = (int) ((pos.course * 3 + course) / 4)+360;
while (course > 360) course-=360;
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentMsg = s;
lastMsgTime.setTime( new Date( System.currentTimeMillis() ) );
repaint();
}
public void receiveStatelit(Satelit[] sat) {
this.sat = sat;
}
public MIDlet getParent() {
return parent;
}
protected void keyRepeated(int keyCode) {
// strange seem to be working in emulator only with this debug line
logger.debug("keyRepeated " + keyCode);
//Scrolling should work with repeated keys the same
//as pressing the key multiple times
if (keyCode==ignoreKeyCode) {
logger.debug("key ignored " + keyCode);
return;
}
int gameActionCode = this.getGameAction(keyCode);
if ((gameActionCode == UP) || (gameActionCode == DOWN) ||
(gameActionCode == RIGHT) || (gameActionCode == LEFT)) {
keyPressed(keyCode);
return;
}
if ((keyCode == KEY_NUM2) || (keyCode == KEY_NUM8)
|| (keyCode == KEY_NUM4) || (keyCode == KEY_NUM6)) {
keyPressed(keyCode);
return;
}
long keyTime=System.currentTimeMillis();
// other key is held down
if ( (keyTime-pressedKeyTime)>=1000 &&
pressedKeyCode==keyCode)
{
Command longC = (Command)longKeyPressCommand.get(keyCode);
//#debug debug
logger.debug("long key pressed " + keyCode + " executing command " + longC);
if (longC != null) {
ignoreKeyCode=keyCode;
commandAction(longC,(Displayable) null);
}
}
}
// // manage keys that would have different meanings when
// // held down in keyReleased
protected void keyReleased(final int keyCode) {
// if key was not handled as held down key
// strange seem to be working in emulator only with this debug line
logger.debug("keyReleased " + keyCode + " ignoreKeyCode: " + ignoreKeyCode + " prevRelCode: " + releasedKeyCode);
if (keyCode == ignoreKeyCode) {
ignoreKeyCode=0;
return;
}
final Command doubleC = (Command)doubleKeyPressCommand.get(keyCode);
// key was pressed twice quickly
if (releasedKeyCode == keyCode) {
releasedKeyCode = 0;
//#debug debug
logger.debug("double key pressed " + keyCode + " executing command " + doubleC);
if (doubleC != null) {
commandAction(doubleC,(Displayable) null);
}
} else {
releasedKeyCode = keyCode;
final Command singleC = (Command)singleKeyPressCommand.get(keyCode);
// #debug debug
logger.debug("single key initiated " + keyCode + " executing command " + singleC);
if (singleC != null) {
if (doubleC != null) {
TimerTask timerT;
Timer tm = new Timer();
timerT = new TimerTask() {
public void run() {
if (releasedKeyCode == keyCode) {
//#debug debug
logger.debug("single key pressed " + keyCode + " delayed executing command " + singleC);
// key was not pressed again within double press time
commandAction(singleC,(Displayable) null);
releasedKeyCode = 0;
repaint(0, 0, getWidth(), getHeight());
}
}
};
// set double press time
tm.schedule(timerT, 300);
} else {
//#debug debug
logger.debug("single key pressed " + keyCode + " executing command " + singleC);
commandAction(singleC,(Displayable) null);
releasedKeyCode = 0;
}
}
}
repaint();
}
protected void keyPressed(int keyCode) {
logger.debug("keyPressed " + keyCode);
ignoreKeyCode=0;
pressedKeyCode=keyCode;
pressedKeyTime=System.currentTimeMillis();
if(keyboardLocked && keyCode!=KEY_NUM9) {
GpsMid.getInstance().alert("GpsMid", "Keys locked. Hold down '9' to unlock.",1500);
ignoreKeyCode=keyCode;
return;
}
if (imageCollector != null) {
if (this.getGameAction(keyCode) == UP) {
imageCollector.getCurrentProjection().pan(center, 0, -2);
gpsRecenter = false;
} else if (this.getGameAction(keyCode) == DOWN) {
imageCollector.getCurrentProjection().pan(center, 0, 2);
gpsRecenter = false;
} else if (this.getGameAction(keyCode) == LEFT) {
imageCollector.getCurrentProjection().pan(center, -2, 0);
gpsRecenter = false;
} else if (this.getGameAction(keyCode) == RIGHT) {
imageCollector.getCurrentProjection().pan(center, 2, 0);
gpsRecenter = false;
}
if (keyCode == KEY_NUM2) {
imageCollector.getCurrentProjection().pan(center, 0, -25);
gpsRecenter = false;
} else if (keyCode == KEY_NUM8) {
imageCollector.getCurrentProjection().pan(center, 0, 25);
gpsRecenter = false;
} else if (keyCode == KEY_NUM4) {
imageCollector.getCurrentProjection().pan(center, -25, 0);
gpsRecenter = false;
} else if (keyCode == KEY_NUM6) {
imageCollector.getCurrentProjection().pan(center, 25, 0);
gpsRecenter = false;
}
}
repaint(0, 0, getWidth(), getHeight());
}
public Tile getDict(byte zl) {
return t[zl];
}
public void setDict(Tile dict, byte zl) {
t[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from config
config.getStartupPos(center);
if(center.radlat==0.0f && center.radlon==0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
if (pc != null) {
pc.center = center.clone();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint(0, 0, getWidth(), getHeight());
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (config.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
parent.mNoiseMaker.playSound("DISCONNECT");
}
if (gpx != null) {
/**
* Close and Save the gpx recording, to ensure we don't loose data
*/
gpx.saveTrk();
}
removeCommand(DISCONNECT_GPS_CMD);
if (locationProducer == null){
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
closeBtConnection();
notify();
addCommand(CONNECT_GPS_CMD);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveSolution(String s) {
solution = s;
}
public String getName(int idx) {
if (idx < 0)
return null;
return namesThread.getName(idx);
}
public Vector fulltextSearch (String snippet) {
return namesThread.fulltextSearch(snippet);
}
public void requestRedraw() {
repaint(0, 0, getWidth(), getHeight());
}
public void newDataReady() {
if (imageCollector != null)
imageCollector.newDataReady();
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
GpsMid.getInstance().show(this);
setFullScreenMode(config.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
requestRedraw();
}
public Configuration getConfig() {
return config;
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getTarget() {
return target;
}
public void setTarget(PositionMark target) {
setRoute(null);
setRouteNodes(null);
this.target = target;
pc.target = target;
if(target!=null) {
center.setLatLon(target.lat, target.lon,true);
pc.center = center.clone();
pc.scale = scale;
pc.course = course;
}
routeRecalculationRequired = false;
movedAwayFromTarget=false;
repaint(0, 0, getWidth(), getHeight());
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
rootCalc=false;
routeEngine=null;
iPassedRouteArrow=0;
sumWrongDirection=-1;
oldRouteInstructionColor = 0x00E6E6E6;
}
try {
if (config.isStopAllWhileRouteing()){
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else {
// resume();
}
repaint(0, 0, getWidth(), getHeight());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
logger.info("Hide notify has been called, screen will nolonger be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
logger.info("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
}
| false | true | private void showRoute(PaintContext pc) {
/* PASSINGDISTANCE is the distance when a routing arrow
is considered to match to the current position.
We currently can't adjust this value according to the speed
because if we would be slowing down during approaching the arrow,
then PASSINGDISTANCE could become smaller than the distance
to the arrow due and thus the routines would already use the
next arrow for routing assistance
*/
final int PASSINGDISTANCE=25;
StringBuffer soundToPlay = new StringBuffer();
String routeInstruction = null;
// backgound colour for standard routing instructions
int routeInstructionColor=0x00E6E6E6;
int diffArrowDist=0;
byte soundRepeatDelay=3;
byte soundRepeatTimes=2;
float nearestLat=0.0f;
float nearestLon=0.0f;
// this makes the distance when prepare-sound is played depending on the speed
int PREPAREDISTANCE=100;
if (speed>100) {
PREPAREDISTANCE=500;
} else if (speed>80) {
PREPAREDISTANCE=300;
} else if (speed>55) {
PREPAREDISTANCE=200;
} else if (speed>45) {
PREPAREDISTANCE=150;
} else if (speed>35) {
PREPAREDISTANCE=125;
}
ConnectionWithNode c;
// Show helper nodes for Routing
for (int x=0; x<routeNodes.size();x++){
RouteHelper n=(RouteHelper) routeNodes.elementAt(x);
pc.getP().forward(n.node.radlat, n.node.radlon, pc.lineP2);
pc.g.drawRect(pc.lineP2.x-5, pc.lineP2.y-5, 10, 10);
pc.g.drawString(n.name, pc.lineP2.x+7, pc.lineP2.y+5, Graphics.BOTTOM | Graphics.LEFT);
}
synchronized(this) {
if (route != null && route.size() > 0){
// there's a route so no calculation required
routeRecalculationRequired = false;
RouteNode lastTo;
// find nearest routing arrow (to center of screen)
int iNearest=0;
if (config.getCfgBitState(Configuration.CFGBIT_ROUTING_HELP)) {
c = (ConnectionWithNode) route.elementAt(0);
lastTo=c.to;
float minimumDistance=99999;
float distance=99999;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c!=null && c.to!=null && lastTo!=null) {
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
continue;
}
distance = ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
if (distance<minimumDistance) {
minimumDistance=distance;
iNearest=i;
}
lastTo=c.to;
}
}
//System.out.println("iNearest "+ iNearest + "dist: " + minimumDistance);
// if nearest route arrow is closer than PASSINGDISTANCE meters we're currently passing this route arrow
if (minimumDistance<PASSINGDISTANCE) {
if (iPassedRouteArrow != iNearest) {
iPassedRouteArrow = iNearest;
// if there's i.e. a 2nd left arrow in row "left" must be repeated
parent.mNoiseMaker.resetSoundRepeatTimes();
}
// after passing an arrow saying "in xxx metres" is allowed again
prepareInstructionSaid = false;
//System.out.println("iPassedRouteArrow "+ iPassedRouteArrow);
} else {
c = (ConnectionWithNode) route.elementAt(iPassedRouteArrow);
// if we got away more than PASSINGDISTANCE m of the previously passed routing arrow
if (ProjMath.getDistance(center.radlat, center.radlon, c.to.lat, c.to.lon) >= PASSINGDISTANCE) {
// assume we should start to emphasize the next routing arrow now
iNearest=iPassedRouteArrow+1;
}
}
}
c = (ConnectionWithNode) route.elementAt(0);
byte lastEndBearing=c.endBearing;
lastTo=c.to;
byte a=0;
byte aNearest=0;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c == null){
logger.error("show Route got null connection");
break;
}
if (c.to == null){
logger.error("show Route got connection with NULL as target");
break;
}
if (lastTo == null){
logger.error("show Route strange lastTo is null");
break;
}
if (pc == null){
logger.error("show Route strange pc is null");
break;
}
// if (pc.screenLD == null){
// System.out.println("show Route strange pc.screenLD is null");
// }
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
// draw small circle for left out connection
pc.g.setColor(0x00FDDF9F);
pc.getP().forward(c.to.lat, c.to.lon, pc.lineP2);
final byte radius=6;
pc.g.fillArc(pc.lineP2.x-radius/2,pc.lineP2.y-radius/2,radius,radius,0,359);
//System.out.println("Skipped routing arrow " + i);
// if this would have been our iNearest, use next one as iNearest
if(i==iNearest) iNearest++;
continue;
}
if(i!=iNearest) {
if (lastTo.lat < pc.getP().getMinLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon < pc.getP().getMinLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lat > pc.getP().getMaxLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon > pc.getP().getMaxLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
}
Image pict = pc.images.IMG_MARK; a=0;
// make bearing relative to current course for the first route arrow
if (i==1) {
lastEndBearing = (byte) (course%360 / 2);
}
int turn=(c.startBearing-lastEndBearing) * 2;
if (turn > 180) turn -= 360;
if (turn < -180) turn += 360;
// System.out.println("from: " + lastEndBearing*2 + " to:" +c.startBearing*2+ " turn " + turn);
if (turn > 110) {
pict=pc.images.IMG_HARDRIGHT; a=1;
} else if (turn > 70){
pict=pc.images.IMG_RIGHT; a=2;
} else if (turn > 20){
pict=pc.images.IMG_HALFRIGHT; a=3;
} else if (turn >= -20){
pict=pc.images.IMG_STRAIGHTON; a=4;
} else if (turn >= -70){
pict=pc.images.IMG_HALFLEFT; a=5;
} else if (turn >= -110){
pict=pc.images.IMG_LEFT; a=6;
} else {
pict=pc.images.IMG_HARDLEFT; a=7;
}
if (atTarget) {
a=8;
}
pc.getP().forward(lastTo.lat, lastTo.lon, pc.lineP2);
// optionally scale nearest arrow
if (i==iNearest) {
nearestLat=lastTo.lat;
nearestLon=lastTo.lon;
aNearest=a;
double distance=ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
int intDistance=new Double(distance).intValue();
routeInstruction=directions[a] + ((intDistance<PASSINGDISTANCE)?"":" in " + intDistance + "m");
if(intDistance<PASSINGDISTANCE) {
if (!atTarget) {
soundToPlay.append (soundDirections[a]);
}
soundRepeatTimes=1;
sumWrongDirection = -1;
diffArrowDist = 0;
oldRouteInstructionColor=0x00E6E6E6;
} else if (sumWrongDirection == -1) {
oldAwayFromNextArrow = intDistance;
sumWrongDirection=0;
diffArrowDist = 0;
} else {
diffArrowDist = (intDistance - oldAwayFromNextArrow);
}
if ( diffArrowDist == 0 ) {
routeInstructionColor=oldRouteInstructionColor;
} else if (intDistance < PASSINGDISTANCE) {
// background colour if currently passing
routeInstructionColor=0x00E6E6E6;
} else if ( diffArrowDist > 0) {
// background colour if distance to next arrow has just increased
routeInstructionColor=0x00FFCD9B;
} else {
// background colour if distance to next arrow has just decreased
routeInstructionColor=0x00B7FBBA;
}
sumWrongDirection += diffArrowDist;
//System.out.println("Sum wrong direction: " + sumWrongDirection);
oldAwayFromNextArrow = intDistance;
if (intDistance>=PASSINGDISTANCE) {
if (intDistance <= PREPAREDISTANCE) {
soundToPlay.append( (a==4 ? "CONTINUE" : "PREPARE") + ";" + soundDirections[a]);
soundRepeatDelay=5;
// Because of adaptive-to-speed distances for "prepare"-instructions
// GpsMid could fall back from "prepare"-instructions to "in xxx metres" voice instructions
// Remembering and checking if the prepare instruction already was given since the latest passing of an arrow avoids this
prepareInstructionSaid = true;
} else if (intDistance < 900 && !prepareInstructionSaid) {
soundRepeatDelay=60;
soundToPlay.append("IN;" + Integer.toString(intDistance / 100)+ "00;METERS;" + soundDirections[a]);
}
}
if (a!=arrow) {
arrow=a;
scaledPict=doubleImage(pict);
}
pict=scaledPict;
}
if (i == iNearest + 1) {
double distance=ProjMath.getDistance(nearestLat, nearestLon, lastTo.lat, lastTo.lon);
// if there is a close direction arrow after the current one
// inform the user about its direction
if (distance <= PREPAREDISTANCE &&
// only if not both arrows are STRAIGHT_ON
!(a==4 && aNearest == 4) &&
// and only as continuation of instruction
soundToPlay.length()!=0
) {
soundToPlay.append(";THEN;");
if (distance > PASSINGDISTANCE) {
soundToPlay.append("SOON;");
}
soundToPlay.append(soundDirections[a]);
// same arrow as currently nearest arrow?
if (a==aNearest) {
soundToPlay.append(";AGAIN");
}
//System.out.println(soundToPlay.toString());
}
}
// if the sum of movement away from the next arrow
// is much too high then recalculate route
if ( sumWrongDirection >= PREPAREDISTANCE * 2 / 3
|| sumWrongDirection >= 300) {
routeRecalculationRequired = true;
// if the sum of movement away from the next arrow is high
} else if ( sumWrongDirection >= PREPAREDISTANCE / 3
|| sumWrongDirection >= 150) {
// if distance to next arrow is high
// and moving away from next arrow
// ask user to check direction
if (diffArrowDist > 0) {
soundToPlay.setLength(0);
soundToPlay.append ("CHECK_DIRECTION");
soundRepeatDelay=5;
routeInstructionColor=0x00E6A03C;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
pc.g.drawImage(pict,pc.lineP2.x,pc.lineP2.y,CENTERPOS);
/*
Font originalFont = pc.g.getFont();
if (smallBoldFont==null) {
smallBoldFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
smallBoldFontHeight=smallBoldFont.getHeight();
}
pc.g.setFont(smallBoldFont);
pc.g.setColor(0,0,0);
int turnOrg=(c.startBearing - lastEndBearing)*2;
pc.g.drawString("S: " + c.startBearing*2 + " E: " + lastEndBearing*2 + " T: " + turn + "(" + turnOrg + ")",
pc.lineP2.x,
pc.lineP2.y-smallBoldFontHeight / 2,
Graphics.HCENTER | Graphics.TOP
);
pc.g.setFont(originalFont);
*/
lastEndBearing=c.endBearing;
lastTo=c.to;
}
}
/* if we just moved away from target,
* and the map is gpscentered
* and there's only one or no route arrow
* ==> auto recalculation
*/
if (movedAwayFromTarget
&& gpsRecenter
&& (route != null && route.size()==2)
&& ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon) > PREPAREDISTANCE
) {
routeRecalculationRequired=true;
}
if ( routeRecalculationRequired && !atTarget ) {
long recalculationTime=System.currentTimeMillis();
if ( source != null
&& gpsRecenter
&& config.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC)
// do not recalculate route more often than every 7 seconds
&& Math.abs(recalculationTime-oldRecalculationTime) >= 7000
) {
// if map is gps-centered recalculate route
soundToPlay.setLength(0);
if (config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound("ROUTE_RECALCULATION", (byte) 5, (byte) 1 );
}
commandAction(ROUTE_TO_CMD,(Displayable) null);
// set source to null to not recalculate
// route again before map was drawn
source=null;
oldRecalculationTime = recalculationTime;
// routerecalculations++;
}
if (diffArrowDist > 0) {
// use red background color if moving away
routeInstructionColor=0x00FF5402;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
}
// Route instruction text output
if ((routeInstruction != null) && (imageCollector != null)) {
Font originalFont = pc.g.getFont();
if (routeFont==null) {
routeFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
routeFontHeight=routeFont.getHeight();
}
pc.g.setFont(routeFont);
pc.g.setColor(routeInstructionColor);
oldRouteInstructionColor=routeInstructionColor;
pc.g.fillRect(0,pc.ySize-imageCollector.statusFontHeight-routeFontHeight, pc.xSize, routeFontHeight);
pc.g.setColor(0,0,0);
// pc.g.drawString(""+routerecalculations,
// 0,
// pc.ySize-imageCollector.statusFontHeight,
// Graphics.LEFT | Graphics.BOTTOM
// );
pc.g.drawString(routeInstruction,
pc.xSize/2,
pc.ySize-imageCollector.statusFontHeight,
Graphics.HCENTER | Graphics.BOTTOM
);
pc.g.setFont(originalFont);
}
// Route instruction sound output
if (soundToPlay.length()!=0 && config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound(soundToPlay.toString(), (byte) soundRepeatDelay, (byte) soundRepeatTimes);
}
}
| private void showRoute(PaintContext pc) {
/* PASSINGDISTANCE is the distance when a routing arrow
is considered to match to the current position.
We currently can't adjust this value according to the speed
because if we would be slowing down during approaching the arrow,
then PASSINGDISTANCE could become smaller than the distance
to the arrow due and thus the routines would already use the
next arrow for routing assistance
*/
final int PASSINGDISTANCE=25;
StringBuffer soundToPlay = new StringBuffer();
String routeInstruction = null;
// backgound colour for standard routing instructions
int routeInstructionColor=0x00E6E6E6;
int diffArrowDist=0;
byte soundRepeatDelay=3;
byte soundRepeatTimes=2;
float nearestLat=0.0f;
float nearestLon=0.0f;
// this makes the distance when prepare-sound is played depending on the speed
int PREPAREDISTANCE=100;
if (speed>100) {
PREPAREDISTANCE=500;
} else if (speed>80) {
PREPAREDISTANCE=300;
} else if (speed>55) {
PREPAREDISTANCE=200;
} else if (speed>45) {
PREPAREDISTANCE=150;
} else if (speed>35) {
PREPAREDISTANCE=125;
}
ConnectionWithNode c;
// Show helper nodes for Routing
for (int x=0; x<routeNodes.size();x++){
RouteHelper n=(RouteHelper) routeNodes.elementAt(x);
pc.getP().forward(n.node.radlat, n.node.radlon, pc.lineP2);
pc.g.drawRect(pc.lineP2.x-5, pc.lineP2.y-5, 10, 10);
pc.g.drawString(n.name, pc.lineP2.x+7, pc.lineP2.y+5, Graphics.BOTTOM | Graphics.LEFT);
}
synchronized(this) {
if (route != null && route.size() > 0){
// there's a route so no calculation required
routeRecalculationRequired = false;
RouteNode lastTo;
// find nearest routing arrow (to center of screen)
int iNearest=0;
if (config.getCfgBitState(Configuration.CFGBIT_ROUTING_HELP)) {
c = (ConnectionWithNode) route.elementAt(0);
lastTo=c.to;
float minimumDistance=99999;
float distance=99999;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c!=null && c.to!=null && lastTo!=null) {
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
continue;
}
distance = ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
if (distance<minimumDistance) {
minimumDistance=distance;
iNearest=i;
}
lastTo=c.to;
}
}
//System.out.println("iNearest "+ iNearest + "dist: " + minimumDistance);
// if nearest route arrow is closer than PASSINGDISTANCE meters we're currently passing this route arrow
if (minimumDistance<PASSINGDISTANCE) {
if (iPassedRouteArrow != iNearest) {
iPassedRouteArrow = iNearest;
// if there's i.e. a 2nd left arrow in row "left" must be repeated
parent.mNoiseMaker.resetSoundRepeatTimes();
}
// after passing an arrow saying "in xxx metres" is allowed again
prepareInstructionSaid = false;
//System.out.println("iPassedRouteArrow "+ iPassedRouteArrow);
} else {
c = (ConnectionWithNode) route.elementAt(iPassedRouteArrow);
// if we got away more than PASSINGDISTANCE m of the previously passed routing arrow
if (ProjMath.getDistance(center.radlat, center.radlon, c.to.lat, c.to.lon) >= PASSINGDISTANCE) {
// assume we should start to emphasize the next routing arrow now
iNearest=iPassedRouteArrow+1;
}
}
}
c = (ConnectionWithNode) route.elementAt(0);
int lastEndBearing=c.endBearing;
lastTo=c.to;
byte a=0;
byte aNearest=0;
for (int i=1; i<route.size();i++){
c = (ConnectionWithNode) route.elementAt(i);
if (c == null){
logger.error("show Route got null connection");
break;
}
if (c.to == null){
logger.error("show Route got connection with NULL as target");
break;
}
if (lastTo == null){
logger.error("show Route strange lastTo is null");
break;
}
if (pc == null){
logger.error("show Route strange pc is null");
break;
}
// if (pc.screenLD == null){
// System.out.println("show Route strange pc.screenLD is null");
// }
// skip connections that are closer than 25 m to the previous one
if( i<route.size()-1 && ProjMath.getDistance(c.to.lat, c.to.lon, lastTo.lat, lastTo.lon) < 25 ) {
// draw small circle for left out connection
pc.g.setColor(0x00FDDF9F);
pc.getP().forward(c.to.lat, c.to.lon, pc.lineP2);
final byte radius=6;
pc.g.fillArc(pc.lineP2.x-radius/2,pc.lineP2.y-radius/2,radius,radius,0,359);
//System.out.println("Skipped routing arrow " + i);
// if this would have been our iNearest, use next one as iNearest
if(i==iNearest) iNearest++;
continue;
}
if(i!=iNearest) {
if (lastTo.lat < pc.getP().getMinLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon < pc.getP().getMinLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lat > pc.getP().getMaxLat()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
if (lastTo.lon > pc.getP().getMaxLon()) {
lastEndBearing=c.endBearing;
lastTo=c.to;
continue;
}
}
Image pict = pc.images.IMG_MARK; a=0;
// make bearing relative to current course for the first route arrow
if (i==1) {
lastEndBearing = (course%360) / 2;
}
int turn=(c.startBearing-lastEndBearing) * 2;
if (turn > 180) turn -= 360;
if (turn < -180) turn += 360;
// System.out.println("from: " + lastEndBearing*2 + " to:" +c.startBearing*2+ " turn " + turn);
if (turn > 110) {
pict=pc.images.IMG_HARDRIGHT; a=1;
} else if (turn > 70){
pict=pc.images.IMG_RIGHT; a=2;
} else if (turn > 20){
pict=pc.images.IMG_HALFRIGHT; a=3;
} else if (turn >= -20){
pict=pc.images.IMG_STRAIGHTON; a=4;
} else if (turn >= -70){
pict=pc.images.IMG_HALFLEFT; a=5;
} else if (turn >= -110){
pict=pc.images.IMG_LEFT; a=6;
} else {
pict=pc.images.IMG_HARDLEFT; a=7;
}
if (atTarget) {
a=8;
}
pc.getP().forward(lastTo.lat, lastTo.lon, pc.lineP2);
// optionally scale nearest arrow
if (i==iNearest) {
nearestLat=lastTo.lat;
nearestLon=lastTo.lon;
aNearest=a;
double distance=ProjMath.getDistance(center.radlat, center.radlon, lastTo.lat, lastTo.lon);
int intDistance=new Double(distance).intValue();
routeInstruction=directions[a] + ((intDistance<PASSINGDISTANCE)?"":" in " + intDistance + "m");
if(intDistance<PASSINGDISTANCE) {
if (!atTarget) {
soundToPlay.append (soundDirections[a]);
}
soundRepeatTimes=1;
sumWrongDirection = -1;
diffArrowDist = 0;
oldRouteInstructionColor=0x00E6E6E6;
} else if (sumWrongDirection == -1) {
oldAwayFromNextArrow = intDistance;
sumWrongDirection=0;
diffArrowDist = 0;
} else {
diffArrowDist = (intDistance - oldAwayFromNextArrow);
}
if ( diffArrowDist == 0 ) {
routeInstructionColor=oldRouteInstructionColor;
} else if (intDistance < PASSINGDISTANCE) {
// background colour if currently passing
routeInstructionColor=0x00E6E6E6;
} else if ( diffArrowDist > 0) {
// background colour if distance to next arrow has just increased
routeInstructionColor=0x00FFCD9B;
} else {
// background colour if distance to next arrow has just decreased
routeInstructionColor=0x00B7FBBA;
}
sumWrongDirection += diffArrowDist;
//System.out.println("Sum wrong direction: " + sumWrongDirection);
oldAwayFromNextArrow = intDistance;
if (intDistance>=PASSINGDISTANCE) {
if (intDistance <= PREPAREDISTANCE) {
soundToPlay.append( (a==4 ? "CONTINUE" : "PREPARE") + ";" + soundDirections[a]);
soundRepeatDelay=5;
// Because of adaptive-to-speed distances for "prepare"-instructions
// GpsMid could fall back from "prepare"-instructions to "in xxx metres" voice instructions
// Remembering and checking if the prepare instruction already was given since the latest passing of an arrow avoids this
prepareInstructionSaid = true;
} else if (intDistance < 900 && !prepareInstructionSaid) {
soundRepeatDelay=60;
soundToPlay.append("IN;" + Integer.toString(intDistance / 100)+ "00;METERS;" + soundDirections[a]);
}
}
if (a!=arrow) {
arrow=a;
scaledPict=doubleImage(pict);
}
pict=scaledPict;
}
if (i == iNearest + 1) {
double distance=ProjMath.getDistance(nearestLat, nearestLon, lastTo.lat, lastTo.lon);
// if there is a close direction arrow after the current one
// inform the user about its direction
if (distance <= PREPAREDISTANCE &&
// only if not both arrows are STRAIGHT_ON
!(a==4 && aNearest == 4) &&
// and only as continuation of instruction
soundToPlay.length()!=0
) {
soundToPlay.append(";THEN;");
if (distance > PASSINGDISTANCE) {
soundToPlay.append("SOON;");
}
soundToPlay.append(soundDirections[a]);
// same arrow as currently nearest arrow?
if (a==aNearest) {
soundToPlay.append(";AGAIN");
}
//System.out.println(soundToPlay.toString());
}
}
// if the sum of movement away from the next arrow
// is much too high then recalculate route
if ( sumWrongDirection >= PREPAREDISTANCE * 2 / 3
|| sumWrongDirection >= 300) {
routeRecalculationRequired = true;
// if the sum of movement away from the next arrow is high
} else if ( sumWrongDirection >= PREPAREDISTANCE / 3
|| sumWrongDirection >= 150) {
// if distance to next arrow is high
// and moving away from next arrow
// ask user to check direction
if (diffArrowDist > 0) {
soundToPlay.setLength(0);
soundToPlay.append ("CHECK_DIRECTION");
soundRepeatDelay=5;
routeInstructionColor=0x00E6A03C;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
pc.g.drawImage(pict,pc.lineP2.x,pc.lineP2.y,CENTERPOS);
/*
Font originalFont = pc.g.getFont();
if (smallBoldFont==null) {
smallBoldFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
smallBoldFontHeight=smallBoldFont.getHeight();
}
pc.g.setFont(smallBoldFont);
pc.g.setColor(0,0,0);
int turnOrg=(c.startBearing - lastEndBearing)*2;
pc.g.drawString("S: " + c.startBearing*2 + " E: " + lastEndBearing*2 + " C: " + course + " T: " + turn + "(" + turnOrg + ")",
pc.lineP2.x,
pc.lineP2.y-smallBoldFontHeight / 2,
Graphics.HCENTER | Graphics.TOP
);
pc.g.setFont(originalFont);
*/
lastEndBearing=c.endBearing;
lastTo=c.to;
}
}
/* if we just moved away from target,
* and the map is gpscentered
* and there's only one or no route arrow
* ==> auto recalculation
*/
if (movedAwayFromTarget
&& gpsRecenter
&& (route != null && route.size()==2)
&& ProjMath.getDistance(target.lat, target.lon, center.radlat, center.radlon) > PREPAREDISTANCE
) {
routeRecalculationRequired=true;
}
if ( routeRecalculationRequired && !atTarget ) {
long recalculationTime=System.currentTimeMillis();
if ( source != null
&& gpsRecenter
&& config.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC)
// do not recalculate route more often than every 7 seconds
&& Math.abs(recalculationTime-oldRecalculationTime) >= 7000
) {
// if map is gps-centered recalculate route
soundToPlay.setLength(0);
if (config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound("ROUTE_RECALCULATION", (byte) 5, (byte) 1 );
}
commandAction(ROUTE_TO_CMD,(Displayable) null);
// set source to null to not recalculate
// route again before map was drawn
source=null;
oldRecalculationTime = recalculationTime;
// routerecalculations++;
}
if (diffArrowDist > 0) {
// use red background color if moving away
routeInstructionColor=0x00FF5402;
} else if (diffArrowDist == 0) {
routeInstructionColor = oldRouteInstructionColor;
}
}
}
// Route instruction text output
if ((routeInstruction != null) && (imageCollector != null)) {
Font originalFont = pc.g.getFont();
if (routeFont==null) {
routeFont=Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
routeFontHeight=routeFont.getHeight();
}
pc.g.setFont(routeFont);
pc.g.setColor(routeInstructionColor);
oldRouteInstructionColor=routeInstructionColor;
pc.g.fillRect(0,pc.ySize-imageCollector.statusFontHeight-routeFontHeight, pc.xSize, routeFontHeight);
pc.g.setColor(0,0,0);
// pc.g.drawString(""+routerecalculations,
// 0,
// pc.ySize-imageCollector.statusFontHeight,
// Graphics.LEFT | Graphics.BOTTOM
// );
pc.g.drawString(routeInstruction,
pc.xSize/2,
pc.ySize-imageCollector.statusFontHeight,
Graphics.HCENTER | Graphics.BOTTOM
);
pc.g.setFont(originalFont);
}
// Route instruction sound output
if (soundToPlay.length()!=0 && config.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
parent.mNoiseMaker.playSound(soundToPlay.toString(), (byte) soundRepeatDelay, (byte) soundRepeatTimes);
}
}
|
diff --git a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java
index dd8ab3a..8d56861 100644
--- a/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java
+++ b/broadcast-transcoder-commandline/src/main/java/dk/statsbiblioteket/broadcasttranscoder/ReklamefilmTranscoderApplication.java
@@ -1,92 +1,94 @@
package dk.statsbiblioteket.broadcasttranscoder;
import dk.statsbiblioteket.broadcasttranscoder.cli.Context;
import dk.statsbiblioteket.broadcasttranscoder.cli.OptionParseException;
import dk.statsbiblioteket.broadcasttranscoder.cli.OptionsParser;
import dk.statsbiblioteket.broadcasttranscoder.processors.*;
import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.FfprobeFetcherProcessor;
import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.GoNoGoProcessor;
import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmFileResolverProcessor;
import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmPersistentRecordEnricherProcessor;
import dk.statsbiblioteket.broadcasttranscoder.reklamefilm.ReklamefilmFileResolverImpl;
import dk.statsbiblioteket.broadcasttranscoder.util.FileUtils;
import dk.statsbiblioteket.broadcasttranscoder.util.persistence.HibernateUtil;
import dk.statsbiblioteket.broadcasttranscoder.util.persistence.ReklamefilmTranscodingRecordDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
*
*/
public class ReklamefilmTranscoderApplication {
private static Logger logger = LoggerFactory.getLogger(ReklamefilmTranscoderApplication.class);
public static void main(String[] args) throws Exception {
logger.debug("Entered main method.");
Context context = new OptionsParser().parseOptions(args);
HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath());
context.setTimestampPersister(new ReklamefilmTranscodingRecordDAO(util));
context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context));
TranscodeRequest request = new TranscodeRequest();
File lockFile = FileUtils.getLockFile(request, context);
if (lockFile.exists()) {
logger.warn("Lockfile " + lockFile.getAbsolutePath() + " already exists. Exiting.");
System.exit(2);
}
try {
boolean created = lockFile.createNewFile();
if (!created) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
} catch (IOException e) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
try {
request.setGoForTranscoding(true);
ProcessorChainElement gonogoer = new GoNoGoProcessor();
ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer);
firstChain.processIteratively(request, context);
if (request.isGoForTranscoding()) {
context.getTimestampPersister().setTimestamp(context.getProgrampid(), context.getTranscodingTimestamp());
ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor();
ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor();
ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor();
+ ProcessorChainElement renamer = new FinalMediaFileRenamerProcessor();
ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor();
ProcessorChainElement ffprober = new FfprobeFetcherProcessor();
ProcessorChainElement snapshotter = new SnapshotExtractorProcessor();
ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor();
ProcessorChainElement secondChain = ProcessorChainElement.makeChain(
resolver,
aspecter,
transcoder,
+ renamer,
zeroChecker,
ffprober,
snapshotter,
reklamePersistenceEnricher
);
secondChain.processIteratively(request, context);
}
} catch (Exception e) {
//Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it
//failed on.
logger.error("Error processing " + context.getProgrampid(), e);
throw(e);
} finally {
boolean deleted = lockFile.delete();
if (!deleted) {
logger.error("Could not delete lockfile: " + lockFile.getAbsolutePath());
System.exit(4);
}
}
}
}
| false | true | public static void main(String[] args) throws Exception {
logger.debug("Entered main method.");
Context context = new OptionsParser().parseOptions(args);
HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath());
context.setTimestampPersister(new ReklamefilmTranscodingRecordDAO(util));
context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context));
TranscodeRequest request = new TranscodeRequest();
File lockFile = FileUtils.getLockFile(request, context);
if (lockFile.exists()) {
logger.warn("Lockfile " + lockFile.getAbsolutePath() + " already exists. Exiting.");
System.exit(2);
}
try {
boolean created = lockFile.createNewFile();
if (!created) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
} catch (IOException e) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
try {
request.setGoForTranscoding(true);
ProcessorChainElement gonogoer = new GoNoGoProcessor();
ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer);
firstChain.processIteratively(request, context);
if (request.isGoForTranscoding()) {
context.getTimestampPersister().setTimestamp(context.getProgrampid(), context.getTranscodingTimestamp());
ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor();
ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor();
ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor();
ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor();
ProcessorChainElement ffprober = new FfprobeFetcherProcessor();
ProcessorChainElement snapshotter = new SnapshotExtractorProcessor();
ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor();
ProcessorChainElement secondChain = ProcessorChainElement.makeChain(
resolver,
aspecter,
transcoder,
zeroChecker,
ffprober,
snapshotter,
reklamePersistenceEnricher
);
secondChain.processIteratively(request, context);
}
} catch (Exception e) {
//Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it
//failed on.
logger.error("Error processing " + context.getProgrampid(), e);
throw(e);
} finally {
boolean deleted = lockFile.delete();
if (!deleted) {
logger.error("Could not delete lockfile: " + lockFile.getAbsolutePath());
System.exit(4);
}
}
}
| public static void main(String[] args) throws Exception {
logger.debug("Entered main method.");
Context context = new OptionsParser().parseOptions(args);
HibernateUtil util = HibernateUtil.getInstance(context.getHibernateConfigFile().getAbsolutePath());
context.setTimestampPersister(new ReklamefilmTranscodingRecordDAO(util));
context.setReklamefilmFileResolver(new ReklamefilmFileResolverImpl(context));
TranscodeRequest request = new TranscodeRequest();
File lockFile = FileUtils.getLockFile(request, context);
if (lockFile.exists()) {
logger.warn("Lockfile " + lockFile.getAbsolutePath() + " already exists. Exiting.");
System.exit(2);
}
try {
boolean created = lockFile.createNewFile();
if (!created) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
} catch (IOException e) {
logger.warn("Could not create lockfile: " + lockFile.getAbsolutePath() + ". Exiting.");
System.exit(3);
}
try {
request.setGoForTranscoding(true);
ProcessorChainElement gonogoer = new GoNoGoProcessor();
ProcessorChainElement firstChain = ProcessorChainElement.makeChain(gonogoer);
firstChain.processIteratively(request, context);
if (request.isGoForTranscoding()) {
context.getTimestampPersister().setTimestamp(context.getProgrampid(), context.getTranscodingTimestamp());
ProcessorChainElement resolver = new ReklamefilmFileResolverProcessor();
ProcessorChainElement aspecter = new PidAndAsepctRatioExtractorProcessor();
ProcessorChainElement transcoder = new UnistreamVideoTranscoderProcessor();
ProcessorChainElement renamer = new FinalMediaFileRenamerProcessor();
ProcessorChainElement zeroChecker = new ZeroLengthCheckerProcessor();
ProcessorChainElement ffprober = new FfprobeFetcherProcessor();
ProcessorChainElement snapshotter = new SnapshotExtractorProcessor();
ProcessorChainElement reklamePersistenceEnricher = new ReklamefilmPersistentRecordEnricherProcessor();
ProcessorChainElement secondChain = ProcessorChainElement.makeChain(
resolver,
aspecter,
transcoder,
renamer,
zeroChecker,
ffprober,
snapshotter,
reklamePersistenceEnricher
);
secondChain.processIteratively(request, context);
}
} catch (Exception e) {
//Fault barrier. This is necessary because an uncaught RuntimeException will otherwise not log the pid it
//failed on.
logger.error("Error processing " + context.getProgrampid(), e);
throw(e);
} finally {
boolean deleted = lockFile.delete();
if (!deleted) {
logger.error("Could not delete lockfile: " + lockFile.getAbsolutePath());
System.exit(4);
}
}
}
|
diff --git a/src/main/java/fr/ribesg/alix/network/InternalMessageHandler.java b/src/main/java/fr/ribesg/alix/network/InternalMessageHandler.java
index e32d141..825c1d0 100644
--- a/src/main/java/fr/ribesg/alix/network/InternalMessageHandler.java
+++ b/src/main/java/fr/ribesg/alix/network/InternalMessageHandler.java
@@ -1,134 +1,134 @@
package fr.ribesg.alix.network;
import fr.ribesg.alix.api.Channel;
import fr.ribesg.alix.api.Client;
import fr.ribesg.alix.api.Server;
import fr.ribesg.alix.api.Source;
import fr.ribesg.alix.api.enums.Command;
import fr.ribesg.alix.api.enums.Reply;
import fr.ribesg.alix.api.message.Message;
import fr.ribesg.alix.api.message.PongMessage;
import org.apache.log4j.Logger;
/**
* This class handles messages internally. An example being more clear than
* any explanation, this class typically handle PING commands by responding
* with a PONG command.
* <p/>
* If the message has or can be handled externally (understand "by the API
* user" here), then the handler will make appropriate calls to the Client.
* <p/>
* Note that every message will still produce a call to
* {@link Client#onRawIrcMessage(Server, Message)}.
*
* @author Ribesg
*/
public class InternalMessageHandler {
private static final Logger LOGGER = Logger.getLogger(InternalMessageHandler.class.getName());
/**
* A reference to the Client is always nice to have.
*/
private final Client client;
/**
* Constructor
*
* @param client the Client this Handler relates to
*/
/* package */ InternalMessageHandler(final Client client) {
this.client = client;
}
/**
* Handles received messages.
*
* @param server the Server the message come from
* @param messageString the raw IRC message to handle
*/
/* package */ void handleMessage(final Server server, final String messageString) {
new Thread(new Runnable() {
@Override
public void run() {
handleMessageAsync(server, messageString);
}
}).start();
}
/**
* Handles received messages asynchronously.
* Used to prevent locking the SocketReceiver.
*
* @param server the Server the message come from
* @param messageString the raw IRC message to handle
*/
private void handleMessageAsync(final Server server, final String messageString) {
// Parse the Message
final Message m = Message.parseMessage(messageString);
// Raw IRC Message
client.onRawIrcMessage(server, m);
// Command?
final boolean isCommand = m.isValidCommand();
if (isCommand) {
final Command cmd = m.getCommandAsCommand();
switch (cmd) {
case PING:
server.send(new PongMessage(m.getTrail()));
break;
case JOIN:
case PART:
// Workaround for IRCds using the trail as parameter (Unreal)
final String channelName = m.getParameters().length > 0 ? m.getParameters()[0] : m.getTrail();
final Channel channel = server.getChannel(channelName);
- if (m.getPrefix() == null) {
+ Source source = m.getPrefix() == null ? null : m.getPrefixAsSource(server);
+ if (source == null || source.getName().equals(client.getName())) {
if (cmd == Command.JOIN) {
client.onAlixJoinChannel(channel);
} else {
client.onAlixPartChannel(channel);
}
} else {
- final Source source = m.getPrefixAsSource(server);
if (cmd == Command.JOIN) {
client.onUserJoinChannel(source, channel);
} else {
client.onUserPartChannel(source, channel);
}
}
break;
case PRIVMSG:
- final Source source = m.getPrefixAsSource(server);
+ source = m.getPrefixAsSource(server);
final String dest = m.getParameters()[0];
if (dest.startsWith("#")) {
client.onChannelMessage(server.getChannel(dest), source, m.getTrail());
} else {
client.onPrivateMessage(server, source, m.getTrail());
}
break;
default:
break;
}
}
// Reply?
else if (m.isValidReply()) {
final Reply rep = m.getCommandAsReply();
switch (rep) {
case RPL_WELCOME:
server.setConnected(true);
server.joinChannels();
client.onServerJoined(server);
break;
default:
break;
}
} else {
// Reply code not defined by the RFCs
LOGGER.warn("Unknown command/reply code: " + m.getRawCommandString());
}
}
}
| false | true | private void handleMessageAsync(final Server server, final String messageString) {
// Parse the Message
final Message m = Message.parseMessage(messageString);
// Raw IRC Message
client.onRawIrcMessage(server, m);
// Command?
final boolean isCommand = m.isValidCommand();
if (isCommand) {
final Command cmd = m.getCommandAsCommand();
switch (cmd) {
case PING:
server.send(new PongMessage(m.getTrail()));
break;
case JOIN:
case PART:
// Workaround for IRCds using the trail as parameter (Unreal)
final String channelName = m.getParameters().length > 0 ? m.getParameters()[0] : m.getTrail();
final Channel channel = server.getChannel(channelName);
if (m.getPrefix() == null) {
if (cmd == Command.JOIN) {
client.onAlixJoinChannel(channel);
} else {
client.onAlixPartChannel(channel);
}
} else {
final Source source = m.getPrefixAsSource(server);
if (cmd == Command.JOIN) {
client.onUserJoinChannel(source, channel);
} else {
client.onUserPartChannel(source, channel);
}
}
break;
case PRIVMSG:
final Source source = m.getPrefixAsSource(server);
final String dest = m.getParameters()[0];
if (dest.startsWith("#")) {
client.onChannelMessage(server.getChannel(dest), source, m.getTrail());
} else {
client.onPrivateMessage(server, source, m.getTrail());
}
break;
default:
break;
}
}
// Reply?
else if (m.isValidReply()) {
final Reply rep = m.getCommandAsReply();
switch (rep) {
case RPL_WELCOME:
server.setConnected(true);
server.joinChannels();
client.onServerJoined(server);
break;
default:
break;
}
} else {
// Reply code not defined by the RFCs
LOGGER.warn("Unknown command/reply code: " + m.getRawCommandString());
}
}
| private void handleMessageAsync(final Server server, final String messageString) {
// Parse the Message
final Message m = Message.parseMessage(messageString);
// Raw IRC Message
client.onRawIrcMessage(server, m);
// Command?
final boolean isCommand = m.isValidCommand();
if (isCommand) {
final Command cmd = m.getCommandAsCommand();
switch (cmd) {
case PING:
server.send(new PongMessage(m.getTrail()));
break;
case JOIN:
case PART:
// Workaround for IRCds using the trail as parameter (Unreal)
final String channelName = m.getParameters().length > 0 ? m.getParameters()[0] : m.getTrail();
final Channel channel = server.getChannel(channelName);
Source source = m.getPrefix() == null ? null : m.getPrefixAsSource(server);
if (source == null || source.getName().equals(client.getName())) {
if (cmd == Command.JOIN) {
client.onAlixJoinChannel(channel);
} else {
client.onAlixPartChannel(channel);
}
} else {
if (cmd == Command.JOIN) {
client.onUserJoinChannel(source, channel);
} else {
client.onUserPartChannel(source, channel);
}
}
break;
case PRIVMSG:
source = m.getPrefixAsSource(server);
final String dest = m.getParameters()[0];
if (dest.startsWith("#")) {
client.onChannelMessage(server.getChannel(dest), source, m.getTrail());
} else {
client.onPrivateMessage(server, source, m.getTrail());
}
break;
default:
break;
}
}
// Reply?
else if (m.isValidReply()) {
final Reply rep = m.getCommandAsReply();
switch (rep) {
case RPL_WELCOME:
server.setConnected(true);
server.joinChannels();
client.onServerJoined(server);
break;
default:
break;
}
} else {
// Reply code not defined by the RFCs
LOGGER.warn("Unknown command/reply code: " + m.getRawCommandString());
}
}
|
diff --git a/src/net/mcft/copy/betterstorage/item/EnchantmentBetterStorage.java b/src/net/mcft/copy/betterstorage/item/EnchantmentBetterStorage.java
index 8bcbab6..2cd3042 100644
--- a/src/net/mcft/copy/betterstorage/item/EnchantmentBetterStorage.java
+++ b/src/net/mcft/copy/betterstorage/item/EnchantmentBetterStorage.java
@@ -1,126 +1,128 @@
package net.mcft.copy.betterstorage.item;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import net.mcft.copy.betterstorage.Config;
import net.mcft.copy.betterstorage.api.BetterStorageEnchantment;
import net.mcft.copy.betterstorage.api.lock.IKey;
import net.mcft.copy.betterstorage.api.lock.ILock;
import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.misc.Constants;
import net.mcft.copy.betterstorage.utils.MiscUtils;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.EnumHelper;
public class EnchantmentBetterStorage extends Enchantment {
private final int maxLevel;
private final int minBase, minScaling;
private final int maxBase, maxScaling;
private List<Enchantment> incompatible = new ArrayList<Enchantment>(0);
public static void initialize() {
Map<String, EnumEnchantmentType> types = BetterStorageEnchantment.enchantmentTypes;
Map<String, Enchantment> enchs = BetterStorageEnchantment.enchantments;
// Add key enchantments
if (MiscUtils.isEnabled(Items.key)) {
EnumEnchantmentType key = EnumHelper.addEnchantmentType("key");
EnchantmentBetterStorage unlocking = conditialNew("unlocking", key, Config.enchantmentUnlockingId, 8, 5, 5, 10, 30, 0);
EnchantmentBetterStorage lockpicking = conditialNew("lockpicking", key, Config.enchantmentLockpickingId, 6, 5, 5, 8, 30, 0);
EnchantmentBetterStorage morphing = conditialNew("morphing", key, Config.enchantmentMorphingId, 1, 5, 10, 12, 30, 0);
- lockpicking.setIncompatible(morphing);
- morphing.setIncompatible(lockpicking);
+ if (lockpicking != null)
+ lockpicking.setIncompatible(morphing);
+ if (morphing != null)
+ morphing.setIncompatible(lockpicking);
types.put("key", key);
enchs.put("unlocking", unlocking);
enchs.put("lockpicking", lockpicking);
enchs.put("morphing", morphing);
}
// Add lock enchantments
if (MiscUtils.isEnabled(Items.lock)) {
EnumEnchantmentType lock = EnumHelper.addEnchantmentType("lock");
EnchantmentBetterStorage persistance = conditialNew("persistance", lock, Config.enchantmentPersistanceId, 20, 5, 1, 8, 30, 0);
EnchantmentBetterStorage security = conditialNew("security", lock, Config.enchantmentSecurityId, 16, 5, 1, 10, 30, 0);
EnchantmentBetterStorage shock = conditialNew("shock", lock, Config.enchantmentShockId, 5, 3, 5, 15, 30, 0);
EnchantmentBetterStorage trigger = conditialNew("trigger", lock, Config.enchantmentTriggerId, 10, 1, 15, 0, 30, 0);
types.put("lock", lock);
enchs.put("persistance",persistance);
enchs.put("security", security);
enchs.put("shock", shock);
enchs.put("trigger", trigger);
}
}
private static EnchantmentBetterStorage conditialNew(String name, EnumEnchantmentType type, int id, int weight, int maxLevel,
int minBase, int minScaling, int maxBase, int maxScaling) {
if (!MiscUtils.isEnabled(id)) return null;
return new EnchantmentBetterStorage(name, type, id, weight, maxLevel, minBase, minScaling, maxBase, maxScaling);
}
public EnchantmentBetterStorage(String name, EnumEnchantmentType type, int id, int weight, int maxLevel,
int minBase, int minScaling, int maxBase, int maxScaling) {
super(id, weight, type);
setName(Constants.modId + "." + type.toString() + "." + name);
this.maxLevel = maxLevel;
this.minBase = minBase;
this.minScaling = minScaling;
this.maxBase = maxBase;
this.maxScaling = maxScaling;
}
public void setIncompatible(Enchantment... incompatible) {
this.incompatible = Arrays.asList(incompatible);
}
@Override
public int getMaxLevel() { return maxLevel; }
@Override
public int getMinEnchantability(int level) {
return minBase + (level - 1) * minScaling;
}
@Override
public int getMaxEnchantability(int level) {
return getMinEnchantability(level) + maxBase + (level - 1) * maxScaling;
}
@Override
public boolean canApplyAtEnchantingTable(ItemStack stack) {
if (type == BetterStorageEnchantment.getType("key")) {
IKey key = (stack.getItem() instanceof IKey ? (IKey)stack.getItem() : null);
return ((key != null) && key.canApplyEnchantment(stack, this));
} else if (type == BetterStorageEnchantment.getType("lock")) {
ILock lock = (stack.getItem() instanceof ILock ? (ILock)stack.getItem() : null);
return ((lock != null) && lock.canApplyEnchantment(stack, this));
} else return false;
}
@Override
public boolean canApply(ItemStack stack) {
return canApplyAtEnchantingTable(stack);
}
@Override
public boolean canApplyTogether(Enchantment other) {
return (super.canApplyTogether(other) &&
!incompatible.contains(other));
}
@Override
public boolean isAllowedOnBooks() { return false; }
}
| true | true | public static void initialize() {
Map<String, EnumEnchantmentType> types = BetterStorageEnchantment.enchantmentTypes;
Map<String, Enchantment> enchs = BetterStorageEnchantment.enchantments;
// Add key enchantments
if (MiscUtils.isEnabled(Items.key)) {
EnumEnchantmentType key = EnumHelper.addEnchantmentType("key");
EnchantmentBetterStorage unlocking = conditialNew("unlocking", key, Config.enchantmentUnlockingId, 8, 5, 5, 10, 30, 0);
EnchantmentBetterStorage lockpicking = conditialNew("lockpicking", key, Config.enchantmentLockpickingId, 6, 5, 5, 8, 30, 0);
EnchantmentBetterStorage morphing = conditialNew("morphing", key, Config.enchantmentMorphingId, 1, 5, 10, 12, 30, 0);
lockpicking.setIncompatible(morphing);
morphing.setIncompatible(lockpicking);
types.put("key", key);
enchs.put("unlocking", unlocking);
enchs.put("lockpicking", lockpicking);
enchs.put("morphing", morphing);
}
// Add lock enchantments
if (MiscUtils.isEnabled(Items.lock)) {
EnumEnchantmentType lock = EnumHelper.addEnchantmentType("lock");
EnchantmentBetterStorage persistance = conditialNew("persistance", lock, Config.enchantmentPersistanceId, 20, 5, 1, 8, 30, 0);
EnchantmentBetterStorage security = conditialNew("security", lock, Config.enchantmentSecurityId, 16, 5, 1, 10, 30, 0);
EnchantmentBetterStorage shock = conditialNew("shock", lock, Config.enchantmentShockId, 5, 3, 5, 15, 30, 0);
EnchantmentBetterStorage trigger = conditialNew("trigger", lock, Config.enchantmentTriggerId, 10, 1, 15, 0, 30, 0);
types.put("lock", lock);
enchs.put("persistance",persistance);
enchs.put("security", security);
enchs.put("shock", shock);
enchs.put("trigger", trigger);
}
}
| public static void initialize() {
Map<String, EnumEnchantmentType> types = BetterStorageEnchantment.enchantmentTypes;
Map<String, Enchantment> enchs = BetterStorageEnchantment.enchantments;
// Add key enchantments
if (MiscUtils.isEnabled(Items.key)) {
EnumEnchantmentType key = EnumHelper.addEnchantmentType("key");
EnchantmentBetterStorage unlocking = conditialNew("unlocking", key, Config.enchantmentUnlockingId, 8, 5, 5, 10, 30, 0);
EnchantmentBetterStorage lockpicking = conditialNew("lockpicking", key, Config.enchantmentLockpickingId, 6, 5, 5, 8, 30, 0);
EnchantmentBetterStorage morphing = conditialNew("morphing", key, Config.enchantmentMorphingId, 1, 5, 10, 12, 30, 0);
if (lockpicking != null)
lockpicking.setIncompatible(morphing);
if (morphing != null)
morphing.setIncompatible(lockpicking);
types.put("key", key);
enchs.put("unlocking", unlocking);
enchs.put("lockpicking", lockpicking);
enchs.put("morphing", morphing);
}
// Add lock enchantments
if (MiscUtils.isEnabled(Items.lock)) {
EnumEnchantmentType lock = EnumHelper.addEnchantmentType("lock");
EnchantmentBetterStorage persistance = conditialNew("persistance", lock, Config.enchantmentPersistanceId, 20, 5, 1, 8, 30, 0);
EnchantmentBetterStorage security = conditialNew("security", lock, Config.enchantmentSecurityId, 16, 5, 1, 10, 30, 0);
EnchantmentBetterStorage shock = conditialNew("shock", lock, Config.enchantmentShockId, 5, 3, 5, 15, 30, 0);
EnchantmentBetterStorage trigger = conditialNew("trigger", lock, Config.enchantmentTriggerId, 10, 1, 15, 0, 30, 0);
types.put("lock", lock);
enchs.put("persistance",persistance);
enchs.put("security", security);
enchs.put("shock", shock);
enchs.put("trigger", trigger);
}
}
|
diff --git a/src/com/irccloud/android/MessageViewFragment.java b/src/com/irccloud/android/MessageViewFragment.java
index 49d55e92..0c262249 100644
--- a/src/com/irccloud/android/MessageViewFragment.java
+++ b/src/com/irccloud/android/MessageViewFragment.java
@@ -1,2182 +1,2185 @@
/*
* Copyright (c) 2013 IRCCloud, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.irccloud.android;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import android.os.Debug;
import android.support.v4.app.ListFragment;
import android.text.TextUtils;
import android.view.animation.AlphaAnimation;
import android.widget.*;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.irccloud.android.BuffersListFragment.OnBufferSelectedListener;
public class MessageViewFragment extends ListFragment {
private NetworkConnection conn;
private TextView statusView;
private View headerViewContainer;
private View headerView;
private TextView backlogFailed;
private Button loadBacklogButton;
private TextView unreadTopLabel;
private TextView unreadBottomLabel;
private View unreadTopView;
private View unreadBottomView;
private TextView highlightsTopLabel;
private TextView highlightsBottomLabel;
private int cid = -1;
public int bid = -1;
private long last_seen_eid;
private long min_eid;
private long earliest_eid;
private long backlog_eid = 0;
private String name;
private String type;
private boolean scrolledUp = false;
private boolean requestingBacklog = false;
private float avgInsertTime = 0;
private int newMsgs = 0;
private long newMsgTime = 0;
private int newHighlights = 0;
private MessageViewListener mListener;
private TextView errorMsg = null;
private TextView connectingMsg = null;
private ProgressBar progressBar = null;
private Timer countdownTimer = null;
private String error = null;
private View connecting = null;
private View awayView = null;
private TextView awayTxt = null;
private int savedScrollPos = -1;
private int timestamp_width = -1;
private View globalMsgView = null;
private TextView globalMsg = null;
private ProgressBar spinner = null;
public static final int ROW_MESSAGE = 0;
public static final int ROW_TIMESTAMP = 1;
public static final int ROW_BACKLOGMARKER = 2;
public static final int ROW_SOCKETCLOSED = 3;
public static final int ROW_LASTSEENEID = 4;
private static final String TYPE_TIMESTAMP = "__timestamp__";
private static final String TYPE_BACKLOGMARKER = "__backlog__";
private static final String TYPE_LASTSEENEID = "__lastseeneid__";
private MessageAdapter adapter;
private long currentCollapsedEid = -1;
private CollapsedEventsList collapsedEvents = new CollapsedEventsList();
private int lastCollapsedDay = -1;
private HashSet<Long> expandedSectionEids = new HashSet<Long>();
private RefreshTask refreshTask = null;
private HeartbeatTask heartbeatTask = null;
private Ignore ignore = new Ignore();
private Timer tapTimer = null;
private ServersDataSource.Server mServer = null;
private boolean longPressOverride = false;
private LinkMovementMethodNoLongPress linkMovementMethodNoLongPress = new LinkMovementMethodNoLongPress();
public boolean ready = false;
private boolean dirty = true;
private class LinkMovementMethodNoLongPress extends LinkMovementMethod {
@Override
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
if(longPressOverride) {
longPressOverride = false;
return false;
} else {
return super.onTouchEvent(widget, buffer, event);
}
}
}
private class MessageAdapter extends BaseAdapter {
ArrayList<EventsDataSource.Event> data;
private ListFragment ctx;
private long max_eid = 0;
private long min_eid = 0;
private int lastDay = -1;
private int lastSeenEidMarkerPosition = -1;
private int currentGroupPosition = -1;
private TreeSet<Integer> unseenHighlightPositions;
private class ViewHolder {
int type;
TextView timestamp;
TextView message;
ImageView expandable;
ImageView failed;
}
public MessageAdapter(ListFragment context) {
ctx = context;
data = new ArrayList<EventsDataSource.Event>();
unseenHighlightPositions = new TreeSet<Integer>(Collections.reverseOrder());
}
public void clear() {
max_eid = 0;
min_eid = 0;
lastDay = -1;
lastSeenEidMarkerPosition = -1;
currentGroupPosition = -1;
data.clear();
unseenHighlightPositions.clear();
}
public void clearPending() {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).reqid != -1 && data.get(i).color == R.color.timestamp) {
data.remove(i);
i--;
}
}
}
public void removeItem(long eid) {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).eid == eid) {
data.remove(i);
i--;
}
}
}
public int getBacklogMarkerPosition() {
try {
for(int i = 0; data != null && i < data.size(); i++) {
EventsDataSource.Event e = data.get(i);
if(e != null && e.row_type == ROW_BACKLOGMARKER) {
return i;
}
}
} catch (Exception e) {
}
return -1;
}
public int insertLastSeenEIDMarker() {
EventsDataSource.Event e = EventsDataSource.getInstance().new Event();
e.type = TYPE_LASTSEENEID;
e.row_type = ROW_LASTSEENEID;
e.bg_color = R.drawable.socketclosed_bg;
for(int i = 0; i < data.size(); i++) {
if(data.get(i).row_type == ROW_LASTSEENEID) {
data.remove(i);
}
}
if(min_eid > 0 && last_seen_eid > 0 && min_eid >= last_seen_eid) {
lastSeenEidMarkerPosition = 0;
} else {
for(int i = data.size() - 1; i >= 0; i--) {
if(data.get(i).eid <= last_seen_eid) {
lastSeenEidMarkerPosition = i;
break;
}
}
if(lastSeenEidMarkerPosition != data.size() - 1) {
if(lastSeenEidMarkerPosition > 0 && data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP)
lastSeenEidMarkerPosition--;
if(lastSeenEidMarkerPosition > 0)
data.add(lastSeenEidMarkerPosition + 1, e);
} else {
lastSeenEidMarkerPosition = -1;
}
}
return lastSeenEidMarkerPosition;
}
public void clearLastSeenEIDMarker() {
for(int i = 0; i < data.size(); i++) {
if(data.get(i).row_type == ROW_LASTSEENEID) {
data.remove(i);
}
}
lastSeenEidMarkerPosition = -1;
}
public int getLastSeenEIDPosition() {
return lastSeenEidMarkerPosition;
}
public int getUnreadHighlightsAbovePosition(int pos) {
int count = 0;
Iterator<Integer> i = unseenHighlightPositions.iterator();
while(i.hasNext()) {
Integer p = i.next();
if(p < pos)
break;
count++;
}
return unseenHighlightPositions.size() - count;
}
public synchronized void addItem(long eid, EventsDataSource.Event e) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
int insert_pos = -1;
SimpleDateFormat formatter = null;
if(e.timestamp == null || e.timestamp.length() == 0) {
formatter = new SimpleDateFormat("h:mm a");
if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
JSONObject prefs = conn.getUserInfo().prefs;
if(prefs.has("time-24hr") && prefs.getBoolean("time-24hr")) {
if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds"))
formatter = new SimpleDateFormat("H:mm:ss");
else
formatter = new SimpleDateFormat("H:mm");
} else if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) {
formatter = new SimpleDateFormat("h:mm:ss a");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
e.timestamp = formatter.format(calendar.getTime());
}
e.group_eid = currentCollapsedEid;
if(e.group_msg != null && e.html == null)
e.html = e.group_msg;
/*if(e.html != null) {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, mServer);
}*/
if(e.day < 1) {
e.day = calendar.get(Calendar.DAY_OF_YEAR);
}
if(currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group
calendar.setTimeInMillis(e.eid / 1000);
lastDay = e.day;
data.remove(currentGroupPosition);
data.add(currentGroupPosition, e);
insert_pos = currentGroupPosition;
} else if(eid > max_eid || data.size() == 0 || eid > data.get(data.size()-1).eid) { //Message at the bottom
if(data.size() > 0) {
lastDay = data.get(data.size()-1).day;
} else {
lastDay = 0;
}
max_eid = eid;
data.add(e);
insert_pos = data.size() - 1;
} else if(min_eid > eid) { //Message goes on top
if(data.size() > 1) {
lastDay = data.get(1).day;
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline
data.add(0, e);
insert_pos = 0;
} else { //Insert below the dateline
data.add(1, e);
insert_pos = 1;
}
} else {
data.add(0, e);
insert_pos = 0;
}
} else {
int i = 0;
for(EventsDataSource.Event e1 : data) {
if(e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid) { //Insert the message
if(i > 0 && data.get(i-1).row_type != ROW_TIMESTAMP) {
lastDay = data.get(i-1).day;
data.add(i, e);
insert_pos = i;
break;
} else { //There was a date line above our insertion point
lastDay = e1.day;
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline
if(i > 1) {
lastDay = data.get(i-2).day;
} else {
//We're above the first dateline, so we'll need to put a new one on top!
lastDay = 0;
}
data.add(i-1, e);
insert_pos = i-1;
} else { //Insert below the dateline
data.add(i, e);
insert_pos = i;
}
break;
}
} else if(e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message
lastDay = calendar.get(Calendar.DAY_OF_YEAR);
data.remove(i);
data.add(i, e);
insert_pos = i;
break;
}
i++;
}
}
if(insert_pos == -1) {
Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html);
return;
}
if(eid > last_seen_eid && e.highlight)
unseenHighlightPositions.add(insert_pos);
if(eid < min_eid || min_eid == 0)
min_eid = eid;
if(eid == currentCollapsedEid && e.eid == eid) {
currentGroupPosition = insert_pos;
} else if(currentCollapsedEid == -1) {
currentGroupPosition = -1;
}
if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) {
if(formatter == null)
formatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
else
formatter.applyPattern("EEEE, MMMM dd, yyyy");
EventsDataSource.Event d = EventsDataSource.getInstance().new Event();
d.type = TYPE_TIMESTAMP;
d.row_type = ROW_TIMESTAMP;
d.eid = eid;
d.timestamp = formatter.format(calendar.getTime());
d.bg_color = R.drawable.row_timestamp_bg;
data.add(insert_pos, d);
lastDay = calendar.get(Calendar.DAY_OF_YEAR);
if(currentGroupPosition > -1)
currentGroupPosition++;
}
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return data.get(position).eid;
}
public void format() {
for(int i = 0; i < data.size(); i++) {
EventsDataSource.Event e = data.get(i);
synchronized(e) {
if(e.html != null) {
try {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, mServer);
} catch (Exception ex) {
}
}
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
EventsDataSource.Event e = data.get(position);
synchronized (e) {
View row = convertView;
ViewHolder holder;
if(row != null && ((ViewHolder)row.getTag()).type != e.row_type)
row = null;
if (row == null) {
LayoutInflater inflater = ctx.getLayoutInflater(null);
if(e.row_type == ROW_BACKLOGMARKER)
row = inflater.inflate(R.layout.row_backlogmarker, null);
else if(e.row_type == ROW_TIMESTAMP)
row = inflater.inflate(R.layout.row_timestamp, null);
else if(e.row_type == ROW_SOCKETCLOSED)
row = inflater.inflate(R.layout.row_socketclosed, null);
else if(e.row_type == ROW_LASTSEENEID)
row = inflater.inflate(R.layout.row_lastseeneid, null);
else
row = inflater.inflate(R.layout.row_message, null);
holder = new ViewHolder();
holder.timestamp = (TextView) row.findViewById(R.id.timestamp);
holder.message = (TextView) row.findViewById(R.id.message);
holder.expandable = (ImageView) row.findViewById(R.id.expandable);
holder.failed = (ImageView) row.findViewById(R.id.failed);
holder.type = e.row_type;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
row.setOnClickListener(new OnItemClickListener(position));
if(e.row_type == ROW_MESSAGE) {
if(e.bg_color == R.color.message_bg)
row.setBackgroundDrawable(null);
else
row.setBackgroundResource(e.bg_color);
}
if(holder.timestamp != null) {
holder.timestamp.setText(e.timestamp);
holder.timestamp.setMinWidth(timestamp_width);
}
if(e.row_type == ROW_SOCKETCLOSED) {
if(e.msg.length() > 0) {
holder.timestamp.setVisibility(View.VISIBLE);
holder.message.setVisibility(View.VISIBLE);
} else {
holder.timestamp.setVisibility(View.GONE);
holder.message.setVisibility(View.GONE);
}
}
if(e.html != null && e.formatted == null) {
e.html = ColorFormatter.irc_to_html(e.html);
e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, mServer);
}
if(holder.message != null && e.html != null) {
holder.message.setMovementMethod(linkMovementMethodNoLongPress);
holder.message.setOnClickListener(new OnItemClickListener(position));
if(e.msg != null && e.msg.startsWith("<pre>"))
holder.message.setTypeface(Typeface.MONOSPACE);
else
holder.message.setTypeface(Typeface.DEFAULT);
try {
holder.message.setTextColor(getResources().getColorStateList(e.color));
} catch (Exception e1) {
}
holder.message.setText(e.formatted);
}
if(holder.expandable != null) {
if(e.group_eid > 0 && (e.group_eid != e.eid || expandedSectionEids.contains(e.group_eid))) {
if(expandedSectionEids.contains(e.group_eid)) {
if(e.group_eid == e.eid + 1) {
holder.expandable.setImageResource(R.drawable.bullet_toggle_minus);
row.setBackgroundResource(R.color.status_bg);
} else {
holder.expandable.setImageResource(R.drawable.tiny_plus);
row.setBackgroundResource(R.color.expanded_row_bg);
}
} else {
holder.expandable.setImageResource(R.drawable.bullet_toggle_plus);
}
holder.expandable.setVisibility(View.VISIBLE);
} else {
holder.expandable.setVisibility(View.GONE);
}
}
if(holder.failed != null)
holder.failed.setVisibility(e.failed?View.VISIBLE:View.GONE);
return row;
}
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.messageview, container, false);
connecting = v.findViewById(R.id.connecting);
errorMsg = (TextView)v.findViewById(R.id.errorMsg);
connectingMsg = (TextView)v.findViewById(R.id.connectingMsg);
progressBar = (ProgressBar)v.findViewById(R.id.connectingProgress);
statusView = (TextView)v.findViewById(R.id.statusView);
statusView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mServer != null && mServer.status != null && mServer.status.equalsIgnoreCase("disconnected")) {
conn.reconnect(cid);
}
}
});
awayView = v.findViewById(R.id.away);
awayView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
conn.back(cid);
}
});
awayTxt = (TextView)v.findViewById(R.id.awayTxt);
unreadBottomView = v.findViewById(R.id.unreadBottom);
unreadBottomView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getListView().setSelection(adapter.getCount() - 1);
}
});
unreadBottomLabel = (TextView)v.findViewById(R.id.unread);
highlightsBottomLabel = (TextView)v.findViewById(R.id.highlightsBottom);
unreadTopView = v.findViewById(R.id.unreadTop);
unreadTopView.setVisibility(View.GONE);
unreadTopView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(adapter.getLastSeenEIDPosition() > 0) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
unreadTopView.setVisibility(View.GONE);
}
getListView().setSelection(adapter.getLastSeenEIDPosition());
}
});
unreadTopLabel = (TextView)v.findViewById(R.id.unreadTopText);
highlightsTopLabel = (TextView)v.findViewById(R.id.highlightsTop);
Button b = (Button)v.findViewById(R.id.markAsRead);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
unreadTopView.setVisibility(View.GONE);
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
});
globalMsgView = v.findViewById(R.id.globalMessageView);
globalMsg = (TextView)v.findViewById(R.id.globalMessageTxt);
b = (Button)v.findViewById(R.id.dismissGlobalMessage);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(conn != null)
conn.globalMsg = null;
update_global_msg();
}
});
((ListView)v.findViewById(android.R.id.list)).setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
if(pos > 1 && pos <= adapter.data.size()) {
longPressOverride = mListener.onMessageLongClicked(adapter.data.get(pos - 1));
return longPressOverride;
} else {
return false;
}
}
});
spinner = (ProgressBar)v.findViewById(R.id.spinner);
return v;
}
public void showSpinner(boolean show) {
if(show) {
AlphaAnimation anim = new AlphaAnimation(0, 1);
anim.setDuration(150);
anim.setFillAfter(true);
spinner.setAnimation(anim);
spinner.setVisibility(View.VISIBLE);
} else {
AlphaAnimation anim = new AlphaAnimation(1, 0);
anim.setDuration(150);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
spinner.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
spinner.setAnimation(anim);
}
}
private OnScrollListener mOnScrollListener = new OnScrollListener() {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(!ready)
return;
if(connecting.getVisibility() == View.VISIBLE)
return;
if(headerView != null && min_eid > 0 && conn.ready) {
if(firstVisibleItem == 0 && !requestingBacklog && headerView.getVisibility() == View.VISIBLE && bid != -1 && conn.getState() == NetworkConnection.STATE_CONNECTED) {
requestingBacklog = true;
conn.request_backlog(cid, bid, earliest_eid);
}
}
if(unreadBottomView != null && adapter != null && adapter.data.size() > 0) {
if(firstVisibleItem + visibleItemCount == totalItemCount) {
unreadBottomView.setVisibility(View.GONE);
if(unreadTopView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
newMsgs = 0;
newMsgTime = 0;
newHighlights = 0;
}
}
if(firstVisibleItem + visibleItemCount < totalItemCount) {
scrolledUp = true;
} else {
scrolledUp = false;
}
if(adapter != null && adapter.data.size() > 0 && unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) {
mUpdateTopUnreadRunnable.run();
int markerPos = -1;
if(adapter != null)
markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 1 && getListView().getFirstVisiblePosition() <= markerPos) {
unreadTopView.setVisibility(View.GONE);
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null && savedInstanceState.containsKey("cid")) {
cid = savedInstanceState.getInt("cid");
bid = savedInstanceState.getInt("bid");
name = savedInstanceState.getString("name");
last_seen_eid = savedInstanceState.getLong("last_seen_eid");
min_eid = savedInstanceState.getLong("min_eid");
type = savedInstanceState.getString("type");
scrolledUp = savedInstanceState.getBoolean("scrolledUp");
backlog_eid = savedInstanceState.getLong("backlog_eid");
//TODO: serialize the adapter data
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (MessageViewListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement MessageViewListener");
}
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt("cid", cid);
state.putInt("bid", bid);
state.putLong("last_seen_eid", last_seen_eid);
state.putLong("min_eid", min_eid);
state.putString("name", name);
state.putString("type", type);
state.putBoolean("scrolledUp", scrolledUp);
state.putLong("backlog_eid", backlog_eid);
//TODO: serialize the adapter data
}
@Override
public void setArguments(Bundle args) {
ready = false;
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = null;
if(tapTimer != null)
tapTimer.cancel();
tapTimer = null;
cid = args.getInt("cid", 0);
if(bid == -1 || (args.containsKey("bid") && args.getInt("bid", 0) != bid)) {
dirty = true;
}
bid = args.getInt("bid", 0);
last_seen_eid = args.getLong("last_seen_eid", 0);
min_eid = args.getLong("min_eid", 0);
name = args.getString("name");
type = args.getString("type");
scrolledUp = false;
requestingBacklog = false;
ready = false;
avgInsertTime = 0;
newMsgs = 0;
newMsgTime = 0;
newHighlights = 0;
earliest_eid = 0;
backlog_eid = 0;
currentCollapsedEid = -1;
lastCollapsedDay = -1;
mServer = ServersDataSource.getInstance().getServer(cid);
if(mServer != null) {
ignore.setIgnores(mServer.ignores);
if(mServer.away != null && mServer.away.length() > 0) {
awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + mServer.away + ")"))).toString());
awayView.setVisibility(View.VISIBLE);
} else {
awayView.setVisibility(View.GONE);
}
update_status(mServer.status, mServer.fail_info);
}
if(unreadTopView != null)
unreadTopView.setVisibility(View.GONE);
if(headerView != null) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)headerView.getLayoutParams();
lp.topMargin = 0;
headerView.setLayoutParams(lp);
lp = (ViewGroup.MarginLayoutParams)backlogFailed.getLayoutParams();
lp.topMargin = 0;
backlogFailed.setLayoutParams(lp);
if(EventsDataSource.getInstance().getEventsForBuffer(bid) != null) {
requestingBacklog = true;
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
} else {
if(bid == -1 || min_eid == 0 || earliest_eid == min_eid || conn.getState() != NetworkConnection.STATE_CONNECTED || !conn.ready) {
headerView.setVisibility(View.GONE);
} else {
headerView.setVisibility(View.VISIBLE);
}
adapter.clear();
adapter.notifyDataSetInvalidated();
mListener.onMessageViewReady();
ready = true;
}
}
}, 200);
}
}
private synchronized void insertEvent(EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(event) {
try {
long start = System.currentTimeMillis();
if(min_eid == 0)
min_eid = event.eid;
if(event.eid <= min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !this.type.equalsIgnoreCase("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(bid)) && expandMap.getBoolean(String.valueOf(bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(type.equalsIgnoreCase("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
if(!showChan)
event.chan = name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equalsIgnoreCase("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equalsIgnoreCase("user_channel_mode")) {
group_msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equalsIgnoreCase("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equalsIgnoreCase("user_channel_mode")) {
msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equalsIgnoreCase("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equalsIgnoreCase("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equalsIgnoreCase("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> " + event.msg + "</i>";
} else if(type.equalsIgnoreCase("notice")) {
- event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ";
+ if(event.from != null && event.from.length() > 0)
+ event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ";
+ else
+ event.html = "";
if(this.type.equalsIgnoreCase("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equalsIgnoreCase("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> (" + event.hostmask + ")";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equalsIgnoreCase("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equalsIgnoreCase("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && scrolledUp && !event.self && EventsDataSource.getInstance().isImportant(event, type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class OnItemClickListener implements OnClickListener {
private int pos;
OnItemClickListener(int position){
pos = position;
}
@Override
public void onClick(View arg0) {
longPressOverride = false;
if(pos < 0 || pos >= adapter.data.size())
return;
if(adapter != null) {
if(tapTimer != null) {
tapTimer.cancel();
tapTimer = null;
mListener.onMessageDoubleClicked(adapter.data.get(pos));
} else {
Timer t = new Timer();
t.schedule(new TimerTask() {
int position = pos;
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
if(adapter != null && adapter.data != null && position < adapter.data.size()) {
EventsDataSource.Event e = adapter.data.get(position);
if(e != null) {
if(e.type.equals("channel_invite")) {
conn.join(cid, e.old_nick, null);
} else if(e.type.equals("callerid")) {
conn.say(cid, null, "/accept " + e.from);
BuffersDataSource b = BuffersDataSource.getInstance();
BuffersDataSource.Buffer buffer = b.getBufferByName(cid, e.from);
if(buffer != null) {
mListener.onBufferSelected(buffer.cid, buffer.bid, buffer.name, buffer.last_seen_eid, buffer.min_eid,
buffer.type, 1, buffer.archived, "connected_ready");
} else {
mListener.onBufferSelected(cid, -1, e.from, 0, 0, "conversation", 1, 0, "connected_ready");
}
} else {
long group = e.group_eid;
if(expandedSectionEids.contains(group))
expandedSectionEids.remove(group);
else if(e.eid != group)
expandedSectionEids.add(group);
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
}
}
}
}
});
tapTimer = null;
}
}, 300);
tapTimer = t;
}
}
}
}
@SuppressWarnings("unchecked")
public void onResume() {
super.onResume();
longPressOverride = false;
ready = false;
getListView().setStackFromBottom(true);
getListView().requestFocus();
if(bid == -1 && cid != -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name);
if(b != null) {
bid = b.bid;
}
}
if(cid != -1) {
mServer = ServersDataSource.getInstance().getServer(cid);
if(mServer != null)
update_status(mServer.status, mServer.fail_info);
}
if(bid != -1) {
dirty = true;
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null)
last_seen_eid = b.last_seen_eid;
}
if(getListView().getHeaderViewsCount() == 0) {
headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null);
headerView = headerViewContainer.findViewById(R.id.progress);
backlogFailed = (TextView)headerViewContainer.findViewById(R.id.backlogFailed);
loadBacklogButton = (Button)headerViewContainer.findViewById(R.id.loadBacklogButton);
loadBacklogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
headerView.setVisibility(View.VISIBLE);
conn.request_backlog(cid, bid, earliest_eid);
}
});
getListView().addHeaderView(headerViewContainer);
}
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
adapter = new MessageAdapter(this);
setListAdapter(adapter);
conn = NetworkConnection.getInstance();
conn.addHandler(mHandler);
if(conn.getState() != NetworkConnection.STATE_CONNECTED || !NetworkConnection.getInstance().ready) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
anim.setDuration(200);
anim.setFillAfter(true);
connecting.startAnimation(anim);
connecting.setVisibility(View.VISIBLE);
}
updateReconnecting();
update_global_msg();
if(mServer != null) {
ignore.setIgnores(mServer.ignores);
if(mServer.away != null && mServer.away.length() > 0) {
awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + mServer.away + ")"))).toString());
awayView.setVisibility(View.VISIBLE);
} else {
awayView.setVisibility(View.GONE);
}
}
if(bid != -1) {
TreeMap<Long,EventsDataSource.Event> events = EventsDataSource.getInstance().getEventsForBuffer((int)bid);
if(events != null && events.size() > 0) {
adapter.clearLastSeenEIDMarker();
events = (TreeMap<Long, EventsDataSource.Event>)events.clone();
BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer((int)bid);
if(backlog_eid > 0) {
EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event();
backlogMarker.eid = backlog_eid;
backlogMarker.type = TYPE_BACKLOGMARKER;
backlogMarker.row_type = ROW_BACKLOGMARKER;
backlogMarker.bg_color = R.color.message_bg;
events.put(backlog_eid, backlogMarker);
}
refresh(events, buffer);
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
headerView.setLayoutParams(lp);
lp = (ViewGroup.MarginLayoutParams)backlogFailed.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
backlogFailed.setLayoutParams(lp);
adapter.notifyDataSetChanged();
if(savedScrollPos > 0)
getListView().setSelection(savedScrollPos);
else
getListView().setSelection(adapter.getCount() - 1);
savedScrollPos = -1;
} else if(conn.getState() != NetworkConnection.STATE_CONNECTED || !conn.ready) {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
} else {
headerView.setVisibility(View.VISIBLE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
ready = true;
}
} else {
if(cid == -1) {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
}
getListView().setOnScrollListener(mOnScrollListener);
}
private class HeartbeatTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
//Log.d("IRCCloud", "Heartbeat task created. Ready: " + ready + " BID: " + bid);
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
if(isCancelled())
return null;
if(connecting.getVisibility() == View.VISIBLE)
return null;
try {
TreeMap<Long, EventsDataSource.Event> events = EventsDataSource.getInstance().getEventsForBuffer(bid);
if(events != null && events.size() > 0) {
Long eid = events.get(events.lastKey()).eid;
if(eid > last_seen_eid && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
if(getActivity() != null && getActivity().getIntent() != null)
getActivity().getIntent().putExtra("last_seen_eid", eid);
NetworkConnection.getInstance().heartbeat(bid, cid, bid, eid);
last_seen_eid = eid;
BuffersDataSource.getInstance().updateLastSeenEid(bid, eid);
}
}
} catch (Exception e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled())
heartbeatTask = null;
}
}
private class FormatTask extends AsyncTaskEx<Void, Void, Void> {
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
adapter.format();
return null;
}
@Override
protected void onPostExecute(Void result) {
}
}
private class RefreshTask extends AsyncTaskEx<Void, Void, Void> {
TreeMap<Long,EventsDataSource.Event> events;
BuffersDataSource.Buffer buffer;
int oldPosition = -1;
int topOffset = -1;
@Override
protected void onPreExecute() {
//Debug.startMethodTracing("refresh");
try {
oldPosition = getListView().getFirstVisiblePosition();
View v = getListView().getChildAt(0);
topOffset = (v == null) ? 0 : v.getTop();
} catch (IllegalStateException e) {
//The list view isn't on screen anymore
cancel(true);
refreshTask = null;
}
}
@SuppressWarnings("unchecked")
@Override
protected Void doInBackground(Void... params) {
buffer = BuffersDataSource.getInstance().getBuffer((int)bid);
long time = System.currentTimeMillis();
events = EventsDataSource.getInstance().getEventsForBuffer((int)bid);
Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms");
if(!isCancelled() && events != null && events.size() > 0) {
events = (TreeMap<Long, EventsDataSource.Event>)events.clone();
if(isCancelled())
return null;
if(events != null && events.size() > 0) {
try {
if(adapter != null && adapter.data.size() > 0 && earliest_eid > events.firstKey()) {
if(oldPosition > 0 && oldPosition == adapter.data.size())
oldPosition--;
EventsDataSource.Event e = adapter.data.get(oldPosition);
if(e != null)
backlog_eid = e.group_eid - 1;
else
backlog_eid = -1;
if(backlog_eid < 0) {
backlog_eid = adapter.getItemId(oldPosition) - 1;
}
EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event();
backlogMarker.eid = backlog_eid;
backlogMarker.type = TYPE_BACKLOGMARKER;
backlogMarker.row_type = ROW_BACKLOGMARKER;
backlogMarker.html = "__backlog__";
backlogMarker.bg_color = R.color.message_bg;
events.put(backlog_eid, backlogMarker);
}
adapter = new MessageAdapter(MessageViewFragment.this);
refresh(events, buffer);
} catch (IndexOutOfBoundsException e) {
return null;
} catch (IllegalStateException e) {
//The list view doesn't exist yet
Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist.");
}
} else if(bid != -1 && min_eid > 0 && conn.ready && conn.getState() == NetworkConnection.STATE_CONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.VISIBLE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(!isCancelled()) {
try {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
headerView.setLayoutParams(lp);
lp = (ViewGroup.MarginLayoutParams)backlogFailed.getLayoutParams();
if(adapter.getLastSeenEIDPosition() == 0)
lp.topMargin = (int)getResources().getDimension(R.dimen.top_bar_height);
else
lp.topMargin = 0;
backlogFailed.setLayoutParams(lp);
setListAdapter(adapter);
if(events != null && events.size() > 0) {
int markerPos = adapter.getBacklogMarkerPosition();
if(markerPos != -1 && requestingBacklog)
getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight());
else if(!scrolledUp)
getListView().setSelection(adapter.getCount() - 1);
else
getListView().setSelectionFromTop(oldPosition, topOffset);
}
new FormatTask().execute((Void)null);
} catch (IllegalStateException e) {
//The list view isn't on screen anymore
}
refreshTask = null;
requestingBacklog = false;
//Debug.stopMethodTracing();
}
}
}
private synchronized void refresh(TreeMap<Long,EventsDataSource.Event> events, BuffersDataSource.Buffer buffer) {
if(conn.getReconnectTimestamp() == 0)
conn.cancel_idle_timer(); //This may take a while...
if(dirty) {
Log.i("IRCCloud", "BID changed, clearing caches");
EventsDataSource.getInstance().clearCacheForBuffer(bid);
dirty = false;
}
collapsedEvents.clear();
currentCollapsedEid = -1;
lastCollapsedDay = -1;
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
try {
JSONObject prefs = conn.getUserInfo().prefs;
timestamp_width = (int)getResources().getDimension(R.dimen.timestamp_base);
if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds"))
timestamp_width += (int)getResources().getDimension(R.dimen.timestamp_seconds);
if(!prefs.has("time-24hr") || !prefs.getBoolean("time-24hr"))
timestamp_width += (int)getResources().getDimension(R.dimen.timestamp_ampm);
} catch (Exception e) {
}
} else {
timestamp_width = getResources().getDimensionPixelSize(R.dimen.timestamp_base) + getResources().getDimensionPixelSize(R.dimen.timestamp_ampm);
}
if(events == null || (events.size() == 0 && min_eid > 0)) {
if(bid != -1 && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
requestingBacklog = true;
mHandler.post(new Runnable() {
@Override
public void run() {
conn.request_backlog(cid, bid, 0);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
} else if(events.size() > 0) {
mServer = ServersDataSource.getInstance().getServer(cid);
if(mServer != null)
ignore.setIgnores(mServer.ignores);
else
ignore.setIgnores(null);
earliest_eid = events.firstKey();
if(events.firstKey() > min_eid && min_eid > 0 && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.VISIBLE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(events.size() > 0) {
avgInsertTime = 0;
//Debug.startMethodTracing("refresh");
long start = System.currentTimeMillis();
Iterator<EventsDataSource.Event> i = events.values().iterator();
EventsDataSource.Event next = i.next();
Calendar calendar = Calendar.getInstance();
while(next != null) {
EventsDataSource.Event e = next;
next = i.hasNext()?i.next():null;
String type = (next == null)?"":next.type;
if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) {
calendar.setTimeInMillis(next.eid / 1000);
insertEvent(e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay);
} else {
insertEvent(e, true, false);
}
}
adapter.insertLastSeenEIDMarker();
Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms");
//Debug.stopMethodTracing();
avgInsertTime = 0;
//adapter.notifyDataSetChanged();
}
}
mHandler.removeCallbacks(mUpdateTopUnreadRunnable);
mHandler.postDelayed(mUpdateTopUnreadRunnable, 100);
if(conn.getReconnectTimestamp() == 0 && conn.getState() == NetworkConnection.STATE_CONNECTED)
conn.schedule_idle_timer();
}
private Runnable mUpdateTopUnreadRunnable = new Runnable() {
@Override
public void run() {
if(adapter != null) {
try {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos >= 0 && getListView().getFirstVisiblePosition() > (markerPos + 1)) {
if(shouldTrackUnread()) {
int highlights = adapter.getUnreadHighlightsAbovePosition(getListView().getFirstVisiblePosition());
int count = (getListView().getFirstVisiblePosition() - markerPos - 1) - highlights;
String txt = "";
if(highlights > 0) {
if(highlights == 1)
txt = "mention";
else if(highlights > 0)
txt = "mentions";
highlightsTopLabel.setText(String.valueOf(highlights));
highlightsTopLabel.setVisibility(View.VISIBLE);
if(count > 0)
txt += " and ";
} else {
highlightsTopLabel.setVisibility(View.GONE);
}
if(markerPos == 0) {
long seconds = (long)Math.ceil((earliest_eid - last_seen_eid) / 1000000.0);
if(seconds < 0) {
if(count < 0) {
unreadTopView.setVisibility(View.GONE);
return;
} else {
if(count == 1)
txt += count + " unread message";
else if(count > 0)
txt += count + " unread messages";
}
} else {
int minutes = (int)Math.ceil(seconds / 60.0);
int hours = (int)Math.ceil(seconds / 60.0 / 60.0);
int days = (int)Math.ceil(seconds / 60.0 / 60.0 / 24.0);
if(hours >= 24) {
if(days == 1)
txt += days + " day of unread messages";
else
txt += days + " days of unread messages";
} else if(hours > 0) {
if(hours == 1)
txt += hours + " hour of unread messages";
else
txt += hours + " hours of unread messages";
} else if(minutes > 0) {
if(minutes == 1)
txt += minutes + " minute of unread messages";
else
txt += minutes + " minutes of unread messages";
} else {
if(seconds == 1)
txt += seconds + " second of unread messages";
else
txt += seconds + " seconds of unread messages";
}
}
} else {
if(count == 1)
txt += count + " unread message";
else if(count > 0)
txt += count + " unread messages";
}
unreadTopLabel.setText(txt);
unreadTopView.setVisibility(View.VISIBLE);
} else {
unreadTopView.setVisibility(View.GONE);
}
} else {
if(markerPos > 0) {
unreadTopView.setVisibility(View.GONE);
if(adapter.data.size() > 0) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
}
}
if(mServer != null)
update_status(mServer.status, mServer.fail_info);
if(mListener != null && !ready)
mListener.onMessageViewReady();
ready = true;
} catch (IllegalStateException e) {
//The list view wasn't on screen yet
}
}
}
};
private boolean shouldTrackUnread() {
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) {
try {
JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread");
if(disabledMap.has(String.valueOf(bid)) && disabledMap.getBoolean(String.valueOf(bid))) {
return false;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
private class UnreadRefreshRunnable implements Runnable {
@Override
public void run() {
update_unread();
}
}
UnreadRefreshRunnable unreadRefreshRunnable = null;
private void update_unread() {
if(unreadRefreshRunnable != null) {
mHandler.removeCallbacks(unreadRefreshRunnable);
unreadRefreshRunnable = null;
}
if(newMsgs > 0) {
/*int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000);
if(minutes < 1)
unreadBottomLabel.setText("Less than a minute of chatter (");
else if(minutes == 1)
unreadBottomLabel.setText("1 minute of chatter (");
else
unreadBottomLabel.setText(minutes + " minutes of chatter (");
if(newMsgs == 1)
unreadBottomLabel.setText(unreadBottomLabel.getText() + "1 message)");
else
unreadBottomLabel.setText(unreadBottomLabel.getText() + (newMsgs + " messages)"));*/
String txt = "";
int msgCnt = newMsgs - newHighlights;
if(newHighlights > 0) {
if(newHighlights == 1)
txt = "mention";
else
txt = "mentions";
if(msgCnt > 0)
txt += " and ";
highlightsBottomLabel.setText(String.valueOf(newHighlights));
highlightsBottomLabel.setVisibility(View.VISIBLE);
} else {
highlightsBottomLabel.setVisibility(View.GONE);
}
if(msgCnt == 1)
txt += msgCnt + " unread message";
else if(msgCnt > 0)
txt += msgCnt + " unread messages";
unreadBottomLabel.setText(txt);
unreadBottomView.setVisibility(View.VISIBLE);
unreadRefreshRunnable = new UnreadRefreshRunnable();
mHandler.postDelayed(unreadRefreshRunnable, 10000);
}
}
private class StatusRefreshRunnable implements Runnable {
String status;
JsonObject fail_info;
public StatusRefreshRunnable(String status, JsonObject fail_info) {
this.status = status;
this.fail_info = fail_info;
}
@Override
public void run() {
update_status(status, fail_info);
}
}
StatusRefreshRunnable statusRefreshRunnable = null;
public static String ordinal(int i) {
String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
private void update_status(String status, JsonObject fail_info) {
if(statusRefreshRunnable != null) {
mHandler.removeCallbacks(statusRefreshRunnable);
statusRefreshRunnable = null;
}
if(status.equals("connected_ready")) {
if(mServer != null && mServer.lag >= 2*1000*1000) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Slow ping response from " + mServer.hostname + " (" + (mServer.lag / 1000 / 1000) + "s)");
} else {
statusView.setVisibility(View.GONE);
statusView.setText("");
}
} else if(status.equals("quitting")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Disconnecting");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("disconnected")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Disconnected. Tap to reconnect.");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("queued")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connection queued");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connecting")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connecting");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connected")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connected");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("connected_joining")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connected: Joining Channels");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
} else if(status.equals("pool_unavailable")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Connection temporarily unavailable");
statusView.setTextColor(getResources().getColor(R.color.status_fail_text));
statusView.setBackgroundResource(R.drawable.status_fail_bg);
} else if(status.equals("waiting_to_retry")) {
try {
statusView.setVisibility(View.VISIBLE);
long seconds = (fail_info.get("timestamp").getAsLong() + fail_info.get("retry_timeout").getAsLong() - conn.clockOffset) - System.currentTimeMillis()/1000;
if(seconds > 0) {
String text = "Disconnected";
if(fail_info.has("reason") && fail_info.get("reason").getAsString().length() > 0) {
String reason = fail_info.get("reason").getAsString();
if(reason.equalsIgnoreCase("pool_lost")) {
reason = "Connection pool failed";
} else if(reason.equalsIgnoreCase("no_pool")) {
reason = "No available connection pools";
} else if(reason.equalsIgnoreCase("enetdown")) {
reason = "Network down";
} else if(reason.equalsIgnoreCase("etimedout") || reason.equalsIgnoreCase("timeout")) {
reason = "Timed out";
} else if(reason.equalsIgnoreCase("ehostunreach")) {
reason = "Host unreachable";
} else if(reason.equalsIgnoreCase("econnrefused")) {
reason = "Connection refused";
} else if(reason.equalsIgnoreCase("nxdomain")) {
reason = "Invalid hostname";
} else if(reason.equalsIgnoreCase("server_ping_timeout")) {
reason = "PING timeout";
} else if(reason.equalsIgnoreCase("ssl_certificate_error")) {
reason = "SSL certificate error";
} else if(reason.equalsIgnoreCase("ssl_error")) {
reason = "SSL error";
} else if(reason.equalsIgnoreCase("crash")) {
reason = "Connection crashed";
}
text += ": " + reason + ". ";
} else
text += "; ";
text += "Reconnecting in ";
int minutes = (int)(seconds / 60.0);
int hours = (int)(seconds / 60.0 / 60.0);
int days = (int)(seconds / 60.0 / 60.0 / 24.0);
if(days > 0) {
if(days == 1)
text += days + " day.";
else
text += days + " days.";
} else if(hours > 0) {
if(hours == 1)
text += hours + " hour.";
else
text += hours + " hours.";
} else if(minutes > 0) {
if(minutes == 1)
text += minutes + " minute.";
else
text += minutes + " minutes.";
} else {
if(seconds == 1)
text += seconds + " second.";
else
text += seconds + " seconds.";
}
int attempts = fail_info.get("attempts").getAsInt();
if(attempts > 1)
text += " (" + ordinal(attempts) + " attempt)";
statusView.setText(text);
statusView.setTextColor(getResources().getColor(R.color.status_fail_text));
statusView.setBackgroundResource(R.drawable.status_fail_bg);
statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info);
} else {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Ready to connect, waiting our turn…");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
}
mHandler.postDelayed(statusRefreshRunnable, 500);
} catch (Exception e) {
e.printStackTrace();
}
} else if(status.equals("ip_retry")) {
statusView.setVisibility(View.VISIBLE);
statusView.setText("Trying another IP address");
statusView.setTextColor(getResources().getColor(R.color.dark_blue));
statusView.setBackgroundResource(R.drawable.background_blue);
}
}
private void update_global_msg() {
if(globalMsgView != null) {
if(conn != null && conn.globalMsg != null) {
globalMsg.setText(conn.globalMsg);
globalMsgView.setVisibility(View.VISIBLE);
} else {
globalMsgView.setVisibility(View.GONE);
}
}
}
@Override
public void onPause() {
super.onPause();
if(statusRefreshRunnable != null) {
mHandler.removeCallbacks(statusRefreshRunnable);
statusRefreshRunnable = null;
}
if(conn != null)
conn.removeHandler(mHandler);
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, -1);
anim.setDuration(10);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation arg0) {
connecting.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
connecting.startAnimation(anim);
error = null;
try {
if(scrolledUp) {
savedScrollPos = getListView().getFirstVisiblePosition();
} else {
savedScrollPos = -1;
}
getListView().setOnScrollListener(null);
} catch (Exception e) {
savedScrollPos = -1;
}
}
private void updateReconnecting() {
if(conn.getState() == NetworkConnection.STATE_CONNECTED) {
connectingMsg.setText("Loading");
} else if(conn.getState() == NetworkConnection.STATE_CONNECTING || conn.getReconnectTimestamp() > 0) {
progressBar.setIndeterminate(true);
if(connecting.getVisibility() == View.GONE) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0);
anim.setDuration(200);
anim.setFillAfter(true);
connecting.startAnimation(anim);
connecting.setVisibility(View.VISIBLE);
}
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED && conn.getReconnectTimestamp() > 0) {
String plural = "";
int seconds = (int)((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000);
if(seconds != 1)
plural = "s";
if(seconds < 1) {
connectingMsg.setText("Connecting");
errorMsg.setVisibility(View.GONE);
} else if(seconds > 10 && error != null) {
connectingMsg.setText("Reconnecting in " + seconds + " second" + plural);
errorMsg.setText(error);
errorMsg.setVisibility(View.VISIBLE);
} else {
connectingMsg.setText("Reconnecting in " + seconds + " second" + plural);
errorMsg.setVisibility(View.GONE);
error = null;
}
try {
if(countdownTimer != null)
countdownTimer.cancel();
countdownTimer = new Timer();
countdownTimer.schedule( new TimerTask(){
public void run() {
if(conn.getState() == NetworkConnection.STATE_DISCONNECTED) {
mHandler.post(new Runnable() {
@Override
public void run() {
updateReconnecting();
}
});
}
countdownTimer = null;
}
}, 1000);
} catch (Exception e) {
}
} else {
connectingMsg.setText("Connecting");
error = null;
errorMsg.setVisibility(View.GONE);
}
} else {
connectingMsg.setText("Offline");
progressBar.setIndeterminate(false);
progressBar.setProgress(0);
}
}
private final Handler mHandler = new Handler() {
IRCCloudJSONObject e;
public void handleMessage(Message msg) {
switch (msg.what) {
case NetworkConnection.EVENT_DEBUG:
errorMsg.setVisibility(View.VISIBLE);
errorMsg.setText(msg.obj.toString());
break;
case NetworkConnection.EVENT_PROGRESS:
float progress = (Float)msg.obj;
progressBar.setIndeterminate(false);
progressBar.setProgress((int)progress);
break;
case NetworkConnection.EVENT_BACKLOG_FAILED:
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.VISIBLE);
loadBacklogButton.setVisibility(View.VISIBLE);
break;
case NetworkConnection.EVENT_BACKLOG_END:
if(connecting.getVisibility() == View.VISIBLE) {
TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1);
anim.setDuration(200);
anim.setFillAfter(true);
anim.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation arg0) {
connecting.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationStart(Animation animation) {
}
});
connecting.startAnimation(anim);
error = null;
}
if(bid != -1) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null)
last_seen_eid = b.last_seen_eid;
}
case NetworkConnection.EVENT_CONNECTIVITY:
updateReconnecting();
case NetworkConnection.EVENT_USERINFO:
dirty = true;
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
break;
case NetworkConnection.EVENT_FAILURE_MSG:
IRCCloudJSONObject o = (IRCCloudJSONObject)msg.obj;
try {
error = o.getString("message");
if(error.equals("temp_unavailable"))
error = "Your account is temporarily unavailable";
updateReconnecting();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_CONNECTIONLAG:
try {
IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj;
if(mServer != null && object.cid() == cid) {
update_status(mServer.status, mServer.fail_info);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_STATUSCHANGED:
try {
IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj;
if(object.cid() == cid) {
update_status(object.getString("new_status"), object.getJsonObject("fail_info"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case NetworkConnection.EVENT_MAKEBUFFER:
BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj;
if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) {
bid = buffer.bid;
min_eid = buffer.min_eid;
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
}
break;
case NetworkConnection.EVENT_SETIGNORES:
e = (IRCCloudJSONObject)msg.obj;
if(e.cid() == cid) {
if(refreshTask != null)
refreshTask.cancel(true);
refreshTask = new RefreshTask();
refreshTask.execute((Void)null);
}
break;
case NetworkConnection.EVENT_HEARTBEATECHO:
if(adapter != null && adapter.data.size() > 0) {
BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid);
if(b != null && last_seen_eid != b.last_seen_eid) {
last_seen_eid = b.last_seen_eid;
if(last_seen_eid == adapter.data.get(adapter.data.size() - 1).eid || !shouldTrackUnread()) {
unreadTopView.setVisibility(View.GONE);
}
}
}
break;
case NetworkConnection.EVENT_CHANNELTOPIC:
case NetworkConnection.EVENT_JOIN:
case NetworkConnection.EVENT_PART:
case NetworkConnection.EVENT_NICKCHANGE:
case NetworkConnection.EVENT_QUIT:
case NetworkConnection.EVENT_KICK:
case NetworkConnection.EVENT_CHANNELMODE:
case NetworkConnection.EVENT_SELFDETAILS:
case NetworkConnection.EVENT_USERMODE:
case NetworkConnection.EVENT_USERCHANNELMODE:
e = (IRCCloudJSONObject)msg.obj;
if(e.bid() == bid) {
EventsDataSource.Event event = EventsDataSource.getInstance().getEvent(e.eid(), e.bid());
insertEvent(event, false, false);
}
break;
case NetworkConnection.EVENT_BUFFERMSG:
EventsDataSource.Event event = (EventsDataSource.Event)msg.obj;
if(event.bid == bid) {
if(event.from != null && event.from.equals(name) && event.reqid == -1) {
adapter.clearPending();
} else if(event.reqid != -1) {
for(int i = 0; i < adapter.data.size(); i++) {
EventsDataSource.Event e = adapter.data.get(i);
if(e.reqid == event.reqid && e.pending) {
if(i > 1) {
EventsDataSource.Event p = adapter.data.get(i-1);
if(p.row_type == ROW_TIMESTAMP) {
adapter.data.remove(p);
i--;
}
}
adapter.data.remove(e);
i--;
}
}
}
insertEvent(event, false, false);
}
break;
case NetworkConnection.EVENT_AWAY:
case NetworkConnection.EVENT_SELFBACK:
if(mServer != null) {
if(mServer.away != null && mServer.away.length() > 0) {
awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + mServer.away + ")"))).toString());
awayView.setVisibility(View.VISIBLE);
} else {
awayView.setVisibility(View.GONE);
}
}
break;
case NetworkConnection.EVENT_GLOBALMSG:
update_global_msg();
break;
default:
break;
}
}
};
public interface MessageViewListener extends OnBufferSelectedListener {
public void onMessageViewReady();
public boolean onMessageLongClicked(EventsDataSource.Event event);
public void onMessageDoubleClicked(EventsDataSource.Event event);
}
}
| true | true | private synchronized void insertEvent(EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(event) {
try {
long start = System.currentTimeMillis();
if(min_eid == 0)
min_eid = event.eid;
if(event.eid <= min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !this.type.equalsIgnoreCase("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(bid)) && expandMap.getBoolean(String.valueOf(bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(type.equalsIgnoreCase("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
if(!showChan)
event.chan = name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equalsIgnoreCase("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equalsIgnoreCase("user_channel_mode")) {
group_msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equalsIgnoreCase("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equalsIgnoreCase("user_channel_mode")) {
msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equalsIgnoreCase("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equalsIgnoreCase("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equalsIgnoreCase("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> " + event.msg + "</i>";
} else if(type.equalsIgnoreCase("notice")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ";
if(this.type.equalsIgnoreCase("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equalsIgnoreCase("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> (" + event.hostmask + ")";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equalsIgnoreCase("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equalsIgnoreCase("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && scrolledUp && !event.self && EventsDataSource.getInstance().isImportant(event, type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| private synchronized void insertEvent(EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) {
synchronized(event) {
try {
long start = System.currentTimeMillis();
if(min_eid == 0)
min_eid = event.eid;
if(event.eid <= min_eid) {
mHandler.post(new Runnable() {
@Override
public void run() {
headerView.setVisibility(View.GONE);
backlogFailed.setVisibility(View.GONE);
loadBacklogButton.setVisibility(View.GONE);
}
});
}
if(event.eid < earliest_eid)
earliest_eid = event.eid;
String type = event.type;
long eid = event.eid;
if(type.startsWith("you_"))
type = type.substring(4);
if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode")) {
boolean shouldExpand = false;
boolean showChan = !this.type.equalsIgnoreCase("channel");
if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) {
JSONObject hiddenMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-hideJoinPart"))
hiddenMap = conn.getUserInfo().prefs.getJSONObject("buffer-hideJoinPart");
}
if(hiddenMap != null && hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) {
adapter.removeItem(event.eid);
if(!backlog)
adapter.notifyDataSetChanged();
return;
}
JSONObject expandMap = null;
if(this.type.equalsIgnoreCase("channel")) {
if(conn.getUserInfo().prefs.has("channel-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("channel-expandJoinPart");
} else {
if(conn.getUserInfo().prefs.has("buffer-expandJoinPart"))
expandMap = conn.getUserInfo().prefs.getJSONObject("buffer-expandJoinPart");
}
if(expandMap != null && expandMap.has(String.valueOf(bid)) && expandMap.getBoolean(String.valueOf(bid))) {
shouldExpand = true;
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(eid / 1000);
if(shouldExpand)
expandedSectionEids.clear();
if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || shouldExpand) {
collapsedEvents.clear();
currentCollapsedEid = eid;
lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR);
}
if(type.equalsIgnoreCase("user_channel_mode")) {
event.color = R.color.row_message_label;
event.bg_color = R.color.status_bg;
} else {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
if(!showChan)
event.chan = name;
if(!collapsedEvents.addEvent(event))
collapsedEvents.clear();
String msg;
if(expandedSectionEids.contains(currentCollapsedEid)) {
CollapsedEventsList c = new CollapsedEventsList();
c.addEvent(event);
msg = c.getCollapsedMessage(showChan);
if(!nextIsGrouped) {
String group_msg = collapsedEvents.getCollapsedMessage(showChan);
if(group_msg == null && type.equalsIgnoreCase("nickchange")) {
group_msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(group_msg == null && type.equalsIgnoreCase("user_channel_mode")) {
group_msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
EventsDataSource.Event heading = EventsDataSource.getInstance().new Event();
heading.type = "__expanded_group_heading__";
heading.cid = event.cid;
heading.bid = event.bid;
heading.eid = currentCollapsedEid - 1;
heading.group_msg = group_msg;
heading.color = R.color.timestamp;
heading.bg_color = R.color.message_bg;
heading.linkify = false;
adapter.addItem(currentCollapsedEid - 1, heading);
}
event.timestamp = null;
} else {
msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(showChan);
}
if(msg == null && type.equalsIgnoreCase("nickchange")) {
msg = event.old_nick + " → <b>" + event.nick + "</b>";
}
if(msg == null && type.equalsIgnoreCase("user_channel_mode")) {
msg = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>";
currentCollapsedEid = eid;
}
if(!expandedSectionEids.contains(currentCollapsedEid)) {
if(eid != currentCollapsedEid) {
event.color = R.color.timestamp;
event.bg_color = R.color.message_bg;
}
eid = currentCollapsedEid;
}
event.group_msg = msg;
event.html = null;
event.formatted = null;
event.linkify = false;
} else {
currentCollapsedEid = -1;
collapsedEvents.clear();
if(event.html == null) {
if(event.from != null)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> " + event.msg;
else
event.html = event.msg;
}
}
String from = event.from;
if(from == null || from.length() == 0)
from = event.nick;
if(from != null && event.hostmask != null && !type.equalsIgnoreCase("user_channel_mode") && !type.contains("kicked")) {
String usermask = from + "!" + event.hostmask;
if(ignore.match(usermask)) {
if(unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) {
if(heartbeatTask != null)
heartbeatTask.cancel(true);
heartbeatTask = new HeartbeatTask();
heartbeatTask.execute((Void)null);
}
return;
}
}
if(type.equalsIgnoreCase("channel_mode")) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
} else if(type.equalsIgnoreCase("buffer_me_msg")) {
event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> " + event.msg + "</i>";
} else if(type.equalsIgnoreCase("notice")) {
if(event.from != null && event.from.length() > 0)
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ";
else
event.html = "";
if(this.type.equalsIgnoreCase("console") && event.to_chan && event.chan != null && event.chan.length() > 0) {
event.html += event.chan + "﹕ " + event.msg;
} else {
event.html += event.msg;
}
} else if(type.equalsIgnoreCase("kicked_channel")) {
event.html = "← ";
if(event.type.startsWith("you_"))
event.html += "You";
else
event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null) + "</b>";
if(event.type.startsWith("you_"))
event.html += " were";
else
event.html += " was";
event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b> (" + event.hostmask + ")";
if(event.msg != null && event.msg.length() > 0)
event.html += ": " + event.msg;
} else if(type.equalsIgnoreCase("callerid")) {
event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode) + "</b> ("+ event.hostmask + ") " + event.msg + " Tap to accept.";
} else if(type.equalsIgnoreCase("channel_mode_list_change")) {
if(event.from.length() == 0) {
if(event.nick != null && event.nick.length() > 0)
event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode) + "</b>";
else if(event.server != null && event.server.length() > 0)
event.html = event.msg + " by the server <b>" + event.server + "</b>";
}
}
adapter.addItem(eid, event);
if(!backlog)
adapter.notifyDataSetChanged();
long time = (System.currentTimeMillis() - start);
if(avgInsertTime == 0)
avgInsertTime = time;
avgInsertTime += time;
avgInsertTime /= 2.0;
//Log.i("IRCCloud", "Average insert time: " + avgInsertTime);
if(!backlog && scrolledUp && !event.self && EventsDataSource.getInstance().isImportant(event, type)) {
if(newMsgTime == 0)
newMsgTime = System.currentTimeMillis();
newMsgs++;
if(event.highlight)
newHighlights++;
update_unread();
}
if(!backlog && !scrolledUp) {
getListView().setSelection(adapter.getCount() - 1);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
getListView().setSelection(adapter.getCount() - 1);
} catch (Exception e) {
//List view isn't ready yet
}
}
}, 200);
}
if(!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) {
Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit();
editor.putBoolean("mentionTip", true);
editor.commit();
}
if(!backlog) {
int markerPos = adapter.getLastSeenEIDPosition();
if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) {
unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/src/main/java/com/twilio/sdk/resource/list/UsageTriggerList.java b/src/main/java/com/twilio/sdk/resource/list/UsageTriggerList.java
index 00ce5b31e..0e0e3b6b0 100644
--- a/src/main/java/com/twilio/sdk/resource/list/UsageTriggerList.java
+++ b/src/main/java/com/twilio/sdk/resource/list/UsageTriggerList.java
@@ -1,68 +1,68 @@
package com.twilio.sdk.resource.list;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.TwilioRestResponse;
import com.twilio.sdk.resource.ListResource;
import com.twilio.sdk.resource.factory.UsageTriggerFactory;
import com.twilio.sdk.resource.instance.UsageRecord;
import com.twilio.sdk.resource.instance.UsageTrigger;
import java.util.Map;
public class UsageTriggerList extends ListResource<UsageTrigger> implements UsageTriggerFactory {
/**
* Instantiates a new usage trigger list.
*
* @param client the client
*/
public UsageTriggerList(TwilioRestClient client) {
super(client);
}
/**
* Instantiates a new usage trigger list.
*
* @param client the client
* @param filters the filters
*/
public UsageTriggerList(TwilioRestClient client,
Map<String, String> filters) {
super(client, filters);
}
/* (non-Javadoc)
* @see com.twilio.sdk.resource.Resource#getResourceLocation()
*/
@Override
protected String getResourceLocation() {
return "/" + TwilioRestClient.DEFAULT_VERSION + "/Accounts/"
+ this.getRequestAccountSid() + "/Usage/Triggers";
}
/* (non-Javadoc)
* @see com.twilio.sdk.resource.ListResource#makeNew(com.twilio.sdk.TwilioRestClient, java.util.Map)
*/
@Override
protected UsageTrigger makeNew(TwilioRestClient client,
Map<String, Object> properties) {
return new UsageTrigger(client, properties);
}
/* (non-Javadoc)
* @see com.twilio.sdk.resource.ListResource#getListKey()
*/
@Override
protected String getListKey() {
return "UsageTriggers";
}
@Override
public UsageTrigger create(Map<String, String> params) throws TwilioRestException {
TwilioRestResponse response = this.getClient().safeRequest(
this.getResourceLocation(), "POST", params);
- return makeNew(this.getClient(), (Map<String, Object>) response.toMap().get("UsageTrigger"));
+ return makeNew(this.getClient(), (Map<String, Object>) response.toMap().get("UsageTriggers"));
}
}
| true | true | public UsageTrigger create(Map<String, String> params) throws TwilioRestException {
TwilioRestResponse response = this.getClient().safeRequest(
this.getResourceLocation(), "POST", params);
return makeNew(this.getClient(), (Map<String, Object>) response.toMap().get("UsageTrigger"));
}
| public UsageTrigger create(Map<String, String> params) throws TwilioRestException {
TwilioRestResponse response = this.getClient().safeRequest(
this.getResourceLocation(), "POST", params);
return makeNew(this.getClient(), (Map<String, Object>) response.toMap().get("UsageTriggers"));
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
index 0418e672..a5942ca7 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
@@ -1,537 +1,542 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2002 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.Context;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessages;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
/**
* Responsible for walking an abstract syntax tree and notifying interested
* checks at each each node.
*
* @author <a href="mailto:[email protected]">Oliver Burn</a>
* @version 1.0
*/
public final class TreeWalker
extends AbstractFileSetCheck
{
/**
* Overrides ANTLR error reporting so we completely control
* checkstyle's output during parsing. This is important because
* we try parsing with several grammers (with/without support for
* <code>assert</code>). We must not write any error messages when
* parsing fails because with the next grammar it might succeed
* and the user will be confused.
*/
private static class SilentJava14Recognizer
extends GeneratedJava14Recognizer
{
/**
* Creates a new <code>SilentJava14Recognizer</code> instance.
*
* @param aLexer the tokenstream the recognizer operates on.
*/
private SilentJava14Recognizer(GeneratedJava14Lexer aLexer)
{
super(aLexer);
}
/**
* Parser error-reporting function, does nothing.
* @param aRex the exception to be reported
*/
public void reportError(RecognitionException aRex)
{
}
/**
* Parser error-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportError(String aMsg)
{
}
/**
* Parser warning-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportWarning(String aMsg)
{
}
}
/** maps from token name to checks */
private final Map mTokenToChecks = new HashMap();
/** all the registered checks */
private final Set mAllChecks = new HashSet();
/** collects the error messages */
private final LocalizedMessages mMessages;
/** the distance between tab stops */
private int mTabWidth = 8;
/** cache file **/
private PropertyCacheFile mCache = new PropertyCacheFile(null, null);
/** class loader to resolve classes with. **/
private ClassLoader mClassLoader;
/** context of child components */
private Context mChildContext;
/**
* HACK - a reference to a private "mParent" field in DetailAST.
* Don't do this at home!
*/
private Field mDetailASTmParent;
/** a factory for creating submodules (i.e. the Checks) */
private ModuleFactory mModuleFactory;
/**
* Creates a new <code>TreeWalker</code> instance.
*/
public TreeWalker()
{
setFileExtensions(new String[]{"java"});
mMessages = new LocalizedMessages();
// TODO: I (lkuehne) can't believe I wrote this! HACK HACK HACK!
// the parent relationship should really be managed by the DetailAST
// itself but ANTLR calls setFirstChild and friends in an
// unpredictable way. Introducing this hack for now to make
// DetailsAST.setParent() private...
try {
mDetailASTmParent = DetailAST.class.getDeclaredField("mParent");
// this will fail in environments with security managers
mDetailASTmParent.setAccessible(true);
}
catch (NoSuchFieldException e) {
mDetailASTmParent = null;
}
}
/** @param aTabWidth the distance between tab stops */
public void setTabWidth(int aTabWidth)
{
mTabWidth = aTabWidth;
}
/** @param aFileName the cache file */
public void setCacheFile(String aFileName)
{
final Configuration configuration = getConfiguration();
mCache = new PropertyCacheFile(configuration, aFileName);
}
/** @param aClassLoader class loader to resolve classes with. */
public void setClassLoader(ClassLoader aClassLoader)
{
mClassLoader = aClassLoader;
}
/**
* Sets the module factory for creating child modules (Checks).
* @param aModuleFactory the factory
*/
public void setModuleFactory(ModuleFactory aModuleFactory)
{
mModuleFactory = aModuleFactory;
}
/** @see com.puppycrawl.tools.checkstyle.api.Configurable */
public void finishLocalSetup()
{
DefaultContext checkContext = new DefaultContext();
checkContext.add("classLoader", mClassLoader);
checkContext.add("messages", mMessages);
// TODO: hmmm.. this looks less than elegant
// we have just parsed the string,
// now we're recreating it only to parse it again a few moments later
checkContext.add("tabWidth", String.valueOf(mTabWidth));
mChildContext = checkContext;
}
/**
* Instantiates, configures and registers a Check that is specified
* in the provided configuration.
* @see com.puppycrawl.tools.checkstyle.api.AutomaticBean
*/
public void setupChild(Configuration aChildConf)
throws CheckstyleException
{
// TODO: improve the error handing
final String name = aChildConf.getName();
final Object module = mModuleFactory.createModule(name);
if (!(module instanceof Check)) {
throw new CheckstyleException(
"TreeWalker is not allowed as a parent of " + name);
}
final Check c = (Check) module;
c.contextualize(mChildContext);
c.configure(aChildConf);
c.init();
registerCheck(c);
}
/**
* Processes a specified file and reports all errors found.
* @param aFile the file to process
**/
private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
mMessages.reset();
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName);
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound", null));
}
catch (IOException ioe) {
mMessages.add(new LocalizedMessage(
0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()}));
}
catch (RecognitionException re) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()}));
}
catch (TokenStreamException te) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()}));
}
+ catch (Throwable err) {
+ mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
+ "general.exception",
+ new String[] {"" + err}));
+ }
if (mMessages.size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
getMessageDispatcher().fireErrors(
fileName, mMessages.getMessages());
}
getMessageDispatcher().fireFileFinished(fileName);
}
/**
* Register a check for a given configuration.
* @param aCheck the check to register
* @throws CheckstyleException if an error occurs
*/
private void registerCheck(Check aCheck)
throws CheckstyleException
{
int[] tokens = new int[] {}; //safety initialization
final Set checkTokens = aCheck.getTokenNames();
if (!checkTokens.isEmpty()) {
tokens = aCheck.getRequiredTokens();
//register configured tokens
final int acceptableTokens[] = aCheck.getAcceptableTokens();
Arrays.sort(acceptableTokens);
final Iterator it = checkTokens.iterator();
while (it.hasNext()) {
final String token = (String) it.next();
try {
final int tokenId = TokenTypes.getTokenId(token);
if (Arrays.binarySearch(acceptableTokens, tokenId) >= 0) {
registerCheck(token, aCheck);
}
// TODO: else log warning
}
catch (IllegalArgumentException ex) {
throw new CheckstyleException("illegal token \""
+ token + "\" in check " + aCheck, ex);
}
}
}
else {
tokens = aCheck.getDefaultTokens();
}
for (int i = 0; i < tokens.length; i++) {
registerCheck(tokens[i], aCheck);
}
mAllChecks.add(aCheck);
}
/**
* Register a check for a specified token id.
* @param aTokenID the id of the token
* @param aCheck the check to register
*/
private void registerCheck(int aTokenID, Check aCheck)
{
registerCheck(TokenTypes.getTokenName(aTokenID), aCheck);
}
/**
* Register a check for a specified token name
* @param aToken the name of the token
* @param aCheck the check to register
*/
private void registerCheck(String aToken, Check aCheck)
{
ArrayList visitors = (ArrayList) mTokenToChecks.get(aToken);
if (visitors == null) {
visitors = new ArrayList();
mTokenToChecks.put(aToken, visitors);
}
visitors.add(aCheck);
}
/**
* Initiates the walk of an AST.
* @param aAST the root AST
* @param aContents the contents of the file the AST was generated from
*/
private void walk(DetailAST aAST, FileContents aContents)
{
mMessages.reset();
notifyBegin(aAST, aContents);
// empty files are not flagged by javac, will yield aAST == null
if (aAST != null) {
setParent(aAST, null); // TODO: Manage parent in DetailAST
process(aAST);
}
notifyEnd(aAST);
}
/**
* Sets the parent of an AST.
* @param aChildAST the child that gets a new parent
* @param aParentAST the new parent
*/
// TODO: remove this method and manage parent in DetailAST
private void setParent(DetailAST aChildAST, DetailAST aParentAST)
{
// HACK
try {
mDetailASTmParent.set(aChildAST, aParentAST);
}
catch (IllegalAccessException iae) {
// can't happen because method has been made accesible
throw new RuntimeException();
}
// End of HACK
}
/**
* Notify interested checks that about to begin walking a tree.
* @param aRootAST the root of the tree
* @param aContents the contents of the file the AST was generated from
*/
private void notifyBegin(DetailAST aRootAST, FileContents aContents)
{
final Iterator it = mAllChecks.iterator();
while (it.hasNext()) {
final Check check = (Check) it.next();
check.setFileContents(aContents);
check.beginTree(aRootAST);
}
}
/**
* Notify checks that finished walking a tree.
* @param aRootAST the root of the tree
*/
private void notifyEnd(DetailAST aRootAST)
{
final Iterator it = mAllChecks.iterator();
while (it.hasNext()) {
final Check check = (Check) it.next();
check.finishTree(aRootAST);
}
}
/**
* Recursively processes a node calling interested checks at each node.
* @param aAST the node to start from
*/
private void process(DetailAST aAST)
{
if (aAST == null) {
return;
}
notifyVisit(aAST);
final DetailAST child = (DetailAST) aAST.getFirstChild();
if (child != null) {
setParent(child, aAST); // TODO: Manage parent in DetailAST
process(child);
}
notifyLeave(aAST);
final DetailAST sibling = (DetailAST) aAST.getNextSibling();
if (sibling != null) {
setParent(sibling, aAST.getParent()); // TODO: Manage parent ...
process(sibling);
}
}
/**
* Notify interested checks that visiting a node.
* @param aAST the node to notify for
*/
private void notifyVisit(DetailAST aAST)
{
final ArrayList visitors =
(ArrayList) mTokenToChecks.get(
TokenTypes.getTokenName(aAST.getType()));
if (visitors != null) {
for (int i = 0; i < visitors.size(); i++) {
final Check check = (Check) visitors.get(i);
check.visitToken(aAST);
}
}
}
/**
* Notify interested checks that leaving a node.
* @param aAST the node to notify for
*/
private void notifyLeave(DetailAST aAST)
{
final ArrayList visitors =
(ArrayList) mTokenToChecks.get(
TokenTypes.getTokenName(aAST.getType()));
if (visitors != null) {
for (int i = 0; i < visitors.size(); i++) {
final Check check = (Check) visitors.get(i);
check.leaveToken(aAST);
}
}
}
/**
* Static helper method to parses a Java source file.
* @param aContents contains the contents of the file
* @return the root of the AST
* @throws TokenStreamException if lexing failed
* @throws RecognitionException if parsing failed
*/
public static DetailAST parse(FileContents aContents)
throws TokenStreamException, RecognitionException
{
DetailAST rootAST;
try {
// try the 1.4 grammar first, this will succeed for
// all code that compiles without any warnings in JDK 1.4,
// that should cover most cases
final Reader sar = new StringArrayReader(aContents.getLines());
final GeneratedJava14Lexer jl = new GeneratedJava14Lexer(sar);
jl.setFilename(aContents.getFilename());
jl.setFileContents(aContents);
final GeneratedJava14Recognizer jr =
new SilentJava14Recognizer(jl);
jr.setFilename(aContents.getFilename());
jr.setASTNodeClass(DetailAST.class.getName());
jr.compilationUnit();
rootAST = (DetailAST) jr.getAST();
}
catch (RecognitionException re) {
// Parsing might have failed because the checked
// file contains "assert" as an identifier. Retry with a
// grammar that treats "assert" as an identifier
// and not as a keyword
// Arghh - the pain - duplicate code!
final Reader sar = new StringArrayReader(aContents.getLines());
final GeneratedJavaLexer jl = new GeneratedJavaLexer(sar);
jl.setFilename(aContents.getFilename());
jl.setFileContents(aContents);
final GeneratedJavaRecognizer jr = new GeneratedJavaRecognizer(jl);
jr.setFilename(aContents.getFilename());
jr.setASTNodeClass(DetailAST.class.getName());
jr.compilationUnit();
rootAST = (DetailAST) jr.getAST();
}
return rootAST;
}
/** @see com.puppycrawl.tools.checkstyle.api.FileSetCheck */
public void process(File[] aFiles)
{
File[] javaFiles = filter(aFiles);
for (int i = 0; i < javaFiles.length; i++) {
process(javaFiles[i]);
}
}
/**
* @see com.puppycrawl.tools.checkstyle.api.FileSetCheck
*/
public void destroy()
{
for (Iterator it = mAllChecks.iterator(); it.hasNext();) {
final Check c = (Check) it.next();
c.destroy();
}
mCache.destroy();
super.destroy();
}
}
| true | true | private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
mMessages.reset();
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName);
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound", null));
}
catch (IOException ioe) {
mMessages.add(new LocalizedMessage(
0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()}));
}
catch (RecognitionException re) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()}));
}
catch (TokenStreamException te) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()}));
}
if (mMessages.size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
getMessageDispatcher().fireErrors(
fileName, mMessages.getMessages());
}
getMessageDispatcher().fireFileFinished(fileName);
}
| private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
mMessages.reset();
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName);
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound", null));
}
catch (IOException ioe) {
mMessages.add(new LocalizedMessage(
0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()}));
}
catch (RecognitionException re) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()}));
}
catch (TokenStreamException te) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()}));
}
catch (Throwable err) {
mMessages.add(new LocalizedMessage(0, Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {"" + err}));
}
if (mMessages.size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
getMessageDispatcher().fireErrors(
fileName, mMessages.getMessages());
}
getMessageDispatcher().fireFileFinished(fileName);
}
|
diff --git a/src/com/drexel/duca/frontend/ChatWindow.java b/src/com/drexel/duca/frontend/ChatWindow.java
index f4eeff6..8993b76 100644
--- a/src/com/drexel/duca/frontend/ChatWindow.java
+++ b/src/com/drexel/duca/frontend/ChatWindow.java
@@ -1,128 +1,128 @@
package com.drexel.duca.frontend;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.drexel.duca.backend.RSAKeypair;
public class ChatWindow implements Runnable {
private JFrame frmChatWindow;
private JTextArea textArea;
private JTextField textField;
private JButton btnSend;
private JPanel bottomPanel;
private JScrollPane scrollPane;
private Scanner sInput;
private PrintStream sOutput;
private RSAKeypair encryption;
private RSAKeypair decryption;
/**
* Create the application.
*/
public ChatWindow(Socket socket) {
try {
sInput = new Scanner(socket.getInputStream());
sOutput = new PrintStream(socket.getOutputStream());
decryption = new RSAKeypair();
sOutput.println(decryption.getE()+ " " + decryption.getC());
int e = sInput.nextInt();
int c = sInput.nextInt();
sInput.nextLine();//flush new line from buffer
encryption = new RSAKeypair(e, c);
initialize();
new Thread(this).start();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmChatWindow = new JFrame();
frmChatWindow.setTitle("Chat Window");
frmChatWindow.setBounds(100, 100, 450, 300);
- frmChatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ frmChatWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS));
textArea = new JTextArea();
textArea.setRows(15);
scrollPane = new JScrollPane(textArea);
frmChatWindow.getContentPane().add(scrollPane);
bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
textField = new JTextField();
bottomPanel.add(textField);
textField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 10) {
sendText();
}
}
});
btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendText();
}
});
bottomPanel.add(btnSend);
frmChatWindow.getContentPane().add(bottomPanel);
}
private void sendText() {
String msg = textField.getText();
if (!msg.isEmpty()) {
sOutput.println(encryption.encrypt(msg));
textArea.append(msg + "\n");
textField.setText("");
}
}
public JFrame getChatWindowFrame() {
return frmChatWindow;
}
@Override
public void run() {
while (true) {
String msg = decryption.decrypt(sInput.nextLine());
if (!msg.isEmpty()) {
textArea.append(msg + "\n");
}
}
}
}
| true | true | private void initialize() {
frmChatWindow = new JFrame();
frmChatWindow.setTitle("Chat Window");
frmChatWindow.setBounds(100, 100, 450, 300);
frmChatWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS));
textArea = new JTextArea();
textArea.setRows(15);
scrollPane = new JScrollPane(textArea);
frmChatWindow.getContentPane().add(scrollPane);
bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
textField = new JTextField();
bottomPanel.add(textField);
textField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 10) {
sendText();
}
}
});
btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendText();
}
});
bottomPanel.add(btnSend);
frmChatWindow.getContentPane().add(bottomPanel);
}
| private void initialize() {
frmChatWindow = new JFrame();
frmChatWindow.setTitle("Chat Window");
frmChatWindow.setBounds(100, 100, 450, 300);
frmChatWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frmChatWindow.getContentPane().setLayout(new BoxLayout(frmChatWindow.getContentPane(), BoxLayout.Y_AXIS));
textArea = new JTextArea();
textArea.setRows(15);
scrollPane = new JScrollPane(textArea);
frmChatWindow.getContentPane().add(scrollPane);
bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
textField = new JTextField();
bottomPanel.add(textField);
textField.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == 10) {
sendText();
}
}
});
btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendText();
}
});
bottomPanel.add(btnSend);
frmChatWindow.getContentPane().add(bottomPanel);
}
|
diff --git a/src/ru/leks13/jabbertimer/Parse.java b/src/ru/leks13/jabbertimer/Parse.java
index e921173..0574c6c 100644
--- a/src/ru/leks13/jabbertimer/Parse.java
+++ b/src/ru/leks13/jabbertimer/Parse.java
@@ -1,74 +1,74 @@
/*
* Leks13
* GPL v3
*/
package ru.leks13.jabbertimer;
import java.io.*;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.XMPPException;
public class Parse {
public static void ParseConfigFile() throws FileNotFoundException, IOException {
Properties prop = new Properties();
String fileName = "config.cfg";
InputStream is = new FileInputStream(fileName);
prop.load(is);
String jid = prop.getProperty("jid");
String nick = prop.getProperty("login");
- String server = prop.getProperty("server");
+ String domain = prop.getProperty("domain");
int port = Integer.parseInt(prop.getProperty("port", "5222"));
if (jid != null) {
StringTokenizer st = new StringTokenizer(jid, "@");
while (st.hasMoreTokens()) {
nick = st.nextToken();
- server = st.nextToken();
+ domain = st.nextToken();
}
}
- String domain = prop.getProperty("domain", server);
+ String server = prop.getProperty("server", domain);
String password = prop.getProperty("password");
String adminB = prop.getProperty("admin");
String resource = prop.getProperty("resource", "bot");
String status = prop.getProperty("status", "Alpha version");
if (nick == null || server == null || adminB == null) {
System.out.println("Error! Login or server or admin is null!");
System.exit(0);
}
while (password == null) {
char passwd[];
Console cons = System.console();
passwd = cons.readPassword("Enter password : ");
password = new String(passwd);
}
XmppNet conXm;
try {
conXm = new XmppNet(status, nick, domain, server, password, resource, port);
conXm.whoIsAdmin(adminB);
System.out.println("Config parsed.");
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conXm.incomeChat();
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Config parsed ^
}
| false | true | public static void ParseConfigFile() throws FileNotFoundException, IOException {
Properties prop = new Properties();
String fileName = "config.cfg";
InputStream is = new FileInputStream(fileName);
prop.load(is);
String jid = prop.getProperty("jid");
String nick = prop.getProperty("login");
String server = prop.getProperty("server");
int port = Integer.parseInt(prop.getProperty("port", "5222"));
if (jid != null) {
StringTokenizer st = new StringTokenizer(jid, "@");
while (st.hasMoreTokens()) {
nick = st.nextToken();
server = st.nextToken();
}
}
String domain = prop.getProperty("domain", server);
String password = prop.getProperty("password");
String adminB = prop.getProperty("admin");
String resource = prop.getProperty("resource", "bot");
String status = prop.getProperty("status", "Alpha version");
if (nick == null || server == null || adminB == null) {
System.out.println("Error! Login or server or admin is null!");
System.exit(0);
}
while (password == null) {
char passwd[];
Console cons = System.console();
passwd = cons.readPassword("Enter password : ");
password = new String(passwd);
}
XmppNet conXm;
try {
conXm = new XmppNet(status, nick, domain, server, password, resource, port);
conXm.whoIsAdmin(adminB);
System.out.println("Config parsed.");
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conXm.incomeChat();
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
| public static void ParseConfigFile() throws FileNotFoundException, IOException {
Properties prop = new Properties();
String fileName = "config.cfg";
InputStream is = new FileInputStream(fileName);
prop.load(is);
String jid = prop.getProperty("jid");
String nick = prop.getProperty("login");
String domain = prop.getProperty("domain");
int port = Integer.parseInt(prop.getProperty("port", "5222"));
if (jid != null) {
StringTokenizer st = new StringTokenizer(jid, "@");
while (st.hasMoreTokens()) {
nick = st.nextToken();
domain = st.nextToken();
}
}
String server = prop.getProperty("server", domain);
String password = prop.getProperty("password");
String adminB = prop.getProperty("admin");
String resource = prop.getProperty("resource", "bot");
String status = prop.getProperty("status", "Alpha version");
if (nick == null || server == null || adminB == null) {
System.out.println("Error! Login or server or admin is null!");
System.exit(0);
}
while (password == null) {
char passwd[];
Console cons = System.console();
passwd = cons.readPassword("Enter password : ");
password = new String(passwd);
}
XmppNet conXm;
try {
conXm = new XmppNet(status, nick, domain, server, password, resource, port);
conXm.whoIsAdmin(adminB);
System.out.println("Config parsed.");
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
try {
conXm.incomeChat();
} catch (InterruptedException ex) {
Logger.getLogger(Parse.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (XMPPException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
diff --git a/libraries/javalib/java/awt/Image.java b/libraries/javalib/java/awt/Image.java
index a1829f524..21084da31 100644
--- a/libraries/javalib/java/awt/Image.java
+++ b/libraries/javalib/java/awt/Image.java
@@ -1,880 +1,882 @@
package java.awt;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.IndexColorModel;
import java.awt.image.MemoryImageSource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import kaffe.awt.JavaColorModel;
import kaffe.io.AccessibleBAOStream;
import kaffe.util.Ptr;
import kaffe.util.VectorSnapshot;
/**
* Copyright (c) 1998
* Transvirtual Technologies, Inc. All rights reserved.
*
* See the file "license.terms" for information on usage and redistribution
* of this file.
*
* @author P.C.Mehlitz
*/
public class Image
{
Ptr nativeData;
int width = -1;
int height = -1;
ImageProducer producer;
Object observers;
int flags;
Hashtable props;
Image next;
final public static int SCALE_DEFAULT = 1;
final public static int SCALE_FAST = 2;
final public static int SCALE_SMOOTH = 4;
final public static int SCALE_REPLICATE = 8;
final public static int SCALE_AREA_AVERAGING = 16;
final static int MASK = ImageObserver.WIDTH|ImageObserver.HEIGHT|
ImageObserver.PROPERTIES|ImageObserver.SOMEBITS|
ImageObserver.FRAMEBITS|ImageObserver.ALLBITS|
ImageObserver.ERROR|ImageObserver.ABORT;
final static int PRODUCING = 1 << 8;
final static int READY = ImageObserver.WIDTH | ImageObserver.HEIGHT | ImageObserver.ALLBITS | PRODUCING;
final static int SCREEN = 1 << 10;
final static int BLOCK_FRAMELOADER = 1 << 11;
final static int IS_ANIMATION = 1 << 12;
final public static Object UndefinedProperty = ImageLoader.class;
Image ( File file ) {
producer = new ImageNativeProducer( this, file);
}
Image ( Image img, int w, int h ) {
nativeData = Toolkit.imgCreateScaledImage(img.nativeData, w, h);
width = w;
height = h;
flags = READY;
}
Image ( ImageProducer ip ) {
producer = ip;
// there currently is no way to check the size of a MemoryImageSource,
// so everything != 0 causes async production
if ( (Defaults.MemImageSrcThreshold == 0) && (producer instanceof MemoryImageSource) ) {
flags |= PRODUCING;
synchronized ( ImageLoader.syncLoader ) {
ImageLoader.syncLoader.img = this;
ip.startProduction( ImageLoader.syncLoader);
}
}
}
Image ( URL url ) {
producer = new ImageNativeProducer( url);
}
Image ( byte[] data, int offs, int len) {
producer = new ImageNativeProducer( this, data, offs, len);
}
Image ( int w, int h ) {
nativeData = Toolkit.imgCreateScreenImage( w, h );
width = w;
height = h;
flags = READY | SCREEN;
}
synchronized void activateFrameLoader () {
// activate waiting FrameLoader
if ( (flags & BLOCK_FRAMELOADER) != 0 ){
flags &= ~BLOCK_FRAMELOADER;
notify();
}
}
// -------------------------------------------------------------------------
void addObserver ( ImageObserver observer ) {
if ( observer == null ) {
return;
}
if ( observers == null ) {
observers = observer;
}
else if ( observers instanceof Vector ) {
Vector v = (Vector) observers;
if ( !v.contains(observer) )
v.addElement(observer);
}
else {
if ( observer != observers ) {
Vector v = new Vector( 3);
v.addElement( observers);
v.addElement( observer);
observers = v;
}
}
}
synchronized int checkImage ( int w, int h, ImageObserver obs, boolean load ){
if ( (flags & (ImageObserver.ALLBITS | ImageObserver.FRAMEBITS)) != 0 ) {
if ( ((w > 0) || (h > 0)) && (w != width) && (h != height) ){
scale( w, h);
}
if ( load && (flags & ImageObserver.FRAMEBITS) != 0 )
addObserver( obs);
}
else if ( load && ((flags & PRODUCING) == 0) ) {
loadImage( w, h, obs);
}
return (flags & MASK);
}
protected void finalize () throws Throwable {
flush();
super.finalize();
}
public void flush () {
// This is the bad guy - the spec demands that it reverts us into a "not-yet-loaded"
// state, "to be recreated or fetched again from its source" when a subsequent
// rendering takes place. Since "its source" doesn't mean the *original* source
// (see getSource() - "an object that *produces* the image"), we could stay with the
// native representation (probably the most efficient storage and prod environment),
// but apps explicitly using flush most probably use it because the original
// image source has changed, i.e. they use flush() as a way to in-situ modify
// otherwise constant images (by means of changed sources). Only heaven knows why
// they don't replace the image (this is like a Graphics that can be brought back
// to life after a dispose()). That means we have to keep a ref of byte[] data, and
// we can't produce on-screen images
if ( nativeData != null && (flags & ImageObserver.ALLBITS) != 0){
Toolkit.imgFreeImage( nativeData);
nativeData = null;
flags = 0;
width = -1;
height = -1;
}
}
public Graphics getGraphics () {
if ((flags & SCREEN) == 0 || nativeData == null) {
return null;
}
else {
return NativeGraphics.getGraphics( this,
nativeData, NativeGraphics.TGT_TYPE_IMAGE,
0, 0, 0, 0, width, height,
Color.black, Color.white, Defaults.WndFont, false);
}
}
public synchronized int getHeight ( ImageObserver observer ) {
if ( (flags & ImageObserver.HEIGHT) != 0 ) {
return height;
}
else {
loadImage(-1, -1, observer);
return (-1);
}
}
public Object getProperty ( String name, ImageObserver observer ) {
if ( props == null ) {
if ( (flags & (ImageObserver.FRAMEBITS | ImageObserver.ALLBITS)) != 0 )
return UndefinedProperty;
else if ( (flags & PRODUCING) == 0 )
loadImage( -1, -1, observer);
return null;
}
else {
Object val = props.get( name);
if ( val == null )
return UndefinedProperty;
return val;
}
}
public Image getScaledInstance (int width, int height, int hints) {
if (nativeData == null || width <= 0 || height <= 0 || (flags & SCREEN) != 0 || (flags & ImageObserver.ALLBITS) == 0) {
return (null);
}
return (new Image(this, width, height));
}
public ImageProducer getSource () {
if ( producer == null )
producer = new ImageNativeProducer( this);
return producer;
}
public synchronized int getWidth ( ImageObserver observer ) {
if ( (flags & ImageObserver.WIDTH) != 0 ) {
return (width);
}
else {
loadImage(-1, -1, observer);
return (-1);
}
}
synchronized boolean loadImage ( int w, int h, ImageObserver obs ) {
// it's (partly?) loaded already
if ( (flags & (ImageObserver.FRAMEBITS|ImageObserver.ALLBITS)) != 0 ){
if ( ((w > 0) || (h > 0)) && (w != width) && (h != height) ) {
// but do we have to scale it?
scale( w, h);
}
if ( (flags & ImageObserver.FRAMEBITS) != 0 ) {
addObserver( obs);
}
return (true);
}
// we ultimately failed
else if ( (flags & ImageObserver.ABORT) != 0 ) {
return (false);
}
// there's work ahead, kick it off
else if ( (flags & PRODUCING) == 0 ) {
flags |= PRODUCING;
if ( obs != null ) {
addObserver( obs);
}
/*
* We now load the image data synchronously - it's not clear
* that's what you should actually do but it fixes a problem
* with the Citrix ICA client. (Tim 1/18/99)
*/
ImageLoader.loadSync( this);
return (true);
}
return (false);
}
void removeObserver ( ImageObserver observer ) {
if ( (observers == null) || (observer == null) )
return;
if ( observers == observer ){
observers = null;
}
else if ( observers instanceof Vector ) {
Vector v = (Vector)observers;
v.removeElement( observer);
if ( v.size() == 1 )
observers = v.firstElement();
}
}
private boolean scale (int w, int h) {
if ((flags & SCREEN) != 0 || (flags & ImageObserver.ALLBITS) == 0 || nativeData == null) {
return (false);
}
if (w != width || h != height) {
Ptr oldNativeData = nativeData;
nativeData = Toolkit.imgCreateScaledImage( nativeData, w, h );
Toolkit.imgFreeImage( oldNativeData);
width = w;
height = h;
}
return (true);
}
synchronized void stateChange(int flags, int x, int y, int w, int h) {
ImageObserver obs;
this.flags |= flags;
if (observers == null) {
return;
}
// We get false if they're no longer interested in updates. This is *NOT* what is said in the
// Addison-Wesley documentation, but is what is says in the JDK javadoc documentation.
if ( observers instanceof ImageObserver ){
obs = (ImageObserver) observers;
if ( obs.imageUpdate( this, flags, x, y, w, h) == false ) {
observers = null;
}
}
else if ( observers instanceof Vector ){
// we can't use a (index-based) standard Vector enumerator because we have
// to notify *all* elements regardless of any removals
for ( Enumeration e=VectorSnapshot.getCached( (Vector)observers); e.hasMoreElements(); ) {
obs = (ImageObserver) e.nextElement();
if ( obs.imageUpdate( this, flags, x, y, w, h) == false )
removeObserver( obs);
}
}
}
public String toString() {
String s = getClass().getName() + " [" + width + ',' + height +
((nativeData != null) ? ", native" : ", non-native") +
", flags: " + Integer.toHexString( flags);
if ( (flags & PRODUCING) != 0 )
s += " producing";
if ( (flags & ImageObserver.ALLBITS) != 0 )
s += " allbits";
else if ( (flags & ImageObserver.FRAMEBITS) != 0 )
s += " framebits";
else if ( (flags & ImageObserver.ERROR) != 0 )
s += " error";
s += "]";
return s;
}
}
class ImageFrameLoader
extends Thread
{
Image img;
ImageFrameLoader ( Image img ) {
super("ImageFrameLoader");
this.img = img;
img.flags |= Image.BLOCK_FRAMELOADER;
setPriority( NORM_PRIORITY - 3);
setDaemon( true);
start();
}
public void run () {
// Note that we get started *after* the first SINGLEFRAMEDONE, i.e. our image observers
// already got the preceeding dimension notification
if ( img.producer instanceof ImageNativeProducer ) {
runINPLoop();
}
else {
throw new Error("Unhandled production: " + img.producer);
}
}
public void runINPLoop () {
int w, h, latency, dt;
long t;
Ptr ptr = img.nativeData;
img.flags |= Image.IS_ANIMATION;
// we already have the whole thing physically read in, so just start to notify round-robin. We also
// got the first frame propperly reported, i.e. we start with flipping to the next one
do {
latency = Toolkit.imgGetLatency( img.nativeData);
t = System.currentTimeMillis();
// wait until we get requested the next time (to prevent being spinned around by a MediaTracker)
synchronized ( img ) {
try {
while ( (img.flags & Image.BLOCK_FRAMELOADER) != 0 ){
img.wait();
}
} catch ( InterruptedException _ ) {}
}
dt = (int) (System.currentTimeMillis() - t);
if ( dt < latency ){
try { Thread.sleep( latency - dt); } catch ( Exception _ ) {}
}
if ( (latency == 0) || (dt < 2*latency) ){
if ( (ptr = Toolkit.imgGetNextFrame( img.nativeData)) == null )
break;
}
else {
// Most probably we weren't visible for a while, reset because this might be a
// animation with delta frames (and the first one sets the background)
ptr = Toolkit.imgSetFrame( img.nativeData, 0);
}
img.nativeData = ptr;
+/*
w = Toolkit.imgGetWidth( img.nativeData);
h = Toolkit.imgGetHeight( img.nativeData);
if ( (img.width != w) || (img.height != h) ){
img.width = w;
img.height = h;
img.stateChange( ImageObserver.WIDTH|ImageObserver.HEIGHT, 0, 0, img.width, img.height);
}
+*/
img.flags |= Image.BLOCK_FRAMELOADER;
img.stateChange( ImageObserver.FRAMEBITS, 0, 0, img.width, img.height);
} while ( img.observers != null );
}
}
class ImageLoader
implements ImageConsumer, Runnable
{
Image queueHead;
Image queueTail;
Image img;
static ImageLoader asyncLoader;
static ImageLoader syncLoader = new ImageLoader();
public synchronized void imageComplete ( int status ) {
int s = 0;
if ( status == STATICIMAGEDONE ){
s = ImageObserver.ALLBITS;
// give native layer a chance to do alpha channel reduction
if ( !(img.producer instanceof ImageNativeProducer) )
Toolkit.imgComplete( img.nativeData, status);
}
else if ( status == SINGLEFRAMEDONE ) {
s = ImageObserver.FRAMEBITS;
// This is a (indefinite) movie production - move it out of the way (in its own thread)
// so that we can go on with useful work. Note that if our producer was a ImageNativeProducer,
// the whole external image has been read in already (no IO required, anymore)
new ImageFrameLoader( img);
}
else {
if ( (status & IMAGEERROR) != 0 ) s |= ImageObserver.ERROR;
if ( (status & IMAGEABORTED) != 0 ) s |= ImageObserver.ABORT;
}
img.stateChange( s, 0, 0, img.width, img.height);
// this has to be called *after* a optional ImageFrameLoader went into action, since
// the producer might decide to stop if it doesn't have another consumer
img.producer.removeConsumer( this);
img = null; // we are done with it, prevent memory leaks
if ( this == asyncLoader )
notify(); // in case we had an async producer
}
static synchronized void load ( Image img ) {
if ( asyncLoader == null ){
asyncLoader = new ImageLoader();
asyncLoader.queueHead = asyncLoader.queueTail = img;
Thread t = new Thread( asyncLoader, "asyncLoader");
t.setPriority( Thread.NORM_PRIORITY - 1);
t.start();
}
else {
if ( asyncLoader.queueTail == null ) {
asyncLoader.queueHead = asyncLoader.queueTail = img;
}
else {
asyncLoader.queueTail.next = img;
asyncLoader.queueTail = img;
}
ImageLoader.class.notify();
}
}
static void loadSync( Image img ) {
synchronized ( syncLoader ) {
syncLoader.img = img;
img.producer.startProduction(syncLoader);
}
}
public void run () {
for (;;) {
synchronized ( ImageLoader.class ) {
if ( queueHead != null ) {
img = queueHead;
queueHead = img.next;
img.next = null;
if ( img == queueTail )
queueTail = null;
}
else {
try {
ImageLoader.class.wait( 20000);
if ( queueHead == null ) {
// Ok, we waited for too long, lets do suicide
asyncLoader = null;
return;
}
else {
continue;
}
}
catch ( InterruptedException xx ) { xx.printStackTrace(); }
}
}
try {
// this is hopefully sync, but who knows what kinds of producers are out there
img.producer.startProduction( this);
if ( img != null ) {
synchronized ( this ){
wait();
}
}
}
catch ( Throwable x ) {
x.printStackTrace();
imageComplete( IMAGEERROR | IMAGEABORTED);
}
}
}
public void setColorModel ( ColorModel model ) {
// No way to pass this to ImageObservers. Since we also get it in setPixels, we
// just ignore it
}
public void setDimensions ( int width, int height ) {
img.width = width;
img.height = height;
// If we were notified by a ImageNativeProducer, the nativeData field is already
// set. In case this is just an arbitrary producer, create it so that we have a
// target for subsequent setPixel() calls
if ( img.nativeData == null ){
img.nativeData = Toolkit.imgCreateImage( width, height);
}
img.stateChange( ImageObserver.WIDTH|ImageObserver.HEIGHT, 0, 0, width, height);
}
public void setHints ( int hints ) {
// we don't honor them
}
public void setPixels ( int x, int y, int w, int h,
ColorModel model, byte pixels[], int offset, int scansize ) {
if ( img.nativeData == null ) {
// producer trouble, we haven't got dimensions yet
return;
}
if ( model instanceof IndexColorModel ) {
IndexColorModel icm = (IndexColorModel) model;
Toolkit.imgSetIdxPels( img.nativeData, x, y, w, h, icm.rgbs,
pixels, icm.trans, offset, scansize);
img.stateChange( ImageObserver.SOMEBITS, x, y, w, h);
}
else {
System.err.println("Unhandled colorModel: " + model.getClass());
}
}
public void setPixels ( int x, int y, int w, int h,
ColorModel model, int pixels[], int offset, int scansize ) {
if ( img.nativeData == null ) {
// producer trouble, we haven't got dimensions yet
return;
}
if ( model instanceof JavaColorModel ) {
// Ok, nothing to convert here
}
else if ( model instanceof DirectColorModel ) {
// in case our pels aren't default RGB yet, convert them using the ColorModel
int xw = x + w;
int yh = y + h;
int i, j, idx;
int i0 = y * scansize + offset;
for ( j = y; j < yh; j++, i0 += scansize ) {
for ( i = x, idx = i+i0; i < xw; i++, idx++) {
// are we allowed to change the array in-situ?
pixels[idx] = model.getRGB( pixels[idx]);
}
}
}
else {
System.out.println("Unhandled colorModel: " + model.getClass());
}
Toolkit.imgSetRGBPels( img.nativeData, x, y, w, h, pixels, offset, scansize);
img.stateChange( ImageObserver.SOMEBITS, x, y, w, h);
}
public void setProperties ( Hashtable properties ) {
img.props = properties;
img.stateChange( img.flags | ImageObserver.PROPERTIES, 0, 0, img.width, img.height);
}
}
/**
* This shouldn't be a inner class since you can easily grab the source of an
* image and use it outside of this image (e.g. to create other images - whatever
* it might be good for)
*/
class ImageNativeProducer
implements ImageProducer
{
Object consumer;
Object src;
int off;
int len;
ImageNativeProducer ( Image img ) {
src = img;
}
ImageNativeProducer ( Image img, File file ) {
src = file;
// check if we can produce immediately
if ( file.exists() ) {
if ( file.length() < Defaults.FileImageThreshold ){
img.flags |= Image.PRODUCING;
img.producer = this;
ImageLoader.loadSync(img);
}
}
else {
img.flags = ImageObserver.ERROR | ImageObserver.ABORT;
}
}
ImageNativeProducer ( Image img, byte[] data, int off, int len ) {
src = data;
this.off = off;
this.len = len;
if ( len < Defaults.DataImageThreshold ) {
img.flags |= Image.PRODUCING;
synchronized ( ImageLoader.syncLoader ) {
ImageLoader.syncLoader.img = img;
img.producer = this;
startProduction( ImageLoader.syncLoader);
}
}
}
ImageNativeProducer ( URL url ) {
src = url;
}
public void addConsumer ( ImageConsumer ic ) {
if ( consumer == null ){
consumer = ic;
}
else if ( this.consumer instanceof Vector ) {
((Vector)consumer).addElement( ic);
}
else {
Vector v = new Vector(3);
v.addElement( consumer);
v.addElement( ic);
consumer = v;
}
}
void imageComplete ( int flags ){
if ( consumer instanceof ImageConsumer ){
((ImageConsumer)consumer).imageComplete( flags);
}
else if ( consumer instanceof Vector) {
Vector v = (Vector) consumer;
int i, n = v.size();
for ( i=0; i<n; i++ ){
((ImageConsumer)v.elementAt( i)).imageComplete( flags);
}
}
}
public boolean isConsumer ( ImageConsumer ic ) {
if ( consumer instanceof ImageConsumer )
return (consumer == ic);
else if ( consumer instanceof Vector )
return ((Vector)consumer).contains( ic);
else
return false;
}
void produceFrom ( File file ) {
Ptr ptr;
if ( file.exists() &&
(ptr = Toolkit.imgCreateFromFile( file.getAbsolutePath())) != null ){
produceFrom( ptr);
}
else {
imageComplete( ImageConsumer.IMAGEERROR | ImageConsumer.IMAGEABORTED);
}
}
void produceFrom ( Ptr ptr ) {
if ( consumer instanceof ImageLoader ) {
ImageLoader loader = (ImageLoader)consumer;
Image img = loader.img;
img.nativeData = ptr;
img.width = Toolkit.imgGetWidth( ptr);
img.height = Toolkit.imgGetHeight( ptr);
loader.setDimensions( img.width, img.height);
loader.imageComplete( Toolkit.imgIsMultiFrame( ptr) ?
ImageConsumer.SINGLEFRAMEDONE : ImageConsumer.STATICIMAGEDONE);
}
else {
Toolkit.imgProduceImage( this, ptr);
Toolkit.imgFreeImage( ptr);
}
}
void produceFrom ( URL url ) {
// since this is most likely used in a browser context (no file
// system), the only thing we can do (in the absence of a suspendable
// native image production) is to temporarily store the data in
// memory. Note that this is done via kaffe.io.AccessibleBAOStream,
// to prevent the inacceptable memory consumption duplication of
// "toByteArray()".
// Ideally, we would have a suspendable image production (that can
// deal with reading and processing "incomplete" data), but that
// simply isn't supported by many native image conversion libraries.
// Some could be done in Java (at the expense of a significant speed
// degradation - this is the classical native functionality), but
// things like Jpeg ?
try {
URLConnection conn = url.openConnection();
if (conn != null) {
int sz = conn.getContentLength();
if (sz <= 0) { // it's unknown, let's assume some size
sz = 4096;
}
AccessibleBAOStream out = new AccessibleBAOStream(sz);
InputStream in = conn.getInputStream();
if ( in != null ) {
out.readFrom(in);
in.close();
Ptr ptr = Toolkit.imgCreateFromData(out.getBuffer(), 0, out.size());
if ( ptr != null ){
produceFrom( ptr);
return;
}
}
}
}
catch ( Exception x ) {}
imageComplete( ImageConsumer.IMAGEERROR|ImageConsumer.IMAGEABORTED);
}
void produceFrom ( byte[] data, int off, int len ) {
Ptr ptr;
if ( (ptr = Toolkit.imgCreateFromData( data, off, len)) != null )
produceFrom( ptr);
else
imageComplete( ImageConsumer.IMAGEERROR | ImageConsumer.IMAGEABORTED);
}
public void removeConsumer ( ImageConsumer ic ) {
if ( consumer == ic ){
consumer = null;
}
else if ( consumer instanceof Vector ) {
Vector v = (Vector) consumer;
v.removeElement( ic);
if ( v.size() == 1 )
consumer = v.elementAt( 0);
}
}
public void requestTopDownLeftRightResend ( ImageConsumer consumer ) {
// ignored
}
void setColorModel ( ColorModel model ){
if ( consumer instanceof ImageConsumer ){
((ImageConsumer)consumer).setColorModel( model);
}
else if ( consumer instanceof Vector) {
Vector v = (Vector)consumer;
int i, n = v.size();
for ( i=0; i<n; i++ ){
((ImageConsumer)v.elementAt( i)).setColorModel( model);
}
}
}
void setDimensions ( int width, int height ){
if ( consumer instanceof ImageConsumer ){
((ImageConsumer)consumer).setDimensions( width, height);
}
else if ( consumer instanceof Vector) {
Vector v = (Vector)consumer;
int i, n = v.size();
for ( i=0; i<n; i++ ){
((ImageConsumer)v.elementAt( i)).setDimensions( width, height);
}
}
}
void setHints ( int hints ){
if ( consumer instanceof ImageConsumer ){
((ImageConsumer)consumer).setHints( hints);
}
else if ( consumer instanceof Vector) {
Vector v = (Vector)consumer;
int i, n = v.size();
for ( i=0; i<n; i++ ){
((ImageConsumer)v.elementAt( i)).setHints( hints);
}
}
}
void setPixels ( int x, int y, int w, int h,
ColorModel model, int pixels[], int offset, int scansize ) {
if ( consumer instanceof ImageConsumer ){
((ImageConsumer)consumer).setPixels( x, y, w, h, model, pixels, offset, scansize);
}
else if ( consumer instanceof Vector) {
Vector v = (Vector)consumer;
int i, n = v.size();
for ( i=0; i<n; i++ ){
((ImageConsumer)v.elementAt( i)).setPixels( x, y, w, h,
model, pixels, offset, scansize);
}
}
}
public void startProduction ( ImageConsumer ic ) {
addConsumer( ic);
if ( src instanceof File ) {
produceFrom( (File)src);
}
else if ( src instanceof URL ) {
produceFrom( (URL)src);
}
else if ( src instanceof byte[] ) {
produceFrom( (byte[])src, off, len);
}
else if ( src instanceof Image ) {
Toolkit.imgProduceImage( this, ((Image)src).nativeData);
}
else {
System.err.println( "unsupported production source: " + src.getClass());
}
removeConsumer( ic);
}
}
| false | true | public void runINPLoop () {
int w, h, latency, dt;
long t;
Ptr ptr = img.nativeData;
img.flags |= Image.IS_ANIMATION;
// we already have the whole thing physically read in, so just start to notify round-robin. We also
// got the first frame propperly reported, i.e. we start with flipping to the next one
do {
latency = Toolkit.imgGetLatency( img.nativeData);
t = System.currentTimeMillis();
// wait until we get requested the next time (to prevent being spinned around by a MediaTracker)
synchronized ( img ) {
try {
while ( (img.flags & Image.BLOCK_FRAMELOADER) != 0 ){
img.wait();
}
} catch ( InterruptedException _ ) {}
}
dt = (int) (System.currentTimeMillis() - t);
if ( dt < latency ){
try { Thread.sleep( latency - dt); } catch ( Exception _ ) {}
}
if ( (latency == 0) || (dt < 2*latency) ){
if ( (ptr = Toolkit.imgGetNextFrame( img.nativeData)) == null )
break;
}
else {
// Most probably we weren't visible for a while, reset because this might be a
// animation with delta frames (and the first one sets the background)
ptr = Toolkit.imgSetFrame( img.nativeData, 0);
}
img.nativeData = ptr;
w = Toolkit.imgGetWidth( img.nativeData);
h = Toolkit.imgGetHeight( img.nativeData);
if ( (img.width != w) || (img.height != h) ){
img.width = w;
img.height = h;
img.stateChange( ImageObserver.WIDTH|ImageObserver.HEIGHT, 0, 0, img.width, img.height);
}
img.flags |= Image.BLOCK_FRAMELOADER;
img.stateChange( ImageObserver.FRAMEBITS, 0, 0, img.width, img.height);
} while ( img.observers != null );
}
| public void runINPLoop () {
int w, h, latency, dt;
long t;
Ptr ptr = img.nativeData;
img.flags |= Image.IS_ANIMATION;
// we already have the whole thing physically read in, so just start to notify round-robin. We also
// got the first frame propperly reported, i.e. we start with flipping to the next one
do {
latency = Toolkit.imgGetLatency( img.nativeData);
t = System.currentTimeMillis();
// wait until we get requested the next time (to prevent being spinned around by a MediaTracker)
synchronized ( img ) {
try {
while ( (img.flags & Image.BLOCK_FRAMELOADER) != 0 ){
img.wait();
}
} catch ( InterruptedException _ ) {}
}
dt = (int) (System.currentTimeMillis() - t);
if ( dt < latency ){
try { Thread.sleep( latency - dt); } catch ( Exception _ ) {}
}
if ( (latency == 0) || (dt < 2*latency) ){
if ( (ptr = Toolkit.imgGetNextFrame( img.nativeData)) == null )
break;
}
else {
// Most probably we weren't visible for a while, reset because this might be a
// animation with delta frames (and the first one sets the background)
ptr = Toolkit.imgSetFrame( img.nativeData, 0);
}
img.nativeData = ptr;
/*
w = Toolkit.imgGetWidth( img.nativeData);
h = Toolkit.imgGetHeight( img.nativeData);
if ( (img.width != w) || (img.height != h) ){
img.width = w;
img.height = h;
img.stateChange( ImageObserver.WIDTH|ImageObserver.HEIGHT, 0, 0, img.width, img.height);
}
*/
img.flags |= Image.BLOCK_FRAMELOADER;
img.stateChange( ImageObserver.FRAMEBITS, 0, 0, img.width, img.height);
} while ( img.observers != null );
}
|
diff --git a/tikione-jacocoexec-analyzer/src/fr/tikione/jacocoexec/analyzer/JaCoCoReportAnalyzer.java b/tikione-jacocoexec-analyzer/src/fr/tikione/jacocoexec/analyzer/JaCoCoReportAnalyzer.java
index 08d0c46..01417bc 100644
--- a/tikione-jacocoexec-analyzer/src/fr/tikione/jacocoexec/analyzer/JaCoCoReportAnalyzer.java
+++ b/tikione-jacocoexec-analyzer/src/fr/tikione/jacocoexec/analyzer/JaCoCoReportAnalyzer.java
@@ -1,69 +1,69 @@
package fr.tikione.jacocoexec.analyzer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jacoco.core.analysis.Analyzer;
import org.jacoco.core.analysis.CoverageBuilder;
import org.jacoco.core.analysis.IBundleCoverage;
import org.jacoco.core.data.ExecutionDataReader;
import org.jacoco.core.data.ExecutionDataStore;
import org.jacoco.core.data.SessionInfoStore;
import org.jacoco.report.DirectorySourceFileLocator;
import org.jacoco.report.IReportVisitor;
import org.jacoco.report.xml.XMLFormatter;
/**
* JaCoCo reports related utilities.
*
* @author Jonathan Lermitage
*/
public class JaCoCoReportAnalyzer {
private JaCoCoReportAnalyzer() {
}
/**
* Load a JaCoCo binary report and convert it to XML.
*
* @param jacocoexec the JaCoCo binary report.
* @param xmlreport the XML file to generate.
* @param prjClassesDir the directory containing project's compiled classes.
* @param prjSourcesDir the directory containing project's Java source files.
* @throws FileNotFoundException if the JaCoCo binary report, compiled classes or Java sources files directory can't be found.
* @throws IOException if an I/O error occurs.
*/
public static void createXmlReport(File jacocoexec, File xmlreport, File prjClassesDir, File prjSourcesDir)
throws FileNotFoundException,
IOException {
xmlreport.delete();
// Load the JaCoCo binary report.
FileInputStream fis = new FileInputStream(jacocoexec);
- ExecutionDataReader executionDataReader = new ExecutionDataReader(fis);
ExecutionDataStore executionDataStore = new ExecutionDataStore();
SessionInfoStore sessionInfoStore = new SessionInfoStore();
- executionDataReader.setExecutionDataVisitor(executionDataStore);
- executionDataReader.setSessionInfoVisitor(sessionInfoStore);
try {
+ ExecutionDataReader executionDataReader = new ExecutionDataReader(fis);
+ executionDataReader.setExecutionDataVisitor(executionDataStore);
+ executionDataReader.setSessionInfoVisitor(sessionInfoStore);
while (executionDataReader.read()) {
}
} finally {
fis.close();
}
// Convert the binary report to XML.
CoverageBuilder coverageBuilder = new CoverageBuilder();
Analyzer analyzer = new Analyzer(executionDataStore, coverageBuilder);
analyzer.analyzeAll(prjClassesDir);
IBundleCoverage bundleCoverage = coverageBuilder.getBundle("JaCoCoverage analysis, powered by JaCoCo");
XMLFormatter xmlformatter = new XMLFormatter();
xmlformatter.setOutputEncoding("UTF-8");
IReportVisitor visitor = xmlformatter.createVisitor(new FileOutputStream(xmlreport));
visitor.visitInfo(sessionInfoStore.getInfos(), executionDataStore.getContents());
visitor.visitBundle(bundleCoverage, new DirectorySourceFileLocator(prjSourcesDir, "UTF-8", 4));
visitor.visitEnd();
}
}
| false | true | public static void createXmlReport(File jacocoexec, File xmlreport, File prjClassesDir, File prjSourcesDir)
throws FileNotFoundException,
IOException {
xmlreport.delete();
// Load the JaCoCo binary report.
FileInputStream fis = new FileInputStream(jacocoexec);
ExecutionDataReader executionDataReader = new ExecutionDataReader(fis);
ExecutionDataStore executionDataStore = new ExecutionDataStore();
SessionInfoStore sessionInfoStore = new SessionInfoStore();
executionDataReader.setExecutionDataVisitor(executionDataStore);
executionDataReader.setSessionInfoVisitor(sessionInfoStore);
try {
while (executionDataReader.read()) {
}
} finally {
fis.close();
}
// Convert the binary report to XML.
CoverageBuilder coverageBuilder = new CoverageBuilder();
Analyzer analyzer = new Analyzer(executionDataStore, coverageBuilder);
analyzer.analyzeAll(prjClassesDir);
IBundleCoverage bundleCoverage = coverageBuilder.getBundle("JaCoCoverage analysis, powered by JaCoCo");
XMLFormatter xmlformatter = new XMLFormatter();
xmlformatter.setOutputEncoding("UTF-8");
IReportVisitor visitor = xmlformatter.createVisitor(new FileOutputStream(xmlreport));
visitor.visitInfo(sessionInfoStore.getInfos(), executionDataStore.getContents());
visitor.visitBundle(bundleCoverage, new DirectorySourceFileLocator(prjSourcesDir, "UTF-8", 4));
visitor.visitEnd();
}
| public static void createXmlReport(File jacocoexec, File xmlreport, File prjClassesDir, File prjSourcesDir)
throws FileNotFoundException,
IOException {
xmlreport.delete();
// Load the JaCoCo binary report.
FileInputStream fis = new FileInputStream(jacocoexec);
ExecutionDataStore executionDataStore = new ExecutionDataStore();
SessionInfoStore sessionInfoStore = new SessionInfoStore();
try {
ExecutionDataReader executionDataReader = new ExecutionDataReader(fis);
executionDataReader.setExecutionDataVisitor(executionDataStore);
executionDataReader.setSessionInfoVisitor(sessionInfoStore);
while (executionDataReader.read()) {
}
} finally {
fis.close();
}
// Convert the binary report to XML.
CoverageBuilder coverageBuilder = new CoverageBuilder();
Analyzer analyzer = new Analyzer(executionDataStore, coverageBuilder);
analyzer.analyzeAll(prjClassesDir);
IBundleCoverage bundleCoverage = coverageBuilder.getBundle("JaCoCoverage analysis, powered by JaCoCo");
XMLFormatter xmlformatter = new XMLFormatter();
xmlformatter.setOutputEncoding("UTF-8");
IReportVisitor visitor = xmlformatter.createVisitor(new FileOutputStream(xmlreport));
visitor.visitInfo(sessionInfoStore.getInfos(), executionDataStore.getContents());
visitor.visitBundle(bundleCoverage, new DirectorySourceFileLocator(prjSourcesDir, "UTF-8", 4));
visitor.visitEnd();
}
|
diff --git a/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java b/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
index d6067e2..576233f 100644
--- a/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
+++ b/stripes/src/net/sourceforge/stripes/util/UrlBuilder.java
@@ -1,525 +1,525 @@
/* Copyright 2005-2006 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.config.Configuration;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.controller.UrlBinding;
import net.sourceforge.stripes.controller.UrlBindingFactory;
import net.sourceforge.stripes.controller.UrlBindingParameter;
import net.sourceforge.stripes.exception.StripesRuntimeException;
import net.sourceforge.stripes.format.Formatter;
import net.sourceforge.stripes.format.FormatterFactory;
import net.sourceforge.stripes.validation.ValidationMetadata;
import net.sourceforge.stripes.validation.ValidationMetadataProvider;
/**
* <p>Simple class that encapsulates the process of building up a URL from a path fragment
* and a zero or more parameters. Parameters can be single valued, array valued or
* collection valued. In the case of arrays and collections, each value in the array or
* collection will be added as a separate URL parameter (with the same name). The assembled
* URL can then be retrieved by calling toString().</p>
*
* <p>While not immediately obvious, it is possible to add a single parameter with multiple
* values by invoking the addParameter() method that uses varargs, and supplying a Collection as
* the single parameter value to the method.</p>
*
* @author Tim Fennell
* @since Stripes 1.1.2
*/
public class UrlBuilder {
/**
* Holds the name and value of a parameter to be appended to the URL.
*/
private static class Parameter {
String name;
Object value;
Parameter(String name, Object value) {
this.name = name;
this.value = value;
}
public boolean isEvent() {
return UrlBindingParameter.PARAMETER_NAME_EVENT.equals(name);
}
@Override
public String toString() {
return "" + this.name + "=" + this.value;
}
}
private String baseUrl;
private String anchor;
private Locale locale;
private String parameterSeparator;
private Parameter event;
private List<Parameter> parameters = new ArrayList<Parameter>();
private String url;
/**
* Constructs a UrlBuilder with the path to a resource. Parameters can be added
* later using addParameter(). If the link is to be used in a page then the ampersand
* character usually used to separate parameters will be escaped using the XML entity
* for ampersand.
*
* @param url the path part of the URL
* @param isForPage true if the URL is to be embedded in a page (e.g. in an anchor of img
* tag), false if for some other purpose.
* @deprecated As of Stripes 1.5, this constructor has been replaced by
* {@link #UrlBuilder(Locale, String, boolean)}.
*/
@Deprecated
public UrlBuilder(String url, boolean isForPage) {
this(Locale.getDefault(), url, isForPage);
}
/**
* Constructs a UrlBuilder with the path to a resource. Parameters can be added
* later using addParameter(). If the link is to be used in a page then the ampersand
* character usually used to separate parameters will be escaped using the XML entity
* for ampersand.
*
* @param locale the locale to use when formatting parameters with a {@link Formatter}
* @param url the path part of the URL
* @param isForPage true if the URL is to be embedded in a page (e.g. in an anchor of img
* tag), false if for some other purpose.
*/
public UrlBuilder(Locale locale, String url, boolean isForPage) {
this(locale, isForPage);
if (url != null) {
// Check to see if there is an embedded anchor, and strip it out for later
int index = url.indexOf('#');
if (index != -1) {
if (index < url.length() - 1) {
this.anchor = url.substring(index + 1);
}
url = url.substring(0, index);
}
this.baseUrl = url;
}
}
/**
* Constructs a UrlBuilder that references an {@link ActionBean}. Parameters can be added later
* using addParameter(). If the link is to be used in a page then the ampersand character
* usually used to separate parameters will be escaped using the XML entity for ampersand.
*
* @param locale the locale to use when formatting parameters with a {@link Formatter}
* @param beanType {@link ActionBean} class for which the URL will be built
* @param isForPage true if the URL is to be embedded in a page (e.g. in an anchor of img tag),
* false if for some other purpose.
*/
public UrlBuilder(Locale locale, Class<? extends ActionBean> beanType, boolean isForPage) {
this(locale, isForPage);
Configuration configuration = StripesFilter.getConfiguration();
if (configuration != null) {
this.baseUrl = configuration.getActionResolver().getUrlBinding(beanType);
}
else {
throw new StripesRuntimeException("Unable to lookup URL binding for ActionBean class "
+ "because there is no Configuration object available.");
}
}
/**
* Sets the locale and sets the parameter separator based on the value of <code>isForPage</code>.
*
* @param locale the locale to use when formatting parameters with a {@link Formatter}
* @param isForPage true if the URL is to be embedded in a page (e.g. in an anchor of img tag),
* false if for some other purpose.
*/
protected UrlBuilder(Locale locale, boolean isForPage) {
this.locale = locale;
if (isForPage) {
this.parameterSeparator = "&";
}
else {
this.parameterSeparator = "&";
}
}
/**
* Get the name of the event to be executed by this URL.
*/
public String getEvent() {
return (String) (event == null ? null : event.value);
}
/**
* Set the name of the event to be executed by this URL. A default event name can be defined for
* an {@link ActionBean} using either {@link DefaultHandler} or by assigning a default value to
* the $event parameter in a clean URL. If {@code event} is null then the default event name
* will be ignored and no event parameter will be added to the URL.
*
* @param event the event name
*/
public UrlBuilder setEvent(String event) {
this.event = new Parameter(UrlBindingParameter.PARAMETER_NAME_EVENT, event);
return this;
}
/**
* Returns the string that will be used to separate parameters in the query string.
* Will usually be either '&' for query strings that will be embedded in HTML
* pages and '&' otherwise.
*/
public String getParameterSeparator() { return parameterSeparator; }
/**
* Sets the string that will be used to separate parameters. By default the values is a
* single ampersand character. If the URL is to be embedded in a page the value should be
* set to the XML ampersand entity.
*/
public void setParameterSeparator(String parameterSeparator) {
this.parameterSeparator = parameterSeparator;
}
/**
* <p>Appends one or more values of a parameter to the URL. Checks to see if each value is
* null, and if so generates a parameter with no value. URL Encodes the parameter values
* to make sure that it is safe to insert into the URL.</p>
*
* <p>If any parameter value passed is a Collection or an Array then this method is called
* recursively with the contents of the collection or array. As a result you can pass
* arbitrarily nested arrays and collections to this method and it will recurse through them
* adding all scalar values as parameters to the URL.</p.
*
* @param name the name of the request parameter being added
* @param values one or more values for the parameter supplied
*/
public UrlBuilder addParameter(String name, Object... values) {
// If values is null or empty, then simply sub in a single empty string
if (values == null || values.length == 0) {
values = Literal.array("");
}
for (Object v : values) {
// Special case: recurse for nested collections and arrays!
if (v instanceof Collection) {
addParameter(name, ((Collection<?>) v).toArray());
}
else if (v != null && v.getClass().isArray()) {
addParameter(name, CollectionUtil.asObjectArray(v));
}
else {
parameters.add(new Parameter(name, v));
url = null;
}
}
return this;
}
/**
* Appends one or more parameters to the URL. Various assumptions are made about the Map
* parameter. Firstly, that the keys are all either Strings, or objects that can be safely
* toString()'d to yield parameter names. Secondly that the values either toString() to form
* a single parameter value, or are arrays or collections that contain toString()'able
* objects.
*
* @param parameters a non-null Map as described above
*/
public UrlBuilder addParameters(Map<? extends Object,? extends Object> parameters) {
for (Map.Entry<? extends Object,? extends Object> parameter : parameters.entrySet()) {
String name = parameter.getKey().toString();
Object valueOrValues = parameter.getValue();
if (valueOrValues == null) {
addParameter(name, (Object) null);
}
else if (valueOrValues.getClass().isArray()) {
addParameter(name, CollectionUtil.asObjectArray(valueOrValues));
}
else if (valueOrValues instanceof Collection) {
addParameter(name, (Collection<?>) valueOrValues);
}
else {
addParameter(name, valueOrValues);
}
}
return this;
}
/**
* Gets the anchor, if any, that will be appended to the URL. E.g. if this method
* returns 'input' then the URL will be terminated with '#input' in order to instruct
* the browser to navigate to the HTML anchor called 'input' when accessing the URL.
*
* @return the anchor (if any) without the leading pound sign, or null
*/
public String getAnchor() { return anchor; }
/**
* Sets the anchor, if any, that will be appended to the URL. E.g. if supplied with
* 'input' then the URL will be terminated with '#input' in order to instruct
* the browser to navigate to the HTML anchor called 'input' when accessing the URL.
*
* @param anchor the anchor with or without the leading pound sign, or null to disable
*/
public UrlBuilder setAnchor(String anchor) {
if (anchor != null && anchor.startsWith("#") && anchor.length() > 1) {
this.anchor = anchor.substring(1);
}
else {
this.anchor = anchor;
}
return this;
}
/**
* Returns the URL composed thus far as a String. All paramter values will have been
* URL encoded and appended to the URL before returning it.
*/
@Override
public String toString() {
if (url == null) {
url = build();
}
if (this.anchor != null && this.anchor.length() > 0) {
return url + "#" + this.anchor;
}
else {
return url;
}
}
/**
* Attempts to format an object using an appropriate {@link Formatter}. If
* no formatter is available for the object, then this method will call
* <code>toString()</code> on the object. A null <code>value</code> will
* be formatted as an empty string.
*
* @param value
* the object to be formatted
* @return the formatted value
*/
@SuppressWarnings("unchecked")
protected String format(Object value) {
if (value == null) {
return "";
}
else {
Formatter formatter = getFormatter(value);
if (formatter == null)
return value.toString();
else
return formatter.format(value);
}
}
/**
* Tries to get a formatter for the given value using the {@link FormatterFactory}. Returns
* null if there is no {@link Configuration} or {@link FormatterFactory} available (e.g. in a
* test environment) or if there is no {@link Formatter} configured for the value's type.
*
* @param value the object to be formatted
* @return a formatter, if one can be found; null otherwise
*/
@SuppressWarnings("unchecked")
protected Formatter getFormatter(Object value) {
Configuration configuration = StripesFilter.getConfiguration();
if (configuration == null)
return null;
FormatterFactory factory = configuration.getFormatterFactory();
if (factory == null)
return null;
return factory.getFormatter(value.getClass(), locale, null, null);
}
/**
* Get a map of property names to {@link ValidationMetadata} for the {@link ActionBean} class
* bound to the URL being built. If the URL does not point to an ActionBean class or no
* validation metadata exists for the ActionBean class then an empty map will be returned.
*
* @return a map of ActionBean property names to their validation metadata
* @see ValidationMetadataProvider#getValidationMetadata(Class)
*/
protected Map<String, ValidationMetadata> getValidationMetadata() {
Map<String, ValidationMetadata> validations = null;
Configuration configuration = StripesFilter.getConfiguration();
if (configuration != null) {
Class<? extends ActionBean> beanType = configuration.getActionResolver()
.getActionBeanType(this.baseUrl);
if (beanType != null) {
validations = configuration.getValidationMetadataProvider().getValidationMetadata(
beanType);
}
}
if (validations == null)
validations = Collections.emptyMap();
return validations;
}
/**
* Build and return the URL
*/
protected String build() {
// special handling for event parameter
List<Parameter> parameters = new ArrayList<Parameter>(this.parameters.size() + 1);
if (this.event != null) {
parameters.add(this.event);
}
parameters.addAll(this.parameters);
// lookup validation info for the bean class to find encrypted properties
Map<String, ValidationMetadata> validations = getValidationMetadata();
StringBuilder buffer = new StringBuilder(256);
buffer.append(getBaseURL(this.baseUrl, parameters));
boolean seenQuestionMark = buffer.indexOf("?") != -1;
for (Parameter param : parameters) {
// special handling for event parameter
if (param == this.event) {
if (param.value == null)
continue;
else
param = new Parameter((String) this.event.value, "");
}
// Figure out whether we already have params or not
if (!seenQuestionMark) {
buffer.append('?');
seenQuestionMark = true;
}
else {
buffer.append(getParameterSeparator());
}
buffer.append(StringUtil.urlEncode(param.name)).append('=');
if (param.value != null) {
ValidationMetadata validation = validations.get(param.name);
String formatted = format(param.value);
if (validation != null && validation.encrypted())
formatted = CryptoUtil.encrypt(formatted);
buffer.append(StringUtil.urlEncode(formatted));
}
}
return buffer.toString();
}
/**
* Get the base URL (without a query string). If a {@link UrlBinding} exists for the URL or
* {@link ActionBean} type that was passed into the constructor, then this method will return
* the base URL after appending any URI parameters that have been added with a call to
* {@link #addParameter(String, Object[])} or {@link #addParameters(Map)}. Otherwise, it
* returns the original base URL.
*
* @param baseUrl The base URL to start with. In many cases, this value will be returned
* unchanged.
* @param parameters The query parameters. Any parameters that should not be appended to the
* query string by {@link #build()} (e.g., because they are embedded in the URL)
* should be removed from the collection before this method returns.
* @return the base URL, without a query string
* @see #UrlBuilder(Locale, Class, boolean)
* @see #UrlBuilder(Locale, String, boolean)
*/
protected String getBaseURL(String baseUrl, Collection<Parameter> parameters) {
UrlBinding binding = UrlBindingFactory.getInstance().getBindingPrototype(baseUrl);
if (binding == null || binding.getParameters().size() == 0) {
return baseUrl;
}
// if any extra path info is present then do not add URI parameters
if (binding.getPath().length() < baseUrl.length()) {
return baseUrl;
}
// lookup validation info for the bean class to find encrypted properties
Map<String, ValidationMetadata> validations = getValidationMetadata();
// map the declared URI parameter names to values
Map<String, Parameter> map = new HashMap<String, Parameter>();
for (Parameter p : parameters) {
if (!map.containsKey(p.name))
map.put(p.name, p);
}
StringBuilder buf = new StringBuilder(256);
buf.append(baseUrl);
String nextLiteral = null;
for (Object component : binding.getComponents()) {
if (component instanceof String) {
nextLiteral = (String) component;
}
else if (component instanceof UrlBindingParameter) {
boolean ok = false;
// get the value for the parameter, falling back to default value if present
UrlBindingParameter parameter = (UrlBindingParameter) component;
Parameter assigned = map.get(parameter.getName());
Object value;
if (assigned != null && (assigned.value != null || assigned.isEvent()))
value = assigned.value;
else
value = parameter.getDefaultValue();
if (value != null) {
// format (and maybe encrypt) the value as a string
String formatted = format(value);
ValidationMetadata validation = validations.get(parameter.getName());
if (validation != null && validation.encrypted())
formatted = CryptoUtil.encrypt(formatted);
// if after formatting we still have a value then embed it in the URI
if (formatted != null && formatted.length() > 0) {
if (nextLiteral != null) {
buf.append(nextLiteral);
}
- buf.append(formatted);
+ buf.append(StringUtil.urlEncode(formatted));
parameters.remove(assigned);
ok = true;
}
}
else if (assigned != null && assigned.isEvent()) {
// remove event parameter even if value is null
parameters.remove(assigned);
}
nextLiteral = null;
if (!ok)
break;
}
}
// always append trailing literal if one is present
if (nextLiteral != null) {
buf.append(nextLiteral);
}
else if (binding.getSuffix() != null) {
buf.append(binding.getSuffix());
}
return buf.toString();
}
}
| true | true | protected String getBaseURL(String baseUrl, Collection<Parameter> parameters) {
UrlBinding binding = UrlBindingFactory.getInstance().getBindingPrototype(baseUrl);
if (binding == null || binding.getParameters().size() == 0) {
return baseUrl;
}
// if any extra path info is present then do not add URI parameters
if (binding.getPath().length() < baseUrl.length()) {
return baseUrl;
}
// lookup validation info for the bean class to find encrypted properties
Map<String, ValidationMetadata> validations = getValidationMetadata();
// map the declared URI parameter names to values
Map<String, Parameter> map = new HashMap<String, Parameter>();
for (Parameter p : parameters) {
if (!map.containsKey(p.name))
map.put(p.name, p);
}
StringBuilder buf = new StringBuilder(256);
buf.append(baseUrl);
String nextLiteral = null;
for (Object component : binding.getComponents()) {
if (component instanceof String) {
nextLiteral = (String) component;
}
else if (component instanceof UrlBindingParameter) {
boolean ok = false;
// get the value for the parameter, falling back to default value if present
UrlBindingParameter parameter = (UrlBindingParameter) component;
Parameter assigned = map.get(parameter.getName());
Object value;
if (assigned != null && (assigned.value != null || assigned.isEvent()))
value = assigned.value;
else
value = parameter.getDefaultValue();
if (value != null) {
// format (and maybe encrypt) the value as a string
String formatted = format(value);
ValidationMetadata validation = validations.get(parameter.getName());
if (validation != null && validation.encrypted())
formatted = CryptoUtil.encrypt(formatted);
// if after formatting we still have a value then embed it in the URI
if (formatted != null && formatted.length() > 0) {
if (nextLiteral != null) {
buf.append(nextLiteral);
}
buf.append(formatted);
parameters.remove(assigned);
ok = true;
}
}
else if (assigned != null && assigned.isEvent()) {
// remove event parameter even if value is null
parameters.remove(assigned);
}
nextLiteral = null;
if (!ok)
break;
}
}
// always append trailing literal if one is present
if (nextLiteral != null) {
buf.append(nextLiteral);
}
else if (binding.getSuffix() != null) {
buf.append(binding.getSuffix());
}
return buf.toString();
}
| protected String getBaseURL(String baseUrl, Collection<Parameter> parameters) {
UrlBinding binding = UrlBindingFactory.getInstance().getBindingPrototype(baseUrl);
if (binding == null || binding.getParameters().size() == 0) {
return baseUrl;
}
// if any extra path info is present then do not add URI parameters
if (binding.getPath().length() < baseUrl.length()) {
return baseUrl;
}
// lookup validation info for the bean class to find encrypted properties
Map<String, ValidationMetadata> validations = getValidationMetadata();
// map the declared URI parameter names to values
Map<String, Parameter> map = new HashMap<String, Parameter>();
for (Parameter p : parameters) {
if (!map.containsKey(p.name))
map.put(p.name, p);
}
StringBuilder buf = new StringBuilder(256);
buf.append(baseUrl);
String nextLiteral = null;
for (Object component : binding.getComponents()) {
if (component instanceof String) {
nextLiteral = (String) component;
}
else if (component instanceof UrlBindingParameter) {
boolean ok = false;
// get the value for the parameter, falling back to default value if present
UrlBindingParameter parameter = (UrlBindingParameter) component;
Parameter assigned = map.get(parameter.getName());
Object value;
if (assigned != null && (assigned.value != null || assigned.isEvent()))
value = assigned.value;
else
value = parameter.getDefaultValue();
if (value != null) {
// format (and maybe encrypt) the value as a string
String formatted = format(value);
ValidationMetadata validation = validations.get(parameter.getName());
if (validation != null && validation.encrypted())
formatted = CryptoUtil.encrypt(formatted);
// if after formatting we still have a value then embed it in the URI
if (formatted != null && formatted.length() > 0) {
if (nextLiteral != null) {
buf.append(nextLiteral);
}
buf.append(StringUtil.urlEncode(formatted));
parameters.remove(assigned);
ok = true;
}
}
else if (assigned != null && assigned.isEvent()) {
// remove event parameter even if value is null
parameters.remove(assigned);
}
nextLiteral = null;
if (!ok)
break;
}
}
// always append trailing literal if one is present
if (nextLiteral != null) {
buf.append(nextLiteral);
}
else if (binding.getSuffix() != null) {
buf.append(binding.getSuffix());
}
return buf.toString();
}
|
diff --git a/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java b/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java
index 5e75616d..ea8eb8cb 100644
--- a/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java
+++ b/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/ComponentManagerImpl.java
@@ -1,436 +1,439 @@
/*
* (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*/
package org.nuxeo.runtime.model.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.common.collections.ListenerList;
import org.nuxeo.runtime.ComponentEvent;
import org.nuxeo.runtime.ComponentListener;
import org.nuxeo.runtime.RuntimeService;
import org.nuxeo.runtime.model.ComponentInstance;
import org.nuxeo.runtime.model.ComponentManager;
import org.nuxeo.runtime.model.ComponentName;
import org.nuxeo.runtime.model.Extension;
import org.nuxeo.runtime.model.RegistrationInfo;
import org.nuxeo.runtime.remoting.RemoteContext;
/**
* @author <a href="mailto:[email protected]">Bogdan Stefanescu</a>
*
*/
public class ComponentManagerImpl implements ComponentManager {
private static final Log log = LogFactory.getLog(ComponentManager.class);
protected final Map<ComponentName, Set<Extension>> pendingExtensions;
private ListenerList listeners;
private Map<ComponentName, RegistrationInfoImpl> registry;
private Map<ComponentName, Set<RegistrationInfoImpl>> dependsOnMe;
private final Map<String, RegistrationInfoImpl> services;
public ComponentManagerImpl(RuntimeService runtime) {
registry = new HashMap<ComponentName, RegistrationInfoImpl>();
dependsOnMe = new HashMap<ComponentName, Set<RegistrationInfoImpl>>();
pendingExtensions = new HashMap<ComponentName, Set<Extension>>();
listeners = new ListenerList();
services = new Hashtable<String, RegistrationInfoImpl>();
}
public Collection<RegistrationInfo> getRegistrations() {
return new ArrayList<RegistrationInfo>(registry.values());
}
public Collection<ComponentName> getPendingRegistrations() {
List<ComponentName> names = new ArrayList<ComponentName>();
for (RegistrationInfo ri : registry.values()) {
if (ri.getState() == RegistrationInfo.REGISTERED) {
names.add(ri.getName());
}
}
return names;
}
public Collection<ComponentName> getNeededRegistrations() {
return pendingExtensions.keySet();
}
public Collection<Extension> getPendingExtensions(ComponentName name) {
return pendingExtensions.get(name);
}
public RegistrationInfo getRegistrationInfo(ComponentName name) {
return registry.get(name);
}
public synchronized boolean isRegistered(ComponentName name) {
return registry.containsKey(name);
}
public synchronized int size() {
return registry.size();
}
public ComponentInstance getComponent(ComponentName name) {
RegistrationInfoImpl ri = registry.get(name);
return ri != null ? ri.getComponent() : null;
}
public synchronized void shutdown() {
// unregister me -> this will unregister all objects that depends on me
List<RegistrationInfo> elems = new ArrayList<RegistrationInfo>(
registry.values());
for (RegistrationInfo ri : elems) {
try {
unregister(ri);
} catch (Exception e) {
log.error("failed to shutdown component manager", e);
}
}
try {
listeners = null;
registry.clear();
registry = null;
dependsOnMe.clear();
dependsOnMe = null;
} catch (Exception e) {
log.error("Failed to shutdown registry manager");
}
}
public synchronized void register(RegistrationInfo regInfo) {
_register((RegistrationInfoImpl) regInfo);
}
public final void _register(RegistrationInfoImpl ri) {
ComponentName name = ri.getName();
if (isRegistered(name)) {
- //log.warn("Component was already registered: " + name);
- throw new IllegalStateException("Component was already registered: " + name);
+ log.warn("Component was already registered: " + name);
+ // TODO avoid throwing an exception here - for now runtime components are registered twice
+ // When this will be fixed we can thrown an error here
+ return;
+ //throw new IllegalStateException("Component was already registered: " + name);
}
ri.manager = this;
try {
ri.register();
} catch (Exception e) {
log.error("Failed to register component: " + ri.getName(), e);
return;
}
// compute blocking dependencies
boolean hasBlockingDeps = computeBlockingDependencies(ri);
// check if blocking dependencies were found
if (!hasBlockingDeps) {
// check if there is any object waiting for me
Set<RegistrationInfoImpl> pendings = removeDependencies(name);
// update set the dependsOnMe member
ri.dependsOnMe = pendings;
// no blocking dependencies found - register it
log.info("Registering component: " + ri.getName());
// create the component
try {
registry.put(ri.name, ri);
ri.resolve();
// if some objects are waiting for me notify them about my registration
if (ri.dependsOnMe != null) {
// notify all components that deonds on me about my registration
for (RegistrationInfoImpl pending : ri.dependsOnMe) {
if (pending.waitsFor == null) {
_register(pending);
} else {
// remove object dependence on me
pending.waitsFor.remove(name);
// if object has no more dependencies register it
if (pending.waitsFor.isEmpty()) {
pending.waitsFor = null;
_register(pending);
}
}
}
}
} catch (Exception e) {
log.error("Failed to create the component " + ri.name, e);
}
} else {
log.info("Registration delayed for component: " + name
+ ". Waiting for: " + ri.waitsFor);
}
}
public synchronized void unregister(RegistrationInfo regInfo) {
_unregister((RegistrationInfoImpl) regInfo);
}
public final void _unregister(RegistrationInfoImpl ri) {
// remove me as a dependent on other objects
if (ri.requires != null) {
for (ComponentName dep : ri.requires) {
RegistrationInfoImpl depRi = registry.get(dep);
if (depRi != null) { // can be null if comp is unresolved and waiting for this dep.
if (depRi.dependsOnMe != null) {
depRi.dependsOnMe.remove(ri);
}
}
}
}
// unresolve also the dependent objects
if (ri.dependsOnMe != null) {
List<RegistrationInfoImpl> deps = new ArrayList<RegistrationInfoImpl>(
ri.dependsOnMe);
for (RegistrationInfoImpl dep : deps) {
try {
dep.unresolve();
// TODO ------------- keep waiting comp. in the registry - otherwise the unresolved comp will never be unregistered
// add a blocking dependence on me
if (dep.waitsFor == null) {
dep.waitsFor = new HashSet<ComponentName>();
}
dep.waitsFor.add(ri.name);
addDependency(ri.name, dep);
// remove from registry
registry.remove(dep);
// TODO -------------
} catch (Exception e) {
log.error("Failed to unresolve component: " + dep.getName(), e);
}
}
}
log.info("Unregistering component: " + ri.name);
try {
if (registry.remove(ri.name) == null) {
// may be a pending component
//TODO -> put pendings in the registry
}
ri.unregister();
} catch (Exception e) {
log.error("Failed to unregister component: " + ri.getName(), e);
}
}
public synchronized void unregister(ComponentName name) {
RegistrationInfoImpl ri = registry.get(name);
if (ri != null) {
_unregister(ri);
}
}
public void addComponentListener(ComponentListener listener) {
listeners.add(listener);
}
public void removeComponentListener(ComponentListener listener) {
listeners.remove(listener);
}
void sendEvent(ComponentEvent event) {
log.debug("Dispatching event: " + event);
Object[] listeners = this.listeners.getListeners();
for (Object listener : listeners) {
((ComponentListener) listener).handleEvent(event);
}
}
protected boolean computeBlockingDependencies(RegistrationInfoImpl ri) {
if (ri.requires != null) {
for (ComponentName dep : ri.requires) {
RegistrationInfoImpl depRi = registry.get(dep);
if (depRi == null) {
// dep is not yet registered - add it to the blocking deps queue
if (ri.waitsFor == null) {
ri.waitsFor = new HashSet<ComponentName>();
}
ri.waitsFor.add(dep);
addDependency(dep, ri);
} else {
// we need this when unregistering depRi
// to be able to unregister dependent components
if (depRi.dependsOnMe == null) {
depRi.dependsOnMe = new HashSet<RegistrationInfoImpl>();
}
depRi.dependsOnMe.add(ri);
}
}
}
return ri.waitsFor != null;
}
protected synchronized void addDependency(ComponentName name,
RegistrationInfoImpl dependent) {
Set<RegistrationInfoImpl> pendings = dependsOnMe.get(name);
if (pendings == null) {
pendings = new HashSet<RegistrationInfoImpl>();
dependsOnMe.put(name, pendings);
}
pendings.add(dependent);
}
protected synchronized Set<RegistrationInfoImpl> removeDependencies(
ComponentName name) {
return dependsOnMe.remove(name);
}
public void registerExtension(Extension extension) throws Exception {
ComponentName name = extension.getTargetComponent();
RegistrationInfoImpl ri = registry.get(name);
if (ri != null) {
if (log.isDebugEnabled()) {
log.debug("Register contributed extension: " + extension);
}
loadContributions(ri, extension);
ri.component.registerExtension(extension);
if (!(extension.getContext() instanceof RemoteContext)) {
// TODO avoid resending events when remoting extensions are registered
// - temporary hack - find something better
sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_REGISTERED,
((ComponentInstanceImpl) extension.getComponent()).ri, extension));
}
} else { // put the extension in the pending queue
if (log.isDebugEnabled()) {
log.debug("Enqueue contributed extension to pending queue: " + extension);
}
Set<Extension> extensions = pendingExtensions.get(name);
if (extensions == null) {
extensions = new HashSet<Extension>();
pendingExtensions.put(name, extensions);
}
extensions.add(extension);
if (!(extension.getContext() instanceof RemoteContext)) {
// TODO avoid resending events when remoting extensions are registered
// - temporary hack - find something better
sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_PENDING,
((ComponentInstanceImpl) extension.getComponent()).ri, extension));
}
}
}
public void unregisterExtension(Extension extension) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Unregister contributed extension: " + extension);
}
ComponentName name = extension.getTargetComponent();
RegistrationInfo ri = registry.get(name);
if (ri != null) {
ComponentInstance co = ri.getComponent();
if (co != null) {
co.unregisterExtension(extension);
}
} else { // maybe it's pending
Set<Extension> extensions = pendingExtensions.get(name);
if (extensions != null) {
// FIXME: extensions is a set of Extensions, not ComponentNames.
extensions.remove(name);
if (extensions.isEmpty()) {
pendingExtensions.remove(name);
}
}
}
if (!(extension.getContext() instanceof RemoteContext)) {
// TODO avoid resending events when remoting extensions are
// registered - temporary hack - find something better
sendEvent(new ComponentEvent(ComponentEvent.EXTENSION_UNREGISTERED,
((ComponentInstanceImpl) extension.getComponent()).ri,
extension));
}
}
public static void loadContributions(RegistrationInfoImpl ri, Extension xt) {
ExtensionPointImpl xp = ri.getExtensionPoint(xt.getExtensionPoint());
if (xp != null && xp.contributions != null) {
try {
Object[] contribs = xp.loadContributions(ri, xt);
xt.setContributions(contribs);
} catch (Exception e) {
log.error("Failed to create contribution objects", e);
}
}
}
public void registerServices(RegistrationInfoImpl ri) {
if (ri.serviceDescriptor == null) {
return;
}
for (String service : ri.serviceDescriptor.services) {
log.info("Registering service" + service);
services.put(service, ri);
// TODO: send notifications
}
}
public void unregisterServices(RegistrationInfoImpl ri) {
if (ri.serviceDescriptor == null) {
return;
}
for (String service : ri.serviceDescriptor.services) {
services.remove(service);
// TODO: send notifications
}
}
public String[] getServices() {
return services.keySet().toArray(new String[services.size()]);
}
public <T> T getService(Class<T> serviceClass) {
try {
RegistrationInfoImpl ri = services.get(serviceClass.getName());
if (ri == null) {
log.error("Service unknown: " + serviceClass.getName());
} else {
if (!ri.isActivated()) {
if (ri.isResolved()) {
ri.activate(); // activate the component if not yet activated
} else {
log.warn("The component exposing the service " + serviceClass
+ " is not resolved - should be a bug.");
return null;
}
}
return ri.getComponent().getAdapter(serviceClass);
}
} catch (Exception e) {
log.error("Failed to get service: " + serviceClass);
}
return null;
}
}
| true | true | public final void _register(RegistrationInfoImpl ri) {
ComponentName name = ri.getName();
if (isRegistered(name)) {
//log.warn("Component was already registered: " + name);
throw new IllegalStateException("Component was already registered: " + name);
}
ri.manager = this;
try {
ri.register();
} catch (Exception e) {
log.error("Failed to register component: " + ri.getName(), e);
return;
}
// compute blocking dependencies
boolean hasBlockingDeps = computeBlockingDependencies(ri);
// check if blocking dependencies were found
if (!hasBlockingDeps) {
// check if there is any object waiting for me
Set<RegistrationInfoImpl> pendings = removeDependencies(name);
// update set the dependsOnMe member
ri.dependsOnMe = pendings;
// no blocking dependencies found - register it
log.info("Registering component: " + ri.getName());
// create the component
try {
registry.put(ri.name, ri);
ri.resolve();
// if some objects are waiting for me notify them about my registration
if (ri.dependsOnMe != null) {
// notify all components that deonds on me about my registration
for (RegistrationInfoImpl pending : ri.dependsOnMe) {
if (pending.waitsFor == null) {
_register(pending);
} else {
// remove object dependence on me
pending.waitsFor.remove(name);
// if object has no more dependencies register it
if (pending.waitsFor.isEmpty()) {
pending.waitsFor = null;
_register(pending);
}
}
}
}
} catch (Exception e) {
log.error("Failed to create the component " + ri.name, e);
}
} else {
log.info("Registration delayed for component: " + name
+ ". Waiting for: " + ri.waitsFor);
}
}
| public final void _register(RegistrationInfoImpl ri) {
ComponentName name = ri.getName();
if (isRegistered(name)) {
log.warn("Component was already registered: " + name);
// TODO avoid throwing an exception here - for now runtime components are registered twice
// When this will be fixed we can thrown an error here
return;
//throw new IllegalStateException("Component was already registered: " + name);
}
ri.manager = this;
try {
ri.register();
} catch (Exception e) {
log.error("Failed to register component: " + ri.getName(), e);
return;
}
// compute blocking dependencies
boolean hasBlockingDeps = computeBlockingDependencies(ri);
// check if blocking dependencies were found
if (!hasBlockingDeps) {
// check if there is any object waiting for me
Set<RegistrationInfoImpl> pendings = removeDependencies(name);
// update set the dependsOnMe member
ri.dependsOnMe = pendings;
// no blocking dependencies found - register it
log.info("Registering component: " + ri.getName());
// create the component
try {
registry.put(ri.name, ri);
ri.resolve();
// if some objects are waiting for me notify them about my registration
if (ri.dependsOnMe != null) {
// notify all components that deonds on me about my registration
for (RegistrationInfoImpl pending : ri.dependsOnMe) {
if (pending.waitsFor == null) {
_register(pending);
} else {
// remove object dependence on me
pending.waitsFor.remove(name);
// if object has no more dependencies register it
if (pending.waitsFor.isEmpty()) {
pending.waitsFor = null;
_register(pending);
}
}
}
}
} catch (Exception e) {
log.error("Failed to create the component " + ri.name, e);
}
} else {
log.info("Registration delayed for component: " + name
+ ". Waiting for: " + ri.waitsFor);
}
}
|
diff --git a/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java b/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java
index a1b1bba0a..1994a697d 100644
--- a/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java
+++ b/src/webapp/src/java/org/wyona/yanel/servlet/menu/TransitionMenuContentImpl.java
@@ -1,132 +1,132 @@
/**
*
*/
package org.wyona.yanel.servlet.menu;
import org.apache.log4j.Logger;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.workflow.Transition;
import org.wyona.yanel.core.workflow.Workflow;
import org.wyona.yanel.core.workflow.WorkflowException;
import org.wyona.yanel.core.workflow.WorkflowHelper;
/**
* Creates an html element wrapping the transition of a resource from a given state.
* The element contains an appropriately formatted URL (i.e. GET request) as an
* anchor if the transition is valid.
*/
public class TransitionMenuContentImpl implements ITransitionMenuContent {
private static Logger log = Logger.getLogger(TransitionMenuContentImpl.class);
private static final String RESOURCE_REVN_ARG = "yanel.resource.revision=";
private static final String RESOURCE_TRANSITION_ARG = "yanel.resource.workflow.transition=";
private static final String RESOURCE_TRANSITION_OUTPUT = "yanel.resource.workflow.transition.output";
private static final String STYLE_INACTIVE = "inactive";
private Resource resource;
private String state;
private String revision;
private String isoMenuLang;
/**
* ctor.
* @param resource the resource which the transitions are "from"
* @param status status of the revision (draft, review, etc.)
* @param revision revn the revision of the resource which the transitions are "from"
* @param langCode desired language of the resulting menu
*/
public TransitionMenuContentImpl(final Resource resource, final String status, final String revision, final String langCode) {
this.resource = resource;
this.state = status;
this.revision = revision;
this.isoMenuLang = langCode.toLowerCase();
}
/**
* Returns an html <li> element containing either an html <a> element to
* activate the desired action, or plain text if it is not allowed to take
* the action.
* based on the revision state.
* @param t
* @return
*/
public String getTransitionElement(final Transition t) {
- log.warn("DEBUG: Transition: " + t.getID());
+ if(log.isDebugEnabled()) log.debug("Transition: " + t.getID());
try {
Workflow workflow = WorkflowHelper.getWorkflow(this.resource);
Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state);
String label = t.getID() + " (WARNING: No label!)";
try {
label = t.getDescription(this.resource.getRequestedLanguage());
} catch(Exception e) {
log.error(e, e);
}
for (int i = 0; i < stateSpecificTransitions.length; i++) {
if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) {
try {
String url = getTransitionURL(t.getID());
log.warn("DEBUG: Active transition: " + label);
return "<li>" + new AnchorElement(label, url).toString() + "</li>";
} catch (Exception e) {
log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?!
log.warn(e, e);
}
}
}
log.warn("DEBUG: Inactive transition: " + label);
return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>";
} catch (Exception e) {
log.error(e, e);
return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>";
}
}
/**
* Two transitions match if they have the same ID.
* @param t1 Transition 1
* @param t2 Transition 2
* @return true if they match, else false
*/
private boolean transitionsMatch(final Transition t1, final Transition t2) {
return t1.getID().equals(t2.getID());
}
private String getTransitionURL(final String transitionId) throws Exception {
String url = getResourceURL();
String submit = RESOURCE_TRANSITION_ARG + transitionId;
URLBuilder builder = new URLBuilder();
builder.createURL(url, submit);
builder.addParameter(RESOURCE_REVN_ARG, this.revision);
builder.addParameter(RESOURCE_TRANSITION_OUTPUT, "xhtml");
return builder.getURL();
}
private String getResourceURL() throws Exception {
String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(this.resource.getPath());
String url = backToRealm + this.resource.getPath();
url = url.replaceAll("//", "/");
return url;
}
/**
* Also see org/wyona/yanel/core/workflow/WorkflowHelper#canDoTransition() or #getWorkflowIntrospection()
*/
private boolean isComplied(Transition transition, Workflow workflow) throws Exception {
org.wyona.yanel.core.workflow.Condition[] conditions = transition.getConditions();
for (int k = 0; k < conditions.length; k++) {
if (!conditions[k].isComplied((org.wyona.yanel.core.api.attributes.WorkflowableV1) resource, workflow, revision)) {
return false;
}
}
return true;
}
}
| true | true | public String getTransitionElement(final Transition t) {
log.warn("DEBUG: Transition: " + t.getID());
try {
Workflow workflow = WorkflowHelper.getWorkflow(this.resource);
Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state);
String label = t.getID() + " (WARNING: No label!)";
try {
label = t.getDescription(this.resource.getRequestedLanguage());
} catch(Exception e) {
log.error(e, e);
}
for (int i = 0; i < stateSpecificTransitions.length; i++) {
if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) {
try {
String url = getTransitionURL(t.getID());
log.warn("DEBUG: Active transition: " + label);
return "<li>" + new AnchorElement(label, url).toString() + "</li>";
} catch (Exception e) {
log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?!
log.warn(e, e);
}
}
}
log.warn("DEBUG: Inactive transition: " + label);
return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>";
} catch (Exception e) {
log.error(e, e);
return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>";
}
}
| public String getTransitionElement(final Transition t) {
if(log.isDebugEnabled()) log.debug("Transition: " + t.getID());
try {
Workflow workflow = WorkflowHelper.getWorkflow(this.resource);
Transition[] stateSpecificTransitions = workflow.getLeavingTransitions(this.state);
String label = t.getID() + " (WARNING: No label!)";
try {
label = t.getDescription(this.resource.getRequestedLanguage());
} catch(Exception e) {
log.error(e, e);
}
for (int i = 0; i < stateSpecificTransitions.length; i++) {
if (transitionsMatch(stateSpecificTransitions[i], t) && isComplied(t, workflow)) {
try {
String url = getTransitionURL(t.getID());
log.warn("DEBUG: Active transition: " + label);
return "<li>" + new AnchorElement(label, url).toString() + "</li>";
} catch (Exception e) {
log.warn("Could not get transition URL!"); // TODO: Is this always the reason for an exception?!
log.warn(e, e);
}
}
}
log.warn("DEBUG: Inactive transition: " + label);
return "<li class='" + STYLE_INACTIVE + "'>" + label + "</li>";
} catch (Exception e) {
log.error(e, e);
return "<li class='" + STYLE_INACTIVE + "'>Exception: " + e.getMessage() + "</li>";
}
}
|
diff --git a/src/com/android/music/MediaPlaybackService.java b/src/com/android/music/MediaPlaybackService.java
index 511326f..9d926f2 100644
--- a/src/com/android/music/MediaPlaybackService.java
+++ b/src/com/android/music/MediaPlaybackService.java
@@ -1,1836 +1,1837 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.media.MediaFile;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneStateIntentReceiver;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;
/**
* Provides "background" audio playback capabilities, allowing the
* user to switch between activities without stopping playback.
*/
public class MediaPlaybackService extends Service {
/** used to specify whether enqueue() should start playing
* the new list of files right away, next or once all the currently
* queued files have been played
*/
public static final int NOW = 1;
public static final int NEXT = 2;
public static final int LAST = 3;
public static final int PLAYBACKSERVICE_STATUS = 1;
public static final int SHUFFLE_NONE = 0;
public static final int SHUFFLE_NORMAL = 1;
public static final int SHUFFLE_AUTO = 2;
public static final int REPEAT_NONE = 0;
public static final int REPEAT_CURRENT = 1;
public static final int REPEAT_ALL = 2;
public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
public static final String META_CHANGED = "com.android.music.metachanged";
public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
public static final String PLAYBACK_COMPLETE = "com.android.music.playbackcomplete";
public static final String ASYNC_OPEN_COMPLETE = "com.android.music.asyncopencomplete";
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
private static final int PHONE_CHANGED = 1;
private static final int TRACK_ENDED = 1;
private static final int RELEASE_WAKELOCK = 2;
private static final int SERVER_DIED = 3;
private static final int FADEIN = 4;
private static final int MAX_HISTORY_SIZE = 10;
private MultiPlayer mPlayer;
private String mFileToPlay;
private PhoneStateIntentReceiver mPsir;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mMediaMountedCount = 0;
private int [] mAutoShuffleList = null;
private boolean mOneShot;
private int [] mPlayList = null;
private int mPlayListLen = 0;
private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
private Cursor mCursor;
private int mPlayPos = -1;
private static final String LOGTAG = "MediaPlaybackService";
private final Shuffler mRand = new Shuffler();
private int mOpenFailedCounter = 0;
String[] mCursorCols = new String[] {
"audio._id AS _id", // index must match IDCOLIDX below
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below
MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below
};
private final static int IDCOLIDX = 0;
private final static int PODCASTCOLIDX = 8;
private final static int BOOKMARKCOLIDX = 9;
private BroadcastReceiver mUnmountReceiver = null;
private WakeLock mWakeLock;
private int mServiceStartId = -1;
private boolean mServiceInUse = false;
private boolean mResumeAfterCall = false;
private boolean mIsSupposedToBePlaying = false;
private boolean mQuietMode = false;
private SharedPreferences mPreferences;
// We use this to distinguish between different cards when saving/restoring playlists.
// This will have to change if we want to support multiple simultaneous cards.
private int mCardId;
private MediaAppWidgetProvider mAppWidgetProvider = MediaAppWidgetProvider.getInstance();
// interval after which we stop the service when idle
private static final int IDLE_DELAY = 60000;
private Handler mPhoneHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PHONE_CHANGED:
Phone.State state = mPsir.getPhoneState();
if (state == Phone.State.RINGING) {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int ringvolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
if (ringvolume > 0) {
mResumeAfterCall = (isPlaying() || mResumeAfterCall) && (getAudioId() >= 0);
pause();
}
} else if (state == Phone.State.OFFHOOK) {
// pause the music while a conversation is in progress
mResumeAfterCall = (isPlaying() || mResumeAfterCall) && (getAudioId() >= 0);
pause();
} else if (state == Phone.State.IDLE) {
// start playing again
if (mResumeAfterCall) {
// resume playback only if music was playing
// when the call was answered
startAndFadeIn();
mResumeAfterCall = false;
}
}
break;
default:
break;
}
}
};
private void startAndFadeIn() {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
}
private Handler mMediaplayerHandler = new Handler() {
float mCurrentVolume = 1.0f;
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FADEIN:
if (!isPlaying()) {
mCurrentVolume = 0f;
mPlayer.setVolume(mCurrentVolume);
play();
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
} else {
mCurrentVolume += 0.01f;
if (mCurrentVolume < 1.0f) {
mMediaplayerHandler.sendEmptyMessageDelayed(FADEIN, 10);
} else {
mCurrentVolume = 1.0f;
}
mPlayer.setVolume(mCurrentVolume);
}
break;
case SERVER_DIED:
if (mIsSupposedToBePlaying) {
next(true);
} else {
// the server died when we were idle, so just
// reopen the same song (it will start again
// from the beginning though when the user
// restarts)
openCurrent();
}
break;
case TRACK_ENDED:
if (mRepeatMode == REPEAT_CURRENT) {
seek(0);
play();
} else if (!mOneShot) {
next(false);
} else {
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
}
break;
case RELEASE_WAKELOCK:
mWakeLock.release();
break;
default:
break;
}
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
} else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) {
// Someone asked us to refresh a set of specific widgets, probably
// because they were just added.
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds);
}
}
};
public MediaPlaybackService() {
mPsir = new PhoneStateIntentReceiver(this, mPhoneHandler);
mPsir.notifyPhoneCallState(PHONE_CHANGED);
}
@Override
public void onCreate() {
super.onCreate();
mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
mCardId = FileUtils.getFatVolumeId(Environment.getExternalStorageDirectory().getPath());
registerExternalStorageListener();
// Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
mPlayer = new MultiPlayer();
mPlayer.setHandler(mMediaplayerHandler);
// Clear leftover notification in case this service previously got killed while playing
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
reloadQueue();
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(SERVICECMD);
commandFilter.addAction(TOGGLEPAUSE_ACTION);
commandFilter.addAction(PAUSE_ACTION);
commandFilter.addAction(NEXT_ACTION);
commandFilter.addAction(PREVIOUS_ACTION);
registerReceiver(mIntentReceiver, commandFilter);
mPsir.registerIntent();
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
mWakeLock.setReferenceCounted(false);
// If the service was idle, but got killed before it stopped itself, the
// system will relaunch it. Make sure it gets stopped again in that case.
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public void onDestroy() {
// Check that we're not being destroyed while something is still playing.
if (isPlaying()) {
Log.e("MediaPlaybackService", "Service being destroyed while still playing.");
}
// and for good measure, call mPlayer.stop(), which calls MediaPlayer.reset(), which
// releases the MediaPlayer's wake lock, if any.
mPlayer.stop();
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
unregisterReceiver(mIntentReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
mPsir.unregisterIntent();
mWakeLock.release();
super.onDestroy();
}
private final char hexdigits [] = new char [] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
private void saveQueue(boolean full) {
if (mOneShot) {
return;
}
Editor ed = mPreferences.edit();
//long start = System.currentTimeMillis();
if (full) {
StringBuilder q = new StringBuilder();
// The current playlist is saved as a list of "reverse hexadecimal"
// numbers, which we can generate faster than normal decimal or
// hexadecimal numbers, which in turn allows us to save the playlist
// more often without worrying too much about performance.
// (saving the full state takes about 40 ms under no-load conditions
// on the phone)
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
int n = mPlayList[i];
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = n & 0xf;
n >>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
//Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms");
ed.putString("queue", q.toString());
ed.putInt("cardid", mCardId);
}
ed.putInt("curpos", mPlayPos);
if (mPlayer.isInitialized()) {
ed.putLong("seekpos", mPlayer.position());
}
ed.putInt("repeatmode", mRepeatMode);
ed.putInt("shufflemode", mShuffleMode);
ed.commit();
//Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms");
}
private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
if (q != null && q.length() > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
String [] entries = q.split(";");
int len = entries.length;
ensurePlayListCapacity(len);
for (int i = 0; i < len; i++) {
if (newstyle) {
String revhex = entries[i];
int n = 0;
for (int j = revhex.length() - 1; j >= 0 ; j--) {
n <<= 4;
char c = revhex.charAt(j);
if (c >= '0' && c <= '9') {
n += (c - '0');
} else if (c >= 'a' && c <= 'f') {
n += (10 + c - 'a');
} else {
// bogus playlist data
len = 0;
break;
}
}
mPlayList[i] = n;
} else {
mPlayList[i] = Integer.parseInt(entries[i]);
}
}
mPlayListLen = len;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= len) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 1) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Intent statusintent = new Intent("com.android.music.PLAYBACK_VIEWER");
statusintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
- /** Returns whether playback is currently paused
+ /** Returns whether something is currently playing
*
- * @return true if playback is paused, false if not
+ * @return true if something is playing (or will be playing shortly, in case
+ * we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
private final IMediaPlaybackService.Stub mBinder = new IMediaPlaybackService.Stub()
{
public void openFileAsync(String path)
{
MediaPlaybackService.this.openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
MediaPlaybackService.this.open(path, oneShot);
}
public void open(int [] list, int position) {
MediaPlaybackService.this.open(list, position);
}
public int getQueuePosition() {
return MediaPlaybackService.this.getQueuePosition();
}
public void setQueuePosition(int index) {
MediaPlaybackService.this.setQueuePosition(index);
}
public boolean isPlaying() {
return MediaPlaybackService.this.isPlaying();
}
public void stop() {
MediaPlaybackService.this.stop();
}
public void pause() {
MediaPlaybackService.this.pause();
}
public void play() {
MediaPlaybackService.this.play();
}
public void prev() {
MediaPlaybackService.this.prev();
}
public void next() {
MediaPlaybackService.this.next(true);
}
public String getTrackName() {
return MediaPlaybackService.this.getTrackName();
}
public String getAlbumName() {
return MediaPlaybackService.this.getAlbumName();
}
public int getAlbumId() {
return MediaPlaybackService.this.getAlbumId();
}
public String getArtistName() {
return MediaPlaybackService.this.getArtistName();
}
public int getArtistId() {
return MediaPlaybackService.this.getArtistId();
}
public void enqueue(int [] list , int action) {
MediaPlaybackService.this.enqueue(list, action);
}
public int [] getQueue() {
return MediaPlaybackService.this.getQueue();
}
public void moveQueueItem(int from, int to) {
MediaPlaybackService.this.moveQueueItem(from, to);
}
public String getPath() {
return MediaPlaybackService.this.getPath();
}
public int getAudioId() {
return MediaPlaybackService.this.getAudioId();
}
public long position() {
return MediaPlaybackService.this.position();
}
public long duration() {
return MediaPlaybackService.this.duration();
}
public long seek(long pos) {
return MediaPlaybackService.this.seek(pos);
}
public void setShuffleMode(int shufflemode) {
MediaPlaybackService.this.setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return MediaPlaybackService.this.getShuffleMode();
}
public int removeTracks(int first, int last) {
return MediaPlaybackService.this.removeTracks(first, last);
}
public int removeTrack(int id) {
return MediaPlaybackService.this.removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
MediaPlaybackService.this.setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return MediaPlaybackService.this.getRepeatMode();
}
public int getMediaMountedCount() {
return MediaPlaybackService.this.getMediaMountedCount();
}
};
}
| false | true | private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
if (q != null && q.length() > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
String [] entries = q.split(";");
int len = entries.length;
ensurePlayListCapacity(len);
for (int i = 0; i < len; i++) {
if (newstyle) {
String revhex = entries[i];
int n = 0;
for (int j = revhex.length() - 1; j >= 0 ; j--) {
n <<= 4;
char c = revhex.charAt(j);
if (c >= '0' && c <= '9') {
n += (c - '0');
} else if (c >= 'a' && c <= 'f') {
n += (10 + c - 'a');
} else {
// bogus playlist data
len = 0;
break;
}
}
mPlayList[i] = n;
} else {
mPlayList[i] = Integer.parseInt(entries[i]);
}
}
mPlayListLen = len;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= len) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 1) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Intent statusintent = new Intent("com.android.music.PLAYBACK_VIEWER");
statusintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether playback is currently paused
*
* @return true if playback is paused, false if not
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
private final IMediaPlaybackService.Stub mBinder = new IMediaPlaybackService.Stub()
{
public void openFileAsync(String path)
{
MediaPlaybackService.this.openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
MediaPlaybackService.this.open(path, oneShot);
}
public void open(int [] list, int position) {
MediaPlaybackService.this.open(list, position);
}
public int getQueuePosition() {
return MediaPlaybackService.this.getQueuePosition();
}
public void setQueuePosition(int index) {
MediaPlaybackService.this.setQueuePosition(index);
}
public boolean isPlaying() {
return MediaPlaybackService.this.isPlaying();
}
public void stop() {
MediaPlaybackService.this.stop();
}
public void pause() {
MediaPlaybackService.this.pause();
}
public void play() {
MediaPlaybackService.this.play();
}
public void prev() {
MediaPlaybackService.this.prev();
}
public void next() {
MediaPlaybackService.this.next(true);
}
public String getTrackName() {
return MediaPlaybackService.this.getTrackName();
}
public String getAlbumName() {
return MediaPlaybackService.this.getAlbumName();
}
public int getAlbumId() {
return MediaPlaybackService.this.getAlbumId();
}
public String getArtistName() {
return MediaPlaybackService.this.getArtistName();
}
public int getArtistId() {
return MediaPlaybackService.this.getArtistId();
}
public void enqueue(int [] list , int action) {
MediaPlaybackService.this.enqueue(list, action);
}
public int [] getQueue() {
return MediaPlaybackService.this.getQueue();
}
public void moveQueueItem(int from, int to) {
MediaPlaybackService.this.moveQueueItem(from, to);
}
public String getPath() {
return MediaPlaybackService.this.getPath();
}
public int getAudioId() {
return MediaPlaybackService.this.getAudioId();
}
public long position() {
return MediaPlaybackService.this.position();
}
public long duration() {
return MediaPlaybackService.this.duration();
}
public long seek(long pos) {
return MediaPlaybackService.this.seek(pos);
}
public void setShuffleMode(int shufflemode) {
MediaPlaybackService.this.setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return MediaPlaybackService.this.getShuffleMode();
}
public int removeTracks(int first, int last) {
return MediaPlaybackService.this.removeTracks(first, last);
}
public int removeTrack(int id) {
return MediaPlaybackService.this.removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
MediaPlaybackService.this.setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return MediaPlaybackService.this.getRepeatMode();
}
public int getMediaMountedCount() {
return MediaPlaybackService.this.getMediaMountedCount();
}
};
}
| private void reloadQueue() {
String q = null;
boolean newstyle = false;
int id = mCardId;
if (mPreferences.contains("cardid")) {
newstyle = true;
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
if (q != null && q.length() > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
String [] entries = q.split(";");
int len = entries.length;
ensurePlayListCapacity(len);
for (int i = 0; i < len; i++) {
if (newstyle) {
String revhex = entries[i];
int n = 0;
for (int j = revhex.length() - 1; j >= 0 ; j--) {
n <<= 4;
char c = revhex.charAt(j);
if (c >= '0' && c <= '9') {
n += (c - '0');
} else if (c >= 'a' && c <= 'f') {
n += (10 + c - 'a');
} else {
// bogus playlist data
len = 0;
break;
}
}
mPlayList[i] = n;
} else {
mPlayList[i] = Integer.parseInt(entries[i]);
}
}
mPlayListLen = len;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= len) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor c = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (c == null || c.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
c = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (c != null) {
c.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public void onStart(Intent intent, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
next(true);
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
prev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
pause();
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
pause();
} else if (CMDSTOP.equals(cmd)) {
pause();
seek(0);
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mResumeAfterCall) {
// something is currently playing, or will be playing once
// an in-progress call ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mResumeAfterCall || mServiceInUse
|| mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mOneShot = true; // This makes us not save the state again later,
// which would be wrong because the song ids and
// card id might not match.
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = FileUtils.getFatVolumeId(intent.getData().getPath());
reloadQueue();
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Integer.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
sendBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
int [] newlist = new int[size * 2];
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(int [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(int [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(int [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
int oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
int oldpos = mPlayPos;
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
int tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
int tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public int [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
int [] list = new int[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id, false);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
public void openAsync(String path) {
synchronized (this) {
if (path == null) {
return;
}
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
mFileToPlay = path;
mCursor = null;
mPlayer.setDataSourceAsync(mFileToPlay);
mOneShot = true;
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
* @param oneshot when set to true, playback will stop after this file completes, instead
* of moving on to the next track in the list
*/
public void open(String path, boolean oneshot) {
synchronized (this) {
if (path == null) {
return;
}
if (oneshot) {
mRepeatMode = REPEAT_NONE;
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayPos = -1;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getInt(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
mOneShot = oneshot;
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
if (mRepeatMode != REPEAT_CURRENT &&
mPlayer.position() >= mPlayer.duration() - 1) {
next(true);
}
mPlayer.start();
setForeground(true);
NotificationManager nm = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar);
views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer);
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artistalbum, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaFile.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaFile.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artistalbum,
getString(R.string.notification_artist_album, artist, album)
);
}
Intent statusintent = new Intent("com.android.music.PLAYBACK_VIEWER");
statusintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER"), 0);
nm.notify(PLAYBACKSERVICE_STATUS, status);
if (!mIsSupposedToBePlaying) {
notifyChange(PLAYSTATE_CHANGED);
}
mIsSupposedToBePlaying = true;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
}
setForeground(false);
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
setForeground(false);
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'previous'
seek(0);
play();
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mOneShot) {
// we were playing a specific file not part of a playlist, so there is no 'next'
seek(0);
play();
return;
}
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(Integer.valueOf(mPlayPos));
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
notifyChange(PLAYBACK_COMPLETE);
mIsSupposedToBePlaying = false;
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
private void gotoIdleState() {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(PLAYBACKSERVICE_STATUS);
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int idx = mRand.nextInt(mAutoShuffleList.length);
Integer which = mAutoShuffleList[idx];
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = which;
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
int[] list = new int[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getInt(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(int id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public int getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public int getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public int getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getInt(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
return mPlayer.seek(pos);
}
return -1;
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSourceAsync(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(path);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(preparedlistener);
mMediaPlayer.prepareAsync();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(TRACK_ENDED);
mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
}
};
MediaPlayer.OnPreparedListener preparedlistener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
notifyChange(ASYNC_OPEN_COMPLETE);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
return true;
default:
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
}
}
private final IMediaPlaybackService.Stub mBinder = new IMediaPlaybackService.Stub()
{
public void openFileAsync(String path)
{
MediaPlaybackService.this.openAsync(path);
}
public void openFile(String path, boolean oneShot)
{
MediaPlaybackService.this.open(path, oneShot);
}
public void open(int [] list, int position) {
MediaPlaybackService.this.open(list, position);
}
public int getQueuePosition() {
return MediaPlaybackService.this.getQueuePosition();
}
public void setQueuePosition(int index) {
MediaPlaybackService.this.setQueuePosition(index);
}
public boolean isPlaying() {
return MediaPlaybackService.this.isPlaying();
}
public void stop() {
MediaPlaybackService.this.stop();
}
public void pause() {
MediaPlaybackService.this.pause();
}
public void play() {
MediaPlaybackService.this.play();
}
public void prev() {
MediaPlaybackService.this.prev();
}
public void next() {
MediaPlaybackService.this.next(true);
}
public String getTrackName() {
return MediaPlaybackService.this.getTrackName();
}
public String getAlbumName() {
return MediaPlaybackService.this.getAlbumName();
}
public int getAlbumId() {
return MediaPlaybackService.this.getAlbumId();
}
public String getArtistName() {
return MediaPlaybackService.this.getArtistName();
}
public int getArtistId() {
return MediaPlaybackService.this.getArtistId();
}
public void enqueue(int [] list , int action) {
MediaPlaybackService.this.enqueue(list, action);
}
public int [] getQueue() {
return MediaPlaybackService.this.getQueue();
}
public void moveQueueItem(int from, int to) {
MediaPlaybackService.this.moveQueueItem(from, to);
}
public String getPath() {
return MediaPlaybackService.this.getPath();
}
public int getAudioId() {
return MediaPlaybackService.this.getAudioId();
}
public long position() {
return MediaPlaybackService.this.position();
}
public long duration() {
return MediaPlaybackService.this.duration();
}
public long seek(long pos) {
return MediaPlaybackService.this.seek(pos);
}
public void setShuffleMode(int shufflemode) {
MediaPlaybackService.this.setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return MediaPlaybackService.this.getShuffleMode();
}
public int removeTracks(int first, int last) {
return MediaPlaybackService.this.removeTracks(first, last);
}
public int removeTrack(int id) {
return MediaPlaybackService.this.removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
MediaPlaybackService.this.setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return MediaPlaybackService.this.getRepeatMode();
}
public int getMediaMountedCount() {
return MediaPlaybackService.this.getMediaMountedCount();
}
};
}
|
diff --git a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ExtendedSearchController.java b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ExtendedSearchController.java
index de50a4616..ac2557583 100755
--- a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ExtendedSearchController.java
+++ b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ExtendedSearchController.java
@@ -1,586 +1,586 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2, as published by the
* Free Software Foundation. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
* Place, Suite 330 / Boston, MA 02111-1307 / USA.
*
* ===============================================================================
*/
package org.infoglue.cms.controllers.kernel.impl.simple;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.exolab.castor.jdo.Database;
import org.exolab.castor.jdo.OQLQuery;
import org.exolab.castor.jdo.PersistenceException;
import org.exolab.castor.jdo.QueryResults;
import org.infoglue.cms.entities.content.impl.simple.SmallContentImpl;
import org.infoglue.cms.entities.kernel.BaseEntityVO;
import org.infoglue.cms.entities.management.ContentTypeDefinitionVO;
import org.infoglue.cms.entities.management.LanguageVO;
import org.infoglue.cms.exception.SystemException;
import org.infoglue.cms.util.CmsPropertyHandler;
/**
*
*/
public class ExtendedSearchController extends BaseController
{
private final static Logger logger = Logger.getLogger(ExtendedSearchController.class.getName());
/**
* The singleton controller.
*/
private static final ExtendedSearchController instance = new ExtendedSearchController();
/**
* Singleton class; don't allow instantiation.
*/
private ExtendedSearchController()
{
super();
}
/**
* Returns the singleton controller.
*/
public static ExtendedSearchController getController()
{
return instance;
}
/**
* @deprecated Use search(ExtendedSearchCriterias)
*/
public Set search(final Integer stateId, final ContentTypeDefinitionVO contentTypeDefinitionVO, final LanguageVO languageVO, final CategoryConditions categories) throws SystemException
{
final ExtendedSearchCriterias criterias = new ExtendedSearchCriterias(stateId.intValue());
criterias.setContentTypeDefinitions(contentTypeDefinitionVO);
criterias.setLanguage(languageVO);
criterias.setCategoryConditions(categories);
return search(criterias);
}
/**
* @deprecated Use search(ExtendedSearchCriterias)
*/
public Set search(final Integer stateId, final ContentTypeDefinitionVO contentTypeDefinitionVO, final LanguageVO languageVO, final CategoryConditions categories, final Database db) throws SystemException
{
final ExtendedSearchCriterias criterias = new ExtendedSearchCriterias(stateId.intValue());
criterias.setContentTypeDefinitions(contentTypeDefinitionVO);
criterias.setLanguage(languageVO);
criterias.setCategoryConditions(categories);
return search(criterias, db);
}
/**
* @deprecated Use search(ExtendedSearchCriterias)
*/
public Set search(final Integer stateId, final List contentTypeDefinitionVOs, final LanguageVO languageVO, final CategoryConditions categories) throws SystemException
{
final ExtendedSearchCriterias criterias = new ExtendedSearchCriterias(stateId.intValue());
criterias.setContentTypeDefinitions(contentTypeDefinitionVOs);
criterias.setLanguage(languageVO);
criterias.setCategoryConditions(categories);
return search(criterias);
}
/**
* @deprecated Use search(ExtendedSearchCriterias)
*/
public Set search(final Integer stateId, final List contentTypeDefinitionVOs, final LanguageVO languageVO, final CategoryConditions categories, final Database db) throws SystemException
{
final ExtendedSearchCriterias criterias = new ExtendedSearchCriterias(stateId.intValue());
criterias.setContentTypeDefinitions(contentTypeDefinitionVOs);
criterias.setLanguage(languageVO);
criterias.setCategoryConditions(categories);
return search(criterias, db);
}
/**
* @deprecated Use search(ExtendedSearchCriterias)
*/
public Set search(final Integer stateId, final ContentTypeDefinitionVO contentTypeDefinitionVO, final LanguageVO languageVO, final CategoryConditions categories, final List xmlAttributes, final String freetext) throws SystemException
{
final ExtendedSearchCriterias criterias = new ExtendedSearchCriterias(stateId.intValue());
criterias.setContentTypeDefinitions(contentTypeDefinitionVO);
criterias.setLanguage(languageVO);
criterias.setCategoryConditions(categories);
criterias.setFreetext(freetext, xmlAttributes);
return search(criterias);
}
/**
*
*/
public Set search(final ExtendedSearchCriterias criterias) throws SystemException
{
final Database db = beginTransaction();
try
{
final Set result = search(criterias, db);
commitTransaction(db);
return result;
}
catch (Exception e)
{
rollbackTransaction(db);
throw new SystemException(e.getMessage());
}
}
/**
*
*/
public Set search(final ExtendedSearchCriterias criterias, final Database db) throws SystemException
{
if(criterias == null)
return new HashSet();
try
{
final SqlBuilder sqlBuilder = new SqlBuilder(criterias);
- //logger.debug("sql:" + sqlBuilder.getSQL());
- logger.error("sql:" + sqlBuilder.getSQL());
+ if(logger.isDebugEnabled())
+ logger.debug("sql:" + sqlBuilder.getSQL());
final OQLQuery oql = db.getOQLQuery(sqlBuilder.getSQL());
for(Iterator i=sqlBuilder.getBindings().iterator(); i.hasNext(); )
{
Object o = i.next();
- logger.debug("o:" + o.toString());
- logger.error("o:" + o.toString());
+ if(logger.isDebugEnabled())
+ logger.debug("o:" + o.toString());
oql.bind(o);
}
QueryResults results = oql.execute(Database.ReadOnly);
Set matchingResults = createResults(results);
results.close();
oql.close();
return matchingResults;
}
catch(Exception e)
{
e.printStackTrace();
throw new SystemException(e.getMessage());
}
}
/**
*
*/
private Set createResults(final QueryResults qr) throws PersistenceException, SystemException
{
final Set results = new HashSet();
while(qr.hasMore())
{
results.add(qr.next());
}
return results;
}
private static Boolean useFull = null;
public static boolean useFull()
{
if(useFull == null)
{
String useShortTableNames = CmsPropertyHandler.getUseShortTableNames();
if(useShortTableNames == null || !useShortTableNames.equalsIgnoreCase("true"))
{
useFull = new Boolean(true);
}
else
{
useFull = new Boolean(false);
}
}
return useFull.booleanValue();
}
/**
* Unused.
*/
public BaseEntityVO getNewVO()
{
return null;
}
}
/**
*
*/
class SqlBuilder
{
/**
*
*/
private final static Logger logger = Logger.getLogger(SqlBuilder.class.getName());
//
private static final String SELECT_KEYWORD = "SELECT";
private static final String FROM_KEYWORD = "FROM";
private static final String WHERE_KEYWORD = "WHERE";
private static final String SPACE = " ";
private static final String COMMA = ",";
private static final String AND = "AND";
private static final String OR = "OR";
//
private static final String CONTENT_ALIAS = "c";
private static final String CONTENT_VERSION_ALIAS = "cv";
//Here is all the table names used for building the search query.
private static final String CONTENT_TABLE_SHORT = "cmCont";
private static final String CONTENT_TABLE = "cmContent";
private static final String CONTENT_VERSION_TABLE_SHORT = "cmContVer";
private static final String CONTENT_VERSION_TABLE = "cmContentVersion";
//
private static final String CV_ACTIVE_CLAUSE = CONTENT_VERSION_ALIAS + ".isActive=1";
private static final String CV_LANGUAGE_CLAUSE = CONTENT_VERSION_ALIAS + ".languageId={0}";
//private static final String CV_STATE_CLAUSE = CONTENT_VERSION_ALIAS + ".stateId={0}";
private static final String CV_STATE_CLAUSE = CONTENT_VERSION_ALIAS + ".stateId>={0}";
private static final String CV_CONTENT_JOIN_SHORT = CONTENT_ALIAS + ".ContId=" + CONTENT_VERSION_ALIAS + ".ContId";
private static final String CV_CONTENT_JOIN = CONTENT_ALIAS + ".contentId=" + CONTENT_VERSION_ALIAS + ".contentId";
private static final String CV_LATEST_VERSION_CLAUSE_SHORT= CONTENT_VERSION_ALIAS + ".ContVerId in (select max(ContVerId) from " + CONTENT_VERSION_TABLE_SHORT + " cv2 where cv2.ContId=" + CONTENT_VERSION_ALIAS + ".ContId AND cv2.languageId={0} AND cv2.stateId>={1} AND cv2.isActive=1)";
private static final String CV_LATEST_VERSION_CLAUSE = CONTENT_VERSION_ALIAS + ".contentVersionId in (select max(contentVersionId) from " + CONTENT_VERSION_TABLE + " cv2 where cv2.contentId=" + CONTENT_VERSION_ALIAS + ".contentId AND cv2.languageId={0} AND cv2.stateId>={1} AND cv2.isActive=1)";
private static final String C_CONTENT_TYPE_CLAUSE_SHORT = CONTENT_ALIAS + ".contentTypeDefId={0}";
private static final String C_CONTENT_TYPE_CLAUSE = CONTENT_ALIAS + ".contentTypeDefinitionId={0}";
private static final String FREETEXT_EXPRESSION_SHORT = CONTENT_VERSION_ALIAS + ".VerValue like {0}";
private static final String FREETEXT_EXPRESSION = CONTENT_VERSION_ALIAS + ".versionValue like {0}";
private static final String FROM_DATE_CLAUSE = CONTENT_ALIAS + ".publishDateTime>={0}";
private static final String TO_DATE_CLAUSE = CONTENT_ALIAS + ".publishDateTime<={0}";
// BETWEEN DOESN'T SEEMS TO WORK : use FROM_DATE_CLAUSE + TO_DATE_CLAUSE instead
//private static final String BETWEEN_DATE_CLAUSE = CONTENT_ALIAS + ".publishDateTime between {0} and {1}";
private static final String FREETEXT_EXPRESSION_VARIABLE = "%<{0}><![CDATA[%{1}%]]></{0}>%";
private final ExtendedSearchCriterias criterias;
//
private String sql;
private List bindings;
/**
*
*/
public SqlBuilder(final ExtendedSearchCriterias criterias)
{
super();
this.criterias = criterias;
this.bindings = new ArrayList();
logger.debug("===[sql]==============================================================");
this.sql = generate();
logger.debug("======================================================================");
//System.out.println("sql:" + sql);
logger.debug(sql);
logger.debug("===[/sql]=============================================================");
}
/**
*
*/
public String getSQL()
{
return sql;
}
/**
*
*/
public List getBindings()
{
return bindings;
}
/**
*
*/
private String generate()
{
return "CALL SQL" + SPACE + (ExtendedSearchController.useFull() ? generateSelectClause() : generateSelectClauseShort()) + SPACE + generateFromClause() + SPACE + generateWhereClause() + SPACE + (ExtendedSearchController.useFull() ? generateOrderByClause() : generateOrderByClauseShort()) + SPACE + "AS " + SmallContentImpl.class.getName();
}
/**
*
*/
private String generateSelectClauseShort()
{
return SELECT_KEYWORD + SPACE +
CONTENT_ALIAS + ".ContId" +
COMMA + CONTENT_ALIAS + ".name" +
COMMA + CONTENT_ALIAS + ".publishDateTime" +
COMMA + CONTENT_ALIAS + ".expireDateTime" +
COMMA + CONTENT_ALIAS + ".isBranch" +
COMMA + CONTENT_ALIAS + ".isProtected" +
COMMA + CONTENT_ALIAS + ".creator" +
COMMA + CONTENT_ALIAS + ".contentTypeDefId" +
COMMA + CONTENT_ALIAS + ".repositoryId" +
COMMA + CONTENT_ALIAS + ".parentContId" +
COMMA + CONTENT_ALIAS + ".ContId";
}
/**
*
*/
private String generateSelectClause()
{
return SELECT_KEYWORD + SPACE +
CONTENT_ALIAS + ".contentId" +
COMMA + CONTENT_ALIAS + ".name" +
COMMA + CONTENT_ALIAS + ".publishDateTime" +
COMMA + CONTENT_ALIAS + ".expireDateTime" +
COMMA + CONTENT_ALIAS + ".isBranch" +
COMMA + CONTENT_ALIAS + ".isProtected" +
COMMA + CONTENT_ALIAS + ".creator" +
COMMA + CONTENT_ALIAS + ".contentTypeDefinitionId" +
COMMA + CONTENT_ALIAS + ".repositoryId" +
COMMA + CONTENT_ALIAS + ".parentContentId" +
COMMA + CONTENT_ALIAS + ".contentId";
}
/**
*
*/
private String generateFromClause()
{
final List tables = new ArrayList();
tables.add(getCONTENT_TABLE() + SPACE + CONTENT_ALIAS);
tables.add(getCONTENT_VERSION_TABLE() + SPACE + CONTENT_VERSION_ALIAS);
tables.addAll(getCategoryTables());
return FROM_KEYWORD + SPACE + joinCollection(tables, COMMA);
}
/**
*
*/
private String generateWhereClause()
{
final List clauses = new ArrayList();
clauses.addAll(getContentWhereClauses());
clauses.add(getContentVersionWhereClauses());
if(criterias.hasFreetextCritera())
{
clauses.add(getFreetextWhereClause());
}
clauses.addAll(getCategoriesWhereClauses());
clauses.addAll(getDateWhereClauses());
return WHERE_KEYWORD + SPACE + joinCollection(clauses, SPACE + AND + SPACE);
}
/**
*
*/
private List getContentWhereClauses()
{
final List clauses = new ArrayList();
clauses.add(CV_ACTIVE_CLAUSE);
clauses.add(MessageFormat.format(getCV_LATEST_VERSION_CLAUSE(), new Object[] { criterias.getLanguage().getId().toString(), CmsPropertyHandler.getOperatingMode() }));
clauses.add(getCV_CONTENT_JOIN());
clauses.add(MessageFormat.format(CV_STATE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getStateId());
if(criterias.hasLanguageCriteria())
{
logger.debug(" CRITERA[language]");
clauses.add(MessageFormat.format(CV_LANGUAGE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getLanguage().getId());
}
return clauses;
}
/**
*
*/
private String generateOrderByClauseShort()
{
return "ORDER BY " + CONTENT_ALIAS + ".ContId";
}
/**
*
*/
private String generateOrderByClause()
{
return "ORDER BY " + CONTENT_ALIAS + ".contentId";
}
/**
*
*/
private String getContentVersionWhereClauses()
{
final List expressions = new ArrayList();
if(criterias.hasContentTypeDefinitionVOsCriteria())
{
logger.debug(" CRITERA[content type definition]");
for(final Iterator i=criterias.getContentTypeDefinitions().iterator(); i.hasNext(); )
{
final ContentTypeDefinitionVO contentTypeDefinitionVO = (ContentTypeDefinitionVO) i.next();
expressions.add(MessageFormat.format(getC_CONTENT_TYPE_CLAUSE(), new Object[] { getBindingVariable() }));
bindings.add(contentTypeDefinitionVO.getId());
}
}
return "(" + joinCollection(expressions, SPACE + OR + SPACE) + ")";
}
/**
*
*/
private List getCategoriesWhereClauses()
{
final List clauses = new ArrayList();
if(criterias.hasCategoryConditions())
{
logger.debug(" CRITERA[categories]");
clauses.add(criterias.getCategories().getWhereClauseOQL(bindings));
}
return clauses;
}
/**
*
*/
private List getDateWhereClauses()
{
final List clauses = new ArrayList();
switch(criterias.getDateCriteriaType())
{
case ExtendedSearchCriterias.FROM_DATE_CRITERIA_TYPE:
logger.debug(" CRITERA[date : from]");
clauses.add(MessageFormat.format(FROM_DATE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getFromDate());
break;
case ExtendedSearchCriterias.TO_DATE_CRITERIA_TYPE:
logger.debug(" CRITERA[date : to]");
clauses.add(MessageFormat.format(TO_DATE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getToDate());
break;
case ExtendedSearchCriterias.BOTH_DATE_CRITERIA_TYPE:
logger.debug(" CRITERA[date : between]");
clauses.add(MessageFormat.format(FROM_DATE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getFromDate());
clauses.add(MessageFormat.format(TO_DATE_CLAUSE, new Object[] { getBindingVariable() }));
bindings.add(criterias.getToDate());
break;
}
return clauses;
}
/**
*
*/
private String getFreetextWhereClause()
{
logger.debug(" CRITERA[freetext]");
final List expressions = new ArrayList();
if(criterias.hasFreetextCritera())
{
for(final Iterator i=criterias.getXmlAttributes().iterator(); i.hasNext(); )
{
final String xmlAttribute = (String) i.next();
final String freeTextExpression = MessageFormat.format(getFREETEXT_EXPRESSION(), new Object[] { getBindingVariable() });
final String freeTextVariable = MessageFormat.format(FREETEXT_EXPRESSION_VARIABLE, new Object[] { xmlAttribute, criterias.getFreetext() });
bindings.add(freeTextVariable);
expressions.add(freeTextExpression);
}
}
return "(" + joinCollection(expressions, SPACE + OR + SPACE) + ")";
}
/**
*
*/
private List getCategoryTables()
{
final List tables = new ArrayList();
if(criterias.hasCategoryConditions())
{
tables.addAll(criterias.getCategories().getFromClauseTables());
}
return tables;
}
/**
*
*/
private String joinCollection(final Collection collection, final String delimiter)
{
final StringBuffer sb = new StringBuffer();
for(Iterator i=collection.iterator(); i.hasNext(); )
{
String element = (String) i.next();
sb.append(element + (i.hasNext() ? delimiter : ""));
}
return sb.toString();
}
/**
*
*/
private String getBindingVariable()
{
return "$" + (bindings.size() + 1);
}
public static String getCONTENT_TABLE()
{
return (ExtendedSearchController.useFull()) ? CONTENT_TABLE : CONTENT_TABLE_SHORT;
}
public static String getCONTENT_VERSION_TABLE()
{
return (ExtendedSearchController.useFull()) ? CONTENT_VERSION_TABLE : CONTENT_VERSION_TABLE_SHORT;
}
public static String getC_CONTENT_TYPE_CLAUSE()
{
return (ExtendedSearchController.useFull()) ? C_CONTENT_TYPE_CLAUSE : C_CONTENT_TYPE_CLAUSE_SHORT;
}
public static String getCV_CONTENT_JOIN()
{
return (ExtendedSearchController.useFull()) ? CV_CONTENT_JOIN : CV_CONTENT_JOIN_SHORT;
}
public static String getCV_LATEST_VERSION_CLAUSE()
{
return (ExtendedSearchController.useFull()) ? CV_LATEST_VERSION_CLAUSE : CV_LATEST_VERSION_CLAUSE_SHORT;
}
public static String getFREETEXT_EXPRESSION()
{
return (ExtendedSearchController.useFull()) ? FREETEXT_EXPRESSION : FREETEXT_EXPRESSION_SHORT;
}
}
| false | true | public Set search(final ExtendedSearchCriterias criterias, final Database db) throws SystemException
{
if(criterias == null)
return new HashSet();
try
{
final SqlBuilder sqlBuilder = new SqlBuilder(criterias);
//logger.debug("sql:" + sqlBuilder.getSQL());
logger.error("sql:" + sqlBuilder.getSQL());
final OQLQuery oql = db.getOQLQuery(sqlBuilder.getSQL());
for(Iterator i=sqlBuilder.getBindings().iterator(); i.hasNext(); )
{
Object o = i.next();
logger.debug("o:" + o.toString());
logger.error("o:" + o.toString());
oql.bind(o);
}
QueryResults results = oql.execute(Database.ReadOnly);
Set matchingResults = createResults(results);
results.close();
oql.close();
return matchingResults;
}
catch(Exception e)
{
e.printStackTrace();
throw new SystemException(e.getMessage());
}
}
| public Set search(final ExtendedSearchCriterias criterias, final Database db) throws SystemException
{
if(criterias == null)
return new HashSet();
try
{
final SqlBuilder sqlBuilder = new SqlBuilder(criterias);
if(logger.isDebugEnabled())
logger.debug("sql:" + sqlBuilder.getSQL());
final OQLQuery oql = db.getOQLQuery(sqlBuilder.getSQL());
for(Iterator i=sqlBuilder.getBindings().iterator(); i.hasNext(); )
{
Object o = i.next();
if(logger.isDebugEnabled())
logger.debug("o:" + o.toString());
oql.bind(o);
}
QueryResults results = oql.execute(Database.ReadOnly);
Set matchingResults = createResults(results);
results.close();
oql.close();
return matchingResults;
}
catch(Exception e)
{
e.printStackTrace();
throw new SystemException(e.getMessage());
}
}
|
diff --git a/maven-scm-providers/maven-scm-providers-svn/maven-scm-provider-svnexe/src/main/java/org/apache/maven/scm/provider/svn/svnexe/command/update/SvnUpdateConsumer.java b/maven-scm-providers/maven-scm-providers-svn/maven-scm-provider-svnexe/src/main/java/org/apache/maven/scm/provider/svn/svnexe/command/update/SvnUpdateConsumer.java
index bc071f32..7df47462 100644
--- a/maven-scm-providers/maven-scm-providers-svn/maven-scm-provider-svnexe/src/main/java/org/apache/maven/scm/provider/svn/svnexe/command/update/SvnUpdateConsumer.java
+++ b/maven-scm-providers/maven-scm-providers-svn/maven-scm-provider-svnexe/src/main/java/org/apache/maven/scm/provider/svn/svnexe/command/update/SvnUpdateConsumer.java
@@ -1,122 +1,127 @@
package org.apache.maven.scm.provider.svn.svnexe.command.update;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileStatus;
import org.apache.maven.scm.log.ScmLogger;
import org.apache.maven.scm.provider.svn.svnexe.command.AbstractFileCheckingConsumer;
import java.io.File;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
*/
public class SvnUpdateConsumer
extends AbstractFileCheckingConsumer
{
private static final String UPDATED_TO_REVISION_TOKEN = "Updated to revision";
private static final String AT_REVISION_TOKEN = "At revision";
private static final String EXPORTED_REVISION_TOKEN = "Exported revision";
private static final String RESTORED_TOKEN = "Restored";
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
public SvnUpdateConsumer( ScmLogger logger, File workingDirectory )
{
super( logger, workingDirectory );
}
// ----------------------------------------------------------------------
// StreamConsumer Implementation
// ----------------------------------------------------------------------
protected void parseLine( String line )
{
line = line.trim();
String statusString = line.substring( 0, 1 );
String file = line.substring( 3 ).trim();
+ //[SCM-368]
+ if ( file.startsWith( workingDirectory.getAbsolutePath() ) )
+ {
+ file = file.substring( this.workingDirectory.getAbsolutePath().length() + 1 );
+ }
ScmFileStatus status;
if ( line.startsWith( UPDATED_TO_REVISION_TOKEN ) )
{
String revisionString = line.substring( UPDATED_TO_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( AT_REVISION_TOKEN ) )
{
String revisionString = line.substring( AT_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( EXPORTED_REVISION_TOKEN ) )
{
String revisionString = line.substring( EXPORTED_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( RESTORED_TOKEN ) )
{
return;
}
else if ( statusString.equals( "A" ) )
{
status = ScmFileStatus.ADDED;
}
else if ( statusString.equals( "U" ) || statusString.equals( "M" ) )
{
status = ScmFileStatus.UPDATED;
}
else if ( statusString.equals( "D" ) )
{
status = ScmFileStatus.DELETED;
}
else
{
//Do nothing
return;
}
addFile( new ScmFile( file, status ) );
}
public List getUpdatedFiles()
{
return getFiles();
}
}
| true | true | protected void parseLine( String line )
{
line = line.trim();
String statusString = line.substring( 0, 1 );
String file = line.substring( 3 ).trim();
ScmFileStatus status;
if ( line.startsWith( UPDATED_TO_REVISION_TOKEN ) )
{
String revisionString = line.substring( UPDATED_TO_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( AT_REVISION_TOKEN ) )
{
String revisionString = line.substring( AT_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( EXPORTED_REVISION_TOKEN ) )
{
String revisionString = line.substring( EXPORTED_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( RESTORED_TOKEN ) )
{
return;
}
else if ( statusString.equals( "A" ) )
{
status = ScmFileStatus.ADDED;
}
else if ( statusString.equals( "U" ) || statusString.equals( "M" ) )
{
status = ScmFileStatus.UPDATED;
}
else if ( statusString.equals( "D" ) )
{
status = ScmFileStatus.DELETED;
}
else
{
//Do nothing
return;
}
addFile( new ScmFile( file, status ) );
}
| protected void parseLine( String line )
{
line = line.trim();
String statusString = line.substring( 0, 1 );
String file = line.substring( 3 ).trim();
//[SCM-368]
if ( file.startsWith( workingDirectory.getAbsolutePath() ) )
{
file = file.substring( this.workingDirectory.getAbsolutePath().length() + 1 );
}
ScmFileStatus status;
if ( line.startsWith( UPDATED_TO_REVISION_TOKEN ) )
{
String revisionString = line.substring( UPDATED_TO_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( AT_REVISION_TOKEN ) )
{
String revisionString = line.substring( AT_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( EXPORTED_REVISION_TOKEN ) )
{
String revisionString = line.substring( EXPORTED_REVISION_TOKEN.length() + 1, line.length() - 1 );
revision = parseInt( revisionString );
return;
}
else if ( line.startsWith( RESTORED_TOKEN ) )
{
return;
}
else if ( statusString.equals( "A" ) )
{
status = ScmFileStatus.ADDED;
}
else if ( statusString.equals( "U" ) || statusString.equals( "M" ) )
{
status = ScmFileStatus.UPDATED;
}
else if ( statusString.equals( "D" ) )
{
status = ScmFileStatus.DELETED;
}
else
{
//Do nothing
return;
}
addFile( new ScmFile( file, status ) );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.