answer
stringlengths
17
10.2M
package com.opengamma.financial.currency; import java.util.Collections; import java.util.Map; import java.util.Set; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries; import com.opengamma.core.value.MarketDataRequirementNames; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.AbstractFunction; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.engine.function.FunctionExecutionContext; import com.opengamma.engine.function.FunctionInputs; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.financial.OpenGammaCompilationContext; import com.opengamma.financial.OpenGammaExecutionContext; import com.opengamma.financial.analytics.timeseries.DateConstraint; import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils; import com.opengamma.financial.currency.CurrencyMatrixValue.CurrencyMatrixCross; import com.opengamma.financial.currency.CurrencyMatrixValue.CurrencyMatrixFixed; import com.opengamma.financial.currency.CurrencyMatrixValue.CurrencyMatrixValueRequirement; import com.opengamma.id.ExternalId; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult; import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver; import com.opengamma.util.money.Currency; import com.opengamma.util.timeseries.localdate.LocalDateDoubleTimeSeries; // TODO jonathan 2012-02-01 -- added this for immediate demo needs. Need to revisit and fully implement. public abstract class PnlSeriesCurrencyConversionFunction extends AbstractFunction.NonCompiledInvoker { private static final String CONVERSION_CCY_PROPERTY = "ConversionCurrency"; private final String _currencyMatrixName; private CurrencyMatrix _currencyMatrix; public PnlSeriesCurrencyConversionFunction(final String currencyMatrixName) { _currencyMatrixName = currencyMatrixName; } protected CurrencyMatrix getCurrencyMatrix() { return _currencyMatrix; } protected void setCurrencyMatrix(final CurrencyMatrix currencyMatrix) { _currencyMatrix = currencyMatrix; } protected String getCurrencyMatrixName() { return _currencyMatrixName; } @Override public void init(final FunctionCompilationContext context) { super.init(context); final CurrencyMatrix matrix = OpenGammaCompilationContext.getCurrencyMatrixSource(context).getCurrencyMatrix(getCurrencyMatrixName()); setCurrencyMatrix(matrix); if (matrix != null) { if (matrix.getUniqueId() != null) { context.getFunctionReinitializer().reinitializeFunction(this, matrix.getUniqueId()); } } } @Override public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues) { final ComputedValue originalPnlSeriesComputedValue = inputs.getComputedValue(ValueRequirementNames.PNL_SERIES); final HistoricalTimeSeries hts = (HistoricalTimeSeries) inputs.getValue(ValueRequirementNames.HISTORICAL_TIME_SERIES); LocalDateDoubleTimeSeries conversionTS = hts.getTimeSeries(); final LocalDateDoubleTimeSeries originalPnlSeries = (LocalDateDoubleTimeSeries) originalPnlSeriesComputedValue.getValue(); final Currency originalCurrency = Currency.of(originalPnlSeriesComputedValue.getSpecification().getProperty(ValuePropertyNames.CURRENCY)); final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues); final String desiredCurrencyCode = desiredValue.getConstraint(ValuePropertyNames.CURRENCY); final ConfigDBCurrencyPairsSource currencyPairsSource = new ConfigDBCurrencyPairsSource(OpenGammaExecutionContext.getConfigSource(executionContext)); final CurrencyPairs currencyPairs = currencyPairsSource.getCurrencyPairs(CurrencyPairs.DEFAULT_CURRENCY_PAIRS); final Currency desiredCurrency = Currency.of(desiredCurrencyCode); if (currencyPairs.getCurrencyPair(originalCurrency, desiredCurrency).getBase().equals(desiredCurrency)) { conversionTS = conversionTS.reciprocal().toLocalDateDoubleTimeSeries(); } final LocalDateDoubleTimeSeries fxSeries = convertSeries(originalPnlSeries, conversionTS, originalCurrency, desiredCurrency); return ImmutableSet.of(new ComputedValue(getValueSpec(originalPnlSeriesComputedValue.getSpecification(), desiredCurrencyCode), fxSeries)); } @Override public ComputationTargetType getTargetType() { return ComputationTargetType.POSITION; } @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { return getCurrencyMatrix() != null; } @Override public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) { final Set<String> desiredCurrencyValues = desiredValue.getConstraints().getValues(ValuePropertyNames.CURRENCY); if (desiredCurrencyValues == null || desiredCurrencyValues.size() != 1) { return null; } final ValueProperties constraints = desiredValue.getConstraints().copy() .withoutAny(ValuePropertyNames.CURRENCY).withAny(ValuePropertyNames.CURRENCY) .with(CONVERSION_CCY_PROPERTY, Iterables.getOnlyElement(desiredCurrencyValues)) .withOptional(CONVERSION_CCY_PROPERTY).get(); return ImmutableSet.of(new ValueRequirement(ValueRequirementNames.PNL_SERIES, target.toSpecification(), constraints)); } @Override public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) { final ValueRequirement inputRequirement = Iterables.getOnlyElement(inputs.values()); final ValueSpecification inputSpec = Iterables.getOnlyElement(inputs.keySet()); return ImmutableSet.of(getValueSpec(inputSpec, inputRequirement.getConstraint(CONVERSION_CCY_PROPERTY))); } @Override public Set<ValueRequirement> getAdditionalRequirements(final FunctionCompilationContext context, final ComputationTarget target, final Set<ValueSpecification> inputs, final Set<ValueSpecification> outputs) { final ValueSpecification input = inputs.iterator().next(); // only one input, so must be the P&L Series final Currency originalCurrency = Currency.of(input.getProperty(ValuePropertyNames.CURRENCY)); final ValueSpecification output = outputs.iterator().next(); // only one output, so must be the result P&L Series final Currency desiredCurrency = Currency.of(output.getProperty(ValuePropertyNames.CURRENCY)); return getCurrencyMatrix().getConversion(originalCurrency, desiredCurrency).accept( new TimeSeriesCurrencyConversionRequirements(OpenGammaCompilationContext.getHistoricalTimeSeriesResolver(context))); } protected ValueSpecification getValueSpec(final ValueSpecification inputSpec, final String currencyCode) { final ValueProperties properties = inputSpec.getProperties().copy() .withoutAny(ValuePropertyNames.FUNCTION) .with(ValuePropertyNames.FUNCTION, getUniqueId()) .withoutAny(ValuePropertyNames.CURRENCY) .with(ValuePropertyNames.CURRENCY, currencyCode).get(); return new ValueSpecification(ValueRequirementNames.PNL_SERIES, inputSpec.getTargetSpecification(), properties); } private LocalDateDoubleTimeSeries convertSeries(final LocalDateDoubleTimeSeries sourceTs, final LocalDateDoubleTimeSeries conversionTS, final Currency sourceCurrency, final Currency targetCurrency) { final CurrencyMatrixValue fxConversion = getCurrencyMatrix().getConversion(sourceCurrency, targetCurrency); return fxConversion.accept(new TimeSeriesCurrencyConverter(sourceTs, conversionTS)); } private class TimeSeriesCurrencyConverter implements CurrencyMatrixValueVisitor<LocalDateDoubleTimeSeries> { private final LocalDateDoubleTimeSeries _baseTs; private final LocalDateDoubleTimeSeries _conversionTS; public TimeSeriesCurrencyConverter(final LocalDateDoubleTimeSeries baseTs, final LocalDateDoubleTimeSeries conversionTS) { _baseTs = baseTs; _conversionTS = conversionTS; } public LocalDateDoubleTimeSeries getBaseTimeSeries() { return _baseTs; } public LocalDateDoubleTimeSeries getConversionTimeSeries() { return _conversionTS; } @Override public LocalDateDoubleTimeSeries visitFixed(final CurrencyMatrixFixed fixedValue) { return (LocalDateDoubleTimeSeries) getBaseTimeSeries().multiply(fixedValue.getFixedValue()); } @Override public LocalDateDoubleTimeSeries visitValueRequirement(final CurrencyMatrixValueRequirement uniqueId) { return (LocalDateDoubleTimeSeries) getBaseTimeSeries().multiply(getConversionTimeSeries()); } @Override public LocalDateDoubleTimeSeries visitCross(final CurrencyMatrixCross cross) { // TODO throw new UnsupportedOperationException(); } } private class TimeSeriesCurrencyConversionRequirements implements CurrencyMatrixValueVisitor<Set<ValueRequirement>> { private final HistoricalTimeSeriesResolver _timeSeriesResolver; public TimeSeriesCurrencyConversionRequirements(final HistoricalTimeSeriesResolver timeSeriesResolver) { _timeSeriesResolver = timeSeriesResolver; } public HistoricalTimeSeriesResolver getTimeSeriesResolver() { return _timeSeriesResolver; } @Override public Set<ValueRequirement> visitFixed(final CurrencyMatrixFixed fixedValue) { return Collections.emptySet(); } @Override public Set<ValueRequirement> visitValueRequirement(final CurrencyMatrixValueRequirement uniqueId) { final ValueRequirement requirement = uniqueId.getValueRequirement(); final ExternalId targetId = requirement.getTargetSpecification().getIdentifier(); final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(targetId.toBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null); if (timeSeries == null) { return null; } // TODO: this is not great, but we don't know the range of the underlying time series when the graph is built return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE, DateConstraint.EARLIEST_START, true, DateConstraint.VALUATION_TIME, true)); } @Override public Set<ValueRequirement> visitCross(final CurrencyMatrixCross cross) { // TODO throw new UnsupportedOperationException(); } } }
package imagej; import imagej.plugin.PluginIndex; import imagej.service.Service; import imagej.service.ServiceHelper; import imagej.service.ServiceIndex; import imagej.util.CheckSezpoz; import imagej.util.Manifest; import imagej.util.POM; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; /** * Top-level application context for ImageJ, which initializes and maintains a * list of services. * * @author Curtis Rueden * @see Service */ public class Context { /** @deprecated Use {@link Context#getVersion()} instead. */ @Deprecated public static final String VERSION = POM.getPOM(Context.class, "net.imagej", "ij-core").getVersion(); private static boolean sezpozNeedsToRun = true; // -- Fields -- /** Title of the application context. */ private String title = "ImageJ"; /** Index of the application context's services. */ private final ServiceIndex serviceIndex; /** Master index of all plugins known to the application context. */ private final PluginIndex pluginIndex; /** Maven POM with metadata about ImageJ. */ private final POM pom; /** JAR manifest with metadata about ImageJ. */ private final Manifest manifest; /** Creates a new ImageJ application context with all available services. */ public Context() { this(false); } /** * Creates a new ImageJ application context. * * @param empty If true, the context will be empty; otherwise, it will be * initialized with all available services. */ public Context(final boolean empty) { this(empty ? Collections.<Class<? extends Service>> emptyList() : null); } /** * Creates a new ImageJ application context with the specified services (and * any required service dependencies). * <p> * <b>Developer's note:</b> This constructor's argument is raw (i.e., * {@code Class...} instead of {@code Class<? extends Service>...}) because * otherwise, downstream invocations (e.g., * {@code new ImageJ(DisplayService.class)}) yield the potentially confusing * warning: * </p> * <blockquote>Type safety: A generic array of Class<? extends Service> is * created for a varargs parameter</blockquote> * <p> * To avoid this, we have opted to use raw types and suppress the relevant * warnings here instead. * </p> * * @param serviceClasses A list of types that implement the {@link Service} * interface (e.g., {@code DisplayService.class}). * @throws ClassCastException If any of the given arguments do not implement * the {@link Service} interface. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public Context(final Class... serviceClasses) { this(serviceClasses != null ? (Collection) Arrays.asList(serviceClasses) : null); } /** * Creates a new ImageJ application context with the specified services (and * any required service dependencies). * * @param serviceClasses A collection of types that implement the * {@link Service} interface (e.g., {@code DisplayService.class}). */ public Context(final Collection<Class<? extends Service>> serviceClasses) { if (sezpozNeedsToRun) { // First context! Check that annotations were generated properly. try { if (!CheckSezpoz.check(false)) { // SezPoz uses ClassLoader.getResources() which will now pick up the // apt-generated annotations. System.err.println("SezPoz generated annotations."); // no log service } } catch (final IOException e) { e.printStackTrace(); } sezpozNeedsToRun = false; } serviceIndex = new ServiceIndex(); pluginIndex = new PluginIndex(); pluginIndex.discover(); pom = POM.getPOM(Context.class, "net.imagej", "ij-core"); manifest = Manifest.getManifest(Context.class); final ServiceHelper serviceHelper = new ServiceHelper(this, serviceClasses); serviceHelper.loadServices(); } // -- ImageJ methods -- /** * Gets the title of the application context. The default value is "ImageJ" * but it can be overridden by calling {@link #setTitle(String)}. */ public String getTitle() { return title; } /** Overrides the title of the application context. */ public void setTitle(final String title) { this.title = title; } public String getVersion() { return pom.getVersion(); } /** Gets the Maven POM containing metadata about the application context. */ public POM getPOM() { return pom; } /** * Gets the manifest containing metadata about the application context. * <p> * NB: This metadata may be null if run in a development environment. * </p> */ public Manifest getManifest() { return manifest; } /** * Gets a string with information about the application context. * * @param mem If true, memory usage information is included. */ public String getInfo(final boolean mem) { final String appTitle = getTitle(); final String appVersion = getVersion(); final String javaVersion = System.getProperty("java.version"); final String osArch = System.getProperty("os.arch"); final long maxMem = Runtime.getRuntime().maxMemory(); final long totalMem = Runtime.getRuntime().totalMemory(); final long freeMem = Runtime.getRuntime().freeMemory(); final long usedMem = totalMem - freeMem; final long usedMB = usedMem / 1048576; final long maxMB = maxMem / 1048576; final StringBuilder sb = new StringBuilder(); sb.append(appTitle + " " + appVersion); sb.append("; Java " + javaVersion + " [" + osArch + "]"); if (mem) sb.append("; " + usedMB + "MB of " + maxMB + "MB"); return sb.toString(); } public ServiceIndex getServiceIndex() { return serviceIndex; } public PluginIndex getPluginIndex() { return pluginIndex; } /** Gets the service of the given class. */ public <S extends Service> S getService(final Class<S> c) { return serviceIndex.getService(c); } /** Gets the service of the given class name (useful for scripts). */ public Service getService(final String className) { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); @SuppressWarnings("unchecked") final Class<Service> serviceClass = (Class<Service>) loader.loadClass(className); return getService(serviceClass); } catch (ClassNotFoundException exc) { return null; } } public boolean inject(final Object o) { if (!(o instanceof Contextual)) return false; final Contextual c = (Contextual) o; if (c.getContext() == this) return true; c.setContext(this); return true; } }
package org.pwsafe.passwordsafeswt.dialog; import java.util.Random; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pwsafe.passwordsafeswt.dto.PwsEntryDTO; import org.pwsafe.passwordsafeswt.preference.DisplayPreferences; import org.pwsafe.passwordsafeswt.preference.PasswordPolicyPreferences; import org.pwsafe.passwordsafeswt.preference.SecurityPreferences; import org.pwsafe.passwordsafeswt.util.ShellHelpers; import org.pwsafe.passwordsafeswt.util.UserPreferences; /** * The Dialog that allows a user to edit password entries. * * @author Glen Smith */ public class EditDialog extends Dialog { private static final Log log = LogFactory.getLog(EditDialog.class); private Text txtNotes; private Text txtPassword; private Text txtUsername; private Text txtTitle; private Text txtGroup; private boolean dirty; protected Object result; protected Shell shell; private PwsEntryDTO entryToEdit; public EditDialog(Shell parent, int style, PwsEntryDTO entryToEdit) { super(parent, style); this.entryToEdit = entryToEdit; } public EditDialog(Shell parent, PwsEntryDTO entryToEdit) { this(parent, SWT.NONE, entryToEdit); } public Object open() { createContents(); ShellHelpers.centreShell(getParent(), shell); shell.pack(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return result; } /** * Returns whether the data in the dialog has been updated by the user. * * @return true if the data has been updated, false otherwise */ public boolean isDirty() { return dirty; } /** * Marks the dialog as having data that needs to be updated. * * @param dirty true if the dialog data needs saving, false otherwise. */ public void setDirty(boolean dirty) { this.dirty = dirty; } protected void createContents() { shell = new Shell(getParent(), SWT.RESIZE | SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); shell.setSize(530, 340); shell.setText("Edit/View Entry"); final GridLayout gridLayout_2 = new GridLayout(); gridLayout_2.marginWidth = 10; gridLayout_2.marginHeight = 10; shell.setLayout(gridLayout_2); // Setup adapter to catch any keypress and mark dialog dirty KeyAdapter dirtyKeypress = new KeyAdapter() { public void keyPressed(KeyEvent e) { setDirty(true); } }; final Composite compositeLabel = new Composite(shell, SWT.NONE); final GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); gridData.widthHint = 499; compositeLabel.setLayoutData(gridData); compositeLabel.setLayout(new GridLayout()); final Label labelInfo = new Label(compositeLabel, SWT.WRAP); final GridData gridData_1 = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL); gridData_1.widthHint = 499; labelInfo.setLayoutData(gridData_1); labelInfo.setText("To edit this entry from the current password file, simply make the desired changes in the fields below. Note that at least a title and a password are still required."); final Composite compositeFields = new Composite(shell, SWT.NONE); compositeFields.setLayout(new FormLayout()); final GridData gridData_c = new GridData(GridData.FILL_BOTH); gridData_c.widthHint = 499; compositeFields.setLayoutData(gridData_c); final Label lblGroup = new Label(compositeFields, SWT.NONE); final FormData formData = new FormData(); formData.top = new FormAttachment(0, 10); formData.left = new FormAttachment(0, 17); lblGroup.setLayoutData(formData); lblGroup.setText("Group:"); txtGroup = new Text(compositeFields, SWT.BORDER); txtGroup.addKeyListener(dirtyKeypress); final FormData formData_1 = new FormData(); formData_1.left = new FormAttachment(lblGroup, 30); formData_1.top = new FormAttachment(lblGroup, 0, SWT.TOP); formData_1.right = new FormAttachment(43, 0); txtGroup.setLayoutData(formData_1); if (entryToEdit.getGroup() != null) txtGroup.setText(entryToEdit.getGroup()); final Label lblTitle = new Label(compositeFields, SWT.NONE); final FormData formData_2 = new FormData(); formData_2.top = new FormAttachment(txtGroup, 10, SWT.BOTTOM); formData_2.left = new FormAttachment(lblGroup, 0, SWT.LEFT); lblTitle.setLayoutData(formData_2); lblTitle.setText("Title:"); txtTitle = new Text(compositeFields, SWT.BORDER); final FormData formData_3 = new FormData(); formData_3.top = new FormAttachment(txtGroup, 10, SWT.BOTTOM); formData_3.left = new FormAttachment(txtGroup, 0, SWT.LEFT); formData_3.right = new FormAttachment(txtGroup, 0 , SWT.RIGHT); txtTitle.setLayoutData(formData_3); txtTitle.addKeyListener(dirtyKeypress); if (entryToEdit.getTitle() != null) txtTitle.setText(entryToEdit.getTitle()); final Label lblUsername = new Label(compositeFields, SWT.NONE); final FormData formData_4 = new FormData(); formData_4.top = new FormAttachment(txtTitle, 10, SWT.BOTTOM); formData_4.left = new FormAttachment(lblTitle, 0, SWT.LEFT); lblUsername.setLayoutData(formData_4); lblUsername.setText("Username:"); txtUsername = new Text(compositeFields, SWT.BORDER); final FormData formData_5 = new FormData(); formData_5.top = new FormAttachment(txtTitle, 10); formData_5.left = new FormAttachment(txtTitle, 0, SWT.LEFT); formData_5.right = new FormAttachment(txtTitle, 0 , SWT.RIGHT); txtUsername.setLayoutData(formData_5); txtUsername.addKeyListener(dirtyKeypress); if (entryToEdit.getUsername() != null) txtUsername.setText(entryToEdit.getUsername()); final Label lblPassword = new Label(compositeFields, SWT.NONE); final FormData formData_6 = new FormData(); formData_6.top = new FormAttachment(txtUsername, 10, SWT.BOTTOM); formData_6.left = new FormAttachment(lblUsername, 0, SWT.LEFT); lblPassword.setLayoutData(formData_6); lblPassword.setText("Password:"); txtPassword = new Text(compositeFields, SWT.BORDER); final FormData formData_7 = new FormData(); formData_7.top = new FormAttachment(txtUsername, 10, SWT.BOTTOM); formData_7.left = new FormAttachment(txtUsername, 0, SWT.LEFT); formData_7.right = new FormAttachment(txtUsername, 0 , SWT.RIGHT); txtPassword.setLayoutData(formData_7); txtPassword.addKeyListener(dirtyKeypress); if (!UserPreferences.getInstance().getBoolean(DisplayPreferences.SHOW_PASSWORD_IN_EDIT_MODE)) { txtPassword.setEchoChar('*'); } if (entryToEdit.getPassword() != null) txtPassword.setText(entryToEdit.getPassword()); final Button btnShowPassword = new Button(compositeFields, SWT.NONE); btnShowPassword.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (txtPassword.getEchoChar() != '\0') { txtPassword.setEchoChar('\0'); btnShowPassword.setText("Hide Password"); } else { btnShowPassword.setText("Show Password"); txtPassword.setEchoChar('*'); } } }); final FormData formData_8 = new FormData(); formData_8.left = new FormAttachment(txtPassword, 10); formData_8.top = new FormAttachment(txtUsername, 10, SWT.BOTTOM); formData_8.right = new FormAttachment(70, 0); btnShowPassword.setLayoutData(formData_8); btnShowPassword.setText("Show Password"); final Label lblNotes = new Label(compositeFields, SWT.NONE); final FormData formData_9 = new FormData(); formData_9.top = new FormAttachment(txtPassword, 5, SWT.BOTTOM); formData_9.left = new FormAttachment(lblPassword, 0, SWT.LEFT); lblNotes.setLayoutData(formData_9); lblNotes.setText("Notes:"); txtNotes = new Text(compositeFields, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.WRAP); final FormData formData_10 = new FormData(); formData_10.bottom = new FormAttachment(100, -5); formData_10.top = new FormAttachment(txtPassword, 5, SWT.BOTTOM); formData_10.right = new FormAttachment(btnShowPassword, 0, SWT.RIGHT); formData_10.left = new FormAttachment(txtPassword, 0, SWT.LEFT); txtNotes.setLayoutData(formData_10); txtNotes.addKeyListener(dirtyKeypress); if (entryToEdit.getNotes() != null) txtNotes.setText(entryToEdit.getNotes()); final Button btnOk = new Button(compositeFields, SWT.NONE); shell.setDefaultButton(btnOk); btnOk.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (isDirty()) { entryToEdit.setGroup(txtGroup.getText()); entryToEdit.setTitle(txtTitle.getText()); entryToEdit.setUsername(txtUsername.getText()); entryToEdit.setPassword(txtPassword.getText()); entryToEdit.setNotes(txtNotes.getText()); result = entryToEdit; } else { result = null; } shell.dispose(); } }); final FormData formData_11 = new FormData(); formData_11.top = new FormAttachment(txtGroup, 0, SWT.TOP); formData_11.left = new FormAttachment(100,-80); formData_11.right = new FormAttachment(100, -10); btnOk.setLayoutData(formData_11); btnOk.setText("OK"); final Button btnCancel = new Button(compositeFields, SWT.NONE); btnCancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { result = null; shell.dispose(); } }); final FormData formData_12 = new FormData(); formData_12.top = new FormAttachment(btnOk, 5); formData_12.left = new FormAttachment(btnOk, 0, SWT.LEFT); formData_12.right = new FormAttachment(btnOk, 0, SWT.RIGHT); btnCancel.setLayoutData(formData_12); btnCancel.setText("Cancel"); final Button btnHelp = new Button(compositeFields, SWT.NONE); final FormData formData_13 = new FormData(); formData_13.top = new FormAttachment(btnCancel, 5); formData_13.left = new FormAttachment(btnCancel, 0, SWT.LEFT); formData_13.right = new FormAttachment(btnCancel, 0, SWT.RIGHT); btnHelp.setLayoutData(formData_13); btnHelp.setText("Help"); final Group group = new Group(compositeFields, SWT.NONE); group.setLayout(new GridLayout()); group.setText("Random Password"); final FormData formData_14 = new FormData(); formData_14.left = new FormAttachment(txtNotes, 10); formData_14.top = new FormAttachment(btnShowPassword, 5, SWT.BOTTOM); formData_14.right = new FormAttachment(100, 0); group.setLayoutData(formData_14); final Button btnGenerate = new Button(group, SWT.NONE); btnGenerate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { String generatedPassword = generatePassword(); txtPassword.setText(generatedPassword); } }); btnGenerate.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); btnGenerate.setText("Generate"); final Button chkOverride = new Button(group, SWT.CHECK); chkOverride.setText("Override Policy"); } private String generatePassword() { String BASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; String BASE_DIGITS = "1234567890"; String BASE_SYMBOLS = "!@ StringBuffer pwSet = new StringBuffer(); UserPreferences.reload(); // make sure we have a fresh copy UserPreferences preferenceStore = UserPreferences.getInstance(); String passwordLengthStr = preferenceStore.getString(PasswordPolicyPreferences.DEFAULT_PASSWORD_LENGTH); int passwordLength = 0; if (passwordLengthStr != null && passwordLengthStr.trim().length() > 0) { passwordLength = Integer.parseInt(passwordLengthStr); } if (passwordLength <= 0) passwordLength = 8; //let's be sensible about this.. boolean useLowerCase = preferenceStore.getBoolean(PasswordPolicyPreferences.USE_LOWERCASE_LETTERS); boolean useUpperCase = preferenceStore.getBoolean(PasswordPolicyPreferences.USE_UPPERCASE_LETTERS); boolean useDigits = preferenceStore.getBoolean(PasswordPolicyPreferences.USE_DIGITS); boolean useSymbols = preferenceStore.getBoolean(PasswordPolicyPreferences.USE_SYMBOLS); boolean useEasyToRead = preferenceStore.getBoolean(PasswordPolicyPreferences.USE_EASY_TO_READ); if (useLowerCase) { pwSet.append(BASE_LETTERS.toLowerCase()); } if (useUpperCase) { pwSet.append(BASE_LETTERS.toUpperCase()); } if (useDigits) { pwSet.append(BASE_DIGITS); } if (useSymbols) { pwSet.append(BASE_SYMBOLS); } StringBuffer sb = new StringBuffer(); if (pwSet.length() > 0) { Random rand = new Random(System.currentTimeMillis()); for (int i = 0; i < passwordLength; i++) { int randOffset = rand.nextInt(pwSet.length()); sb.append(pwSet.charAt(randOffset)); } } else { sb.append("Must Edit Password Generation Options"); } return sb.toString(); } }
package com.intellij.refactoring.move.moveClassesOrPackages; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiElementFilter; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.PackageWrapper; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.util.*; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.util.IncorrectOperationException; import com.intellij.util.Processor; import org.jetbrains.annotations.NotNull; import java.util.*; /** * @author yole */ public class MoveClassToInnerProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.move.moveClassesOrPackages.MoveClassToInnerProcessor"); private PsiClass myClassToMove; private PsiClass myTargetClass; private PsiPackage mySourcePackage; private PsiPackage myTargetPackage; private String mySourceVisibility; private boolean mySearchInComments; private boolean mySearchInNonJavaFiles; private NonCodeUsageInfo[] myNonCodeUsages; private static final Key<List<NonCodeUsageInfo>> ourNonCodeUsageKey = Key.create("MoveClassToInner.NonCodeUsage"); public MoveClassToInnerProcessor(Project project, final PsiClass classToMove, @NotNull final PsiClass targetClass, boolean searchInComments, boolean searchInNonJavaFiles) { super(project); setClassToMove(classToMove); myTargetClass = targetClass; mySearchInComments = searchInComments; mySearchInNonJavaFiles = searchInNonJavaFiles; myTargetPackage = myTargetClass.getContainingFile().getContainingDirectory().getPackage(); } private void setClassToMove(final PsiClass classToMove) { myClassToMove = classToMove; mySourceVisibility = VisibilityUtil.getVisibilityModifier(myClassToMove.getModifierList()); mySourcePackage = myClassToMove.getContainingFile().getContainingDirectory().getPackage(); } protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { return new MoveClassesOrPackagesViewDescriptor(new PsiElement[] { myClassToMove }, mySearchInComments, mySearchInNonJavaFiles, myTargetClass.getQualifiedName()); } @NotNull public UsageInfo[] findUsages() { List<UsageInfo> usages = new ArrayList<UsageInfo>(); String newName = myTargetClass.getQualifiedName() + "." + myClassToMove.getName(); Collections.addAll(usages, MoveClassesOrPackagesUtil.findUsages(myClassToMove, mySearchInComments, mySearchInNonJavaFiles, newName)); for (Iterator<UsageInfo> iterator = usages.iterator(); iterator.hasNext();) { UsageInfo usageInfo = iterator.next(); if (!(usageInfo instanceof NonCodeUsageInfo) && PsiTreeUtil.isAncestor(myClassToMove, usageInfo.getElement(), false)) { iterator.remove(); } } return usages.toArray(new UsageInfo[usages.size()]); } protected boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) { return showConflicts(getConflicts(refUsages.get())); } protected void refreshElements(final PsiElement[] elements) { assert elements.length == 1; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { setClassToMove((PsiClass)elements[0]); } }); } protected void performRefactoring(UsageInfo[] usages) { if (!prepareWritable(usages)) return; try { saveNonCodeUsages(usages); ChangeContextUtil.encodeContextInfo(myClassToMove, true); PsiClass newClass = (PsiClass)myTargetClass.addBefore(myClassToMove, myTargetClass.getRBrace()); newClass.getModifierList().setModifierProperty(PsiModifier.STATIC, true); newClass = (PsiClass)ChangeContextUtil.decodeContextInfo(newClass, null, null); retargetClassRefs(myClassToMove, newClass); Map<PsiElement, PsiElement> oldToNewElementsMapping = new HashMap<PsiElement, PsiElement>(); oldToNewElementsMapping.put(myClassToMove, newClass); myNonCodeUsages = MoveClassesOrPackagesProcessor.retargetUsages(usages, oldToNewElementsMapping); retargetNonCodeUsages(newClass); PsiManager.getInstance(myProject).getCodeStyleManager().removeRedundantImports((PsiJavaFile)newClass.getContainingFile()); myClassToMove.delete(); } catch (IncorrectOperationException e) { LOG.error(e); } } private boolean prepareWritable(final UsageInfo[] usages) { Set<PsiElement> elementsToMakeWritable = new HashSet<PsiElement>(); elementsToMakeWritable.add(myClassToMove); elementsToMakeWritable.add(myTargetClass); for(UsageInfo usage: usages) { PsiElement element = usage.getElement(); if (element != null) { elementsToMakeWritable.add(element); } } if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, elementsToMakeWritable.toArray(new PsiElement[elementsToMakeWritable.size()]))) { return false; } return true; } private void saveNonCodeUsages(final UsageInfo[] usages) { for(UsageInfo usageInfo: usages) { if (usageInfo instanceof NonCodeUsageInfo) { final NonCodeUsageInfo nonCodeUsage = (NonCodeUsageInfo)usageInfo; PsiElement element = nonCodeUsage.getElement(); if (element != null && PsiTreeUtil.isAncestor(myClassToMove, element, false)) { List<NonCodeUsageInfo> list = element.getCopyableUserData(ourNonCodeUsageKey); if (list == null) { list = new ArrayList<NonCodeUsageInfo>(); element.putCopyableUserData(ourNonCodeUsageKey, list); } list.add(nonCodeUsage); } } } } private void retargetNonCodeUsages(final PsiClass newClass) { newClass.accept(new PsiRecursiveElementVisitor() { public void visitElement(final PsiElement element) { super.visitElement(element); List<NonCodeUsageInfo> list = element.getCopyableUserData(ourNonCodeUsageKey); if (list != null) { for(NonCodeUsageInfo info: list) { for(int i=0; i<myNonCodeUsages.length; i++) { if (myNonCodeUsages [i] == info) { myNonCodeUsages [i] = info.replaceElement(element); break; } } } element.putCopyableUserData(ourNonCodeUsageKey, null); } } }); } protected void performPsiSpoilingRefactoring() { RefactoringUtil.renameNonCodeUsages(myProject, myNonCodeUsages); } private static void retargetClassRefs(final PsiClass classToMove, final PsiClass newClass) { newClass.accept(new PsiRecursiveElementVisitor() { public void visitReferenceElement(final PsiJavaCodeReferenceElement reference) { PsiElement element = reference.resolve(); if (element instanceof PsiClass && PsiTreeUtil.isAncestor(classToMove, element, false)) { PsiClass newInnerClass = findMatchingClass(classToMove, newClass, (PsiClass) element); try { reference.bindToElement(newInnerClass); } catch(IncorrectOperationException ex) { LOG.error(ex); } } else { super.visitReferenceElement(reference); } } }); } private static PsiClass findMatchingClass(final PsiClass classToMove, final PsiClass newClass, final PsiClass innerClass) { if (classToMove == innerClass) { return newClass; } PsiClass parentClass = findMatchingClass(classToMove, newClass, innerClass.getContainingClass()); PsiClass newInnerClass = parentClass.findInnerClassByName(innerClass.getName(), false); assert newInnerClass != null; return newInnerClass; } protected String getCommandName() { return RefactoringBundle.message("move.class.to.inner.command.name", myClassToMove.getQualifiedName(), myTargetClass.getQualifiedName()); } @NotNull protected Collection<? extends PsiElement> getElementsToWrite(final UsageViewDescriptor descriptor) { List<PsiElement> result = new ArrayList<PsiElement>(); result.addAll(super.getElementsToWrite(descriptor)); result.add(myTargetClass); return result; } public List<String> getConflicts(final UsageInfo[] usages) { List<String> conflicts = new ArrayList<String>(); if (myTargetClass.findInnerClassByName(myClassToMove.getName(), false) != null) { conflicts.add(RefactoringBundle.message("move.to.inner.duplicate.inner.class", CommonRefactoringUtil.htmlEmphasize(myTargetClass.getQualifiedName()), CommonRefactoringUtil.htmlEmphasize(myClassToMove.getName()))); } String classToMoveVisibility = VisibilityUtil.getVisibilityModifier(myClassToMove.getModifierList()); String targetClassVisibility = VisibilityUtil.getVisibilityModifier(myTargetClass.getModifierList()); boolean moveToOtherPackage = !Comparing.equal(mySourcePackage, myTargetPackage); if (moveToOtherPackage) { PsiElement[] elementsToMove = new PsiElement[] { myClassToMove }; myClassToMove.accept(new PackageLocalsUsageCollector(elementsToMove, new PackageWrapper(myTargetPackage), conflicts)); } ConflictsCollector collector = new ConflictsCollector(conflicts); if ((moveToOtherPackage && (classToMoveVisibility.equals(PsiModifier.PACKAGE_LOCAL) || targetClassVisibility.equals(PsiModifier.PACKAGE_LOCAL))) || targetClassVisibility.equals(PsiModifier.PRIVATE)) { detectInaccessibleClassUsages(usages, collector); } if (moveToOtherPackage) { detectInaccessibleMemberUsages(collector); } return conflicts; } private void detectInaccessibleClassUsages(final UsageInfo[] usages, final ConflictsCollector collector) { for(UsageInfo usage: usages) { if (usage instanceof MoveRenameUsageInfo && !(usage instanceof NonCodeUsageInfo)) { PsiElement element = usage.getElement(); if (element == null || PsiTreeUtil.getParentOfType(element, PsiImportStatement.class) != null) continue; if (isInaccessibleFromTarget(element, mySourceVisibility)) { collector.addConflict(myClassToMove, element); } } } } private boolean isInaccessibleFromTarget(final PsiElement element, final String visibility) { final PsiPackage elementPackage = element.getContainingFile().getContainingDirectory().getPackage(); return !PsiUtil.isAccessible(myTargetClass, element, null) || (visibility.equals(PsiModifier.PACKAGE_LOCAL) && !Comparing.equal(elementPackage, myTargetPackage)); } private void detectInaccessibleMemberUsages(final ConflictsCollector collector) { PsiElement[] members = collectPackageLocalMembers(); for(PsiElement member: members) { ReferencesSearch.search(member).forEach(new Processor<PsiReference>() { public boolean process(final PsiReference psiReference) { PsiElement element = psiReference.getElement(); if (isInaccessibleFromTarget(element, PsiModifier.PACKAGE_LOCAL)) { collector.addConflict(psiReference.resolve(), element); } return true; } }); } } private PsiElement[] collectPackageLocalMembers() { return PsiTreeUtil.collectElements(myClassToMove, new PsiElementFilter() { public boolean isAccepted(final PsiElement element) { if (element instanceof PsiMember) { PsiMember member = (PsiMember) element; if (VisibilityUtil.getVisibilityModifier(member.getModifierList()) == PsiModifier.PACKAGE_LOCAL) { return true; } } return false; } }); } private class ConflictsCollector { private final List<String> myConflicts; private final Set<PsiElement> myReportedContainers = new HashSet<PsiElement>(); public ConflictsCollector(final List<String> conflicts) { myConflicts = conflicts; } public void addConflict(final PsiElement targetElement, final PsiElement sourceElement) { PsiElement container = ConflictsUtil.getContainer(sourceElement); if (container == null) return; if (!myReportedContainers.contains(container)) { myReportedContainers.add(container); String targetDescription = (targetElement == myClassToMove) ? "Class " + CommonRefactoringUtil.htmlEmphasize(myClassToMove.getName()) : StringUtil.capitalize(ConflictsUtil.getDescription(targetElement, true)); final String message = RefactoringBundle.message("element.will.no.longer.be.accessible", targetDescription, ConflictsUtil.getDescription(container, true)); myConflicts.add(message); } } } }
package org.ow2.proactive_grid_cloud_portal.scheduler.server; import java.io.InputStream; import java.util.Map; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.annotations.GZIP; import org.jboss.resteasy.plugins.providers.multipart.MultipartInput; import org.ow2.proactive_grid_cloud_portal.scheduler.client.controller.TasksCentricController; /** * @author ffonteno * * Interface defining a client for the REST service */ @Path("/scheduler/") public interface RestClient { /** * Disconnect the user identified by the sessionId from the scheduler * * @param sessionId the session id of the user */ @PUT @Path("disconnect") void disconnect(@HeaderParam("sessionid") final String sessionId); /** * Gets the list of jobs in a JSON array * * @param sessionId the session id of the user * @return a ClientResponse containing the response status and the JSON array including the job list, in case of success. */ @GET @Path("jobsinfo") @Produces({ "application/json", "application/xml" }) InputStream jobs(@HeaderParam("sessionid") String sessionId); /** * Submits a job to the Scheduler. * @param sessionId the session id of the user that performs the submission * @param multipart the multipart message that encodes the job descriptor file * @return a ClientResponse containing the response status and the job id generated, in case of success. */ @POST @Path("submit") @Consumes(MediaType.MULTIPART_FORM_DATA) String jobs(@HeaderParam("sessionid") String sessionId, MultipartInput multipart); /** * Submit a flat command job * Each line in the file is a command that will be run on a different node * @param commandFileContent content of the flat command file, one task per line * @param jobName name of the job * @param selectionScriptContent selection script or null */ @POST @Path("submitflat") @Produces("application/json") String submitFlat(@HeaderParam("sessionid") String sessionId, @FormParam("commandFileContent") String commandFileContent, @FormParam("jobName") String jobName, @FormParam("selectionScriptContent") String selectionScriptContent, @FormParam("selectionScriptExtension") String selectionScriptExtension); /** * Deletes a job from the Scheduler. * @param sessionId the session id of the user that performs the deletion * @param jobId the id of the job that will be deleted * @return a ClientResponse containing the response status and true - if the removed was successfully, false - otherwise. */ @DELETE @Path("jobs/{jobid}") InputStream removeJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Pauses a job. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job that will be deleted * @return a ClientResponse containing the response status and true - if the job was successfully paused, false - otherwise. */ @PUT @Path("jobs/{jobid}/pause") InputStream pauseJob(@HeaderParam("sessionid") final String sessionId, @PathParam("jobid") final String jobId); /** * Restart all in error tasks in a job. * @param sessionId the session id of the user which is logged in * @param jobId the job id which will be resumed * @return a ClientResponse containing the response status and true - if the job was successfully restarted, false - otherwise. */ @PUT @Path("jobs/{jobid}/restartAllInErrorTasks") InputStream restartAllTasksInError(@HeaderParam("sessionid") final String sessionId, @PathParam("jobid") final String jobId); /** * Resumes a job. * @param sessionId the session id of the user which is logged in * @param jobId the job id which will be resumed * @return a ClientResponse containing the response status and true - if the job was successfully resumed, false - otherwise. */ @PUT @Path("jobs/{jobid}/resume") InputStream resumeJob(@HeaderParam("sessionid") final String sessionId, @PathParam("jobid") final String jobId); /** * Kills a job. * @param sessionId the session id of the user which is logged in * @param jobId the job id which will be resumed * @return a ClientResponse containing the response status. */ @PUT @Path("jobs/{jobid}/kill") InputStream killJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Kill a task */ @PUT @Path("jobs/{jobid}/tasks/{taskname}/kill") InputStream killTask(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskname") String taskName); /** * Preempt a task */ @PUT @Path("jobs/{jobid}/tasks/{taskname}/preempt") InputStream preemptTask(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskname") String taskName); /** * Mark as finished and resume */ @PUT @Path("jobs/{jobid}/tasks/{taskname}/finishInErrorTask") InputStream markAsFinishedAndResume(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskname") String taskName); /** * Restart a running task. */ @PUT @Path("jobs/{jobid}/tasks/{taskname}/restart") InputStream restartTask(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskname") String taskName); /** * Restart a task paused on error. */ @PUT @Path("jobs/{jobid}/tasks/{taskname}/restartInErrorTask") InputStream restartInErrorTask(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskname") String taskName); /** * Gets the list of tasks in a JSON array for a given job. * @param sessionId the session id of the user which is logged in * @param jobId the job id for which the tasks are asked. * @return a ClientResponse containing the response status and the JSON array including the task list, in case of success. */ @GET @GZIP @Path("jobs/{jobid}/taskstates") @Produces("application/json") InputStream getJobTaskStates(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Returns a list of taskState with pagination * @param sessionId a valid session id * @param jobId the job id * @return a list of task' states of the job <code>jobId</code> */ @GET @GZIP @Path("jobs/{jobid}/taskstates/paginated") @Produces("application/json") InputStream getJobTaskStatesPaginated(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit); @GET @GZIP @Path("jobs/{jobid}/taskstates/filtered/paginated") @Produces("application/json") InputStream getJobTaskStatesPaginated(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit, @QueryParam("statusFilter") @DefaultValue("") String statusFilter); /** * Gets the list of tasks in a JSON array for a given job and filtered by a given tag. * @param sessionId the session id of the user which is logged in * @param jobId the job id for which the tasks are asked. * @param tag the tag used to filter the tasks. * @return a ClientResponse containing the response status and the JSON array including the task list, in case of success. */ @GET @GZIP @Path("jobs/{jobid}/taskstates/{tasktag}") @Produces("application/json") InputStream getJobTaskStatesByTag(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("tasktag") String tag); /** * Returns a list of taskState of the tasks filtered by a given tag and paginated. * @param sessionId a valid session id. * @param jobId the job id. * @param taskTag the tag used to filter the tasks. * @param offset the number of the first task to fetch * @param limit the number of the last task to fetch (non inclusive) * @return a list of task' states of the job <code>jobId</code> filtered by a given tag, for a given pagination. */ @GET @GZIP @Path("jobs/{jobid}/taskstates/{tasktag}/paginated") @Produces("application/json") InputStream getJobTaskStatesByTagPaginated(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("tasktag") String taskTag, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit); /** * Returns a list of taskState of the tasks filtered by a given tag and paginated. * @param sessionId a valid session id. * @param jobId the job id. * @param offset the number of the first task to fetch * @param limit the number of the last task to fetch (non inclusive) * @param taskTag the tag used to filter the tasks. * @param statusFilter aggregation status to apply in filter * @return a list of task' states of the job <code>jobId</code> filtered by a given tag, for a given pagination. */ @GET @GZIP @Path("jobs/{jobid}/taskstates/{tasktag}/{statusFilter}/paginated") @Produces("application/json") InputStream getJobTaskStatesByTagAndStatusPaginated(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit, @PathParam("tasktag") String taskTag, @PathParam("statusFilter") String statusFilter); /** * Returns a paginated list of <code>TaskStateData</code> regarding the given parameters (decoupled from the associated jobs). * The result is paginated using the optional <code>offset</code> and <code>limit</code> parameters. * If those parameters are not specified, the following values will be used: [0, DEFAULT_VALUE[ * The DEFAULT_VALUE can be set in the scheduler config file as the <code>pa.scheduler.tasks.page.size</code> parameter. * * @param sessionId a valid session id. * @param from the scheduled date to which we start fetching tasks. The format is in Epoch time. * @param to the end scheduled end date to stop fetching tasks. The format is in Epoch time. * @param mytasks <code>True</code> if you want to fetch only the user's tasks. Default value is <code>False</code>. * @param running fetch running tasks. Default value is <code>True</code>. * @param pending fetch pending tasks. Default value is <code>True</code>. * @param finished fetch finished tasks. Default value is <code>True</code>. * @param offset the index of the first task to fetch (for pagination). * @param limit the index of the last (excluded) task to fetch (for pagination). * @param sortParameters the tasks sorting parameters. * @return a list of <code>TaskStateData</code> and the total number of them. */ @GET @GZIP @Path("taskstates") @Produces("application/json") InputStream getTaskStates(@HeaderParam("sessionid") String sessionId, @QueryParam("from") @DefaultValue("0") long from, @QueryParam("to") @DefaultValue("0") long to, @QueryParam("mytasks") @DefaultValue("false") boolean mytasks, @QueryParam("running") @DefaultValue("true") boolean running, @QueryParam("pending") @DefaultValue("true") boolean pending, @QueryParam("finished") @DefaultValue("true") boolean finished, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("-1") int limit, @QueryParam("sortparameters") TasksCentricController.SortSpecifierRestContainer sortParameters); /** * Returns a paginated list of <code>TaskStateData</code> regarding the given parameters (decoupled from the associated jobs). * The result is paginated using the optional <code>offset</code> and <code>limit</code> parameters. * If those parameters are not specified, the following values will be used: [0, DEFAULT_VALUE[ * The DEFAULT_VALUE can be set in the scheduler config file as the <code>pa.scheduler.tasks.page.size</code> parameter. * * @param sessionId a valid session id. * @param taskTag tag to filter the tasks. The tag should be complete as the criteria is strict. * @param from the scheduled date to which we start fetching tasks. The format is in Epoch time. * @param to the end scheduled end date to stop fetching tasks. The format is in Epoch time. * @param mytasks <code>True</code> if you want to fetch only the user's tasks. <code>False</code> will fetch everything. * @param running fetch running tasks. Default value is <code>True</code>. * @param pending fetch pending tasks. Default value is <code>True</code>. * @param finished fetch finished tasks. Default value is <code>True</code>. * @param offset the index of the first task to fetch (for pagination). * @param limit the index of the last (excluded) task to fetch (for pagination). * @param sortParameters the tasks sorting parameters. * @return a list of <code>TaskStateData</code> and the total number of them. */ @GET @GZIP @Path("taskstates/tag/{tasktag}") @Produces("application/json") InputStream getTaskStatesByTag(@HeaderParam("sessionid") String sessionId, @PathParam("tasktag") String taskTag, @QueryParam("from") @DefaultValue("0") long from, @QueryParam("to") @DefaultValue("0") long to, @QueryParam("mytasks") @DefaultValue("false") boolean mytasks, @QueryParam("running") @DefaultValue("true") boolean running, @QueryParam("pending") @DefaultValue("true") boolean pending, @QueryParam("finished") @DefaultValue("true") boolean finished, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("-1") int limit, @QueryParam("sortparameters") TasksCentricController.SortSpecifierRestContainer sortParameters); /** * Returns a list of the tags of the tasks belonging to job <code>jobId</code> and filtered by a prefix pattern * @param sessionId a valid session id * @param jobId jobid one wants to list the tasks' tags * @param prefix the prefix used to filter tags * @return a list of tasks' name */ @GET @Path("jobs/{jobid}/tasks/tags/startsWith/{prefix}") @Produces("application/json") InputStream getJobTaskTagsPrefix(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("prefix") String prefix); /** * Gets the state of a certain job. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job * @return a ClientResponse containing the response status and an InputStream containing information about the state of the job. */ @GET @Path("jobs/{jobid}") @Produces("application/json") InputStream job(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Returns the job info associated to the job referenced by the * id <code>jobid</code> * @param sessionId a valid session id * @return a ClientResponse containing the job info of the corresponding job */ @GET @GZIP @Path("jobs/{jobid}/info") @Produces("application/json") InputStream jobInfo(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Returns the job's original workflow as XML. * id <code>jobid</code> * @param sessionId a valid session id * @return a ClientResponse containing the Workflow's XML of the corresponding job */ @GET @GZIP @Path("jobs/{jobid}/xml") @Produces("application/xml") InputStream getJobXML(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Changes the priority of a job. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job * @param priorityName the new priority of the job */ @PUT @Path("jobs/{jobid}/priority/byname/{name}") void schedulerChangeJobPriorityByName(@HeaderParam("sessionid") final String sessionId, @PathParam("jobid") final String jobId, @PathParam("name") String priorityName); /** * Pauses the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully paused and false in case of a * failure */ @PUT @Path("pause") InputStream pauseScheduler(@HeaderParam("sessionid") final String sessionId); /** * Resumes the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully resumed and false in case of a * failure */ @PUT @Path("resume") InputStream resumeScheduler(@HeaderParam("sessionid") final String sessionId); /** * Freezes the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully resumed and false in case of a * failure */ @PUT @Path("freeze") InputStream freezeScheduler(@HeaderParam("sessionid") final String sessionId); /** * Kills the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully killed and false in case of a * failure */ @PUT @Path("kill") InputStream killScheduler(@HeaderParam("sessionid") final String sessionId); /** * Shutdown the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully shutdown and false in case of a * failure */ @PUT @Path("shutdown") InputStream shutdownScheduler(@HeaderParam("sessionid") final String sessionId); /** * Starts the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was successfully started and false in case of a * failure */ @PUT @Path("start") InputStream startScheduler(@HeaderParam("sessionid") final String sessionId); /** * Stops the Scheduler. * @param sessionId the session id of the user which is logged in * @return a ClientResponse containing the response status and true if the Scheduler was stopped paused and false in case of a * failure */ @PUT @Path("stop") InputStream stopScheduler(@HeaderParam("sessionid") final String sessionId); /** * Gets the tasks ids for a job. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job for which the list of task ids is asked for * @return a ClientResponse containing the response status and a list of strings which represent the list of tasks ids */ @GET @Path("jobs/{jobid}/tasks") @Produces("application/json") InputStream getJobTasksIds(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Gets all the logs for a finished task. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task corresponds to * @param taskId the id of the task * @return a ClientResponse containing the response status and a string with the logs */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/log/all") @Produces("application/json") String tasklog(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * Gets the logs for a finished task, only on stdout * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task corresponds to * @param taskId the id of the task * @return a ClientResponse containing the response status and a string with the logs */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/log/out") @Produces("application/json") String taskStdout(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * Gets the logs for a finished task, only on stderr * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task corresponds to * @param taskId the id of the task * @return a ClientResponse containing the response status and a string with the logs */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/log/err") @Produces("application/json") String taskStderr(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * Stream the output of job identified by the id <code>jobid</code> * only stream currently available logs, call this method several times * to get the complete output. * @param sessionId a valid session id * @param jobId the id of the job to retrieve */ @GET @GZIP @Path("jobs/{jobid}/livelog") @Produces("application/json") String getLiveLogJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * number of available bytes in the stream or -1 if the stream does not exist. * @param sessionId a valid session id * @param jobId the id of the job to retrieve */ @GET @Path("jobs/{jobid}/livelog/available") @Produces("application/json") String getLiveLogJobAvailable(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * remove the live log object. * @param sessionId a valid session id * @param jobId the id of the job to retrieve */ @DELETE @Path("jobs/{jobid}/livelog") @Produces("application/json") InputStream deleteLiveLogJob(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Gets server logs for a given task. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task corresponds to * @param taskId the id of the task * @return a ClientResponse containing the response status and a string with the server logs */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/log/server") @Produces("application/json") String taskServerLogs(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * Gets server logs for a given job. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task corresponds to * @return a ClientResponse containing the response status and a string with the server logs */ @GET @GZIP @Path("jobs/{jobid}/log/server") @Produces("application/json") String jobServerLogs(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Gets the result of a task. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task belongs * @param taskId the id of the task to which the result is asked * @return the result of the task */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/value") @Produces("*/*") InputStream taskresult(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * Gets the result of a task. * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task belongs * @param taskId the id of the task to which the result is asked * @return the result of the task */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/metadata") @Produces("application/json") InputStream taskResultMetadata(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task belongs * @return all precious task results' metadata associated to the <code>jobId</code> */ @GET @GZIP @Path("jobs/{jobid}/tasks/results/precious/metadata") @Produces("application/json") InputStream getPreciousTaskName(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Gets the serialized result of a task. * * @param sessionId the session id of the user which is logged in * @param jobId the id of the job to which the task belongs * @param taskId the id of the task to which the result is asked * @return the serialized result of the task */ @GET @GZIP @Path("jobs/{jobid}/tasks/{taskid}/result/serializedvalue") @Produces("*/*") InputStream taskSerializedResult(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId, @PathParam("taskid") String taskId); /** * returns statistics about the scheduler * @param sessionId the session id associated to this new connection * @return a string containing the statistics */ @GET @Path("stats") @Produces("application/json") String getStatistics(@HeaderParam("sessionid") final String sessionId); /** * returns a string containing some data regarding the user's account * @param sessionId the session id associated to this new connection * @return a string containing some data regarding the user's account */ @GET @Path("stats/myaccount") @Produces("application/json") String getStatisticsOnMyAccount(@HeaderParam("sessionid") final String sessionId); /** * Returns the revision number of the scheduler state * @param sessionId a valid session id. * @return the revision of the scheduler state */ @GET @Path("state/revision") @Produces({ "application/json", "application/xml" }) String schedulerStateRevision(@HeaderParam("sessionid") String sessionId); /** * Returns an html visualization corresponding of a jobid * @param sessionId a valid session id * @param jobId the job id * @return an html visualization corresponding of a <code>jobId</code> */ @GET @Path("jobs/{jobid}/html") @Produces("text/html") InputStream getJobHtml(@HeaderParam("sessionid") String sessionId, @PathParam("jobid") String jobId); /** * Users currently connected to the scheduler * * @param sessionId the session id associated to this new connection */ @GET @GZIP @Path("users") @Produces({ "application/json", "application/xml" }) InputStream getSchedulerUsers(@HeaderParam("sessionid") String sessionId); /** * Users having jobs in the scheduler * * @param sessionId the session id associated to this new connection */ @GET @GZIP @Path("userswithjobs") @Produces({ "application/json", "application/xml" }) InputStream getSchedulerUsersWithJobs(@HeaderParam("sessionid") String sessionId); /** * Returns the Scheduler status as a String, * ie org.ow2.proactive.scheduler.common.SchedulerStatus.toString() * @param sessionId a valid session id * @return a String describing the current scheduler status */ @GET @Path("status") String schedulerStatus(@HeaderParam("sessionid") String sessionId); @GET @Path("version") InputStream getVersion(); @GET @Path("usage/myaccount") @Produces("application/json") InputStream getUsageOnMyAccount(@HeaderParam("sessionid") String sessionId, @QueryParam("startdate") String startDate, @QueryParam("enddate") String endDate); @GET @Path("usage/account") @Produces("application/json") InputStream getUsageOnAccount(@HeaderParam("sessionid") String sessionId, @QueryParam("user") String user, @QueryParam("startdate") String startDate, @QueryParam("enddate") String endDate); @POST @Path("/credentials/{key}") void putThirdPartyCredential(@HeaderParam("sessionid") String sessionId, @PathParam("key") @Encoded String key, @FormParam("value") String value); @DELETE @Path("/credentials/{key}") void removeThirdPartyCredential(@HeaderParam("sessionid") String sessionId, @PathParam("key") @Encoded String key); @GET @Path("/credentials/") @Produces("application/json") InputStream thirdPartyCredentialsKeySet(@HeaderParam("sessionid") String sessionId); @GET @Path("configuration/portal") @Produces("application/json") Map<Object, Object> getSchedulerPortalDisplayProperties(@HeaderParam("sessionid") String sessionId); }
package edu.wustl.catissuecore.bizlogic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.json.JSONArray; import org.json.JSONObject; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.bizlogic.DefaultBizLogic; import edu.wustl.common.cde.PermissibleValueImpl; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.util.logger.Logger; import edu.wustl.dao.DAO; import edu.wustl.dao.exception.DAOException; /** * @author sagar_baldwa */ public class ComboDataBizLogic extends CatissueDefaultBizLogic { private transient final Logger logger = Logger.getCommonLogger(ComboDataBizLogic.class); /** * This method would return the Clinical Diagnosis List * @return List which contains the Clinical Diagnosis Data * @throws BizLogicException * @throws BizLogicException */ public List getClinicalDiagnosisList(String query, boolean showSubset) throws BizLogicException { // populating clinical Diagnosis field final List<NameValueBean> clinicalDiagnosisList = new ArrayList(); final String sourceObjectName = PermissibleValueImpl.class.getName(); final String[] selectColumnName = { "value" }; DAO dao = null; try { new DefaultBizLogic(); dao = this.openDAOSession(null); String hql = "Select PermissibleValueImpl.value from edu.wustl.common.cde.PermissibleValueImpl " + "PermissibleValueImpl WHERE LOWER(PermissibleValueImpl.value) like LOWER('%" + query + "%') AND PermissibleValueImpl.cde.publicId = 'Clinical_Diagnosis_PID' " + "order by PermissibleValueImpl.value desc"; List dataList = dao.executeQuery(hql); clinicalDiagnosisList .add(new NameValueBean(Constants.SELECT_OPTION, "" + Constants.SELECT_OPTION_VALUE)); if (showSubset) { clinicalDiagnosisList .add(new NameValueBean(Constants.SHOW_SUBSET + "start", Constants.SHOW_SUBSET)); } int cnt = 1; final Iterator<String> iterator = dataList.iterator(); while (iterator.hasNext()) { final String clinicaDiagnosisvalue = iterator.next(); if (clinicaDiagnosisvalue.toString().toLowerCase().startsWith( query.toLowerCase())) { clinicalDiagnosisList.add(1, new NameValueBean( clinicaDiagnosisvalue, clinicaDiagnosisvalue)); cnt++; } else { clinicalDiagnosisList.add(cnt, new NameValueBean( clinicaDiagnosisvalue, clinicaDiagnosisvalue)); } } if (showSubset) { clinicalDiagnosisList.add(new NameValueBean( Constants.SHOW_SUBSET + "end", Constants.SHOW_SUBSET)); } this.closeDAOSession(dao); } catch (final DAOException exp) { this.logger.error(exp.getMessage(), exp); exp.printStackTrace(); throw this.getBizLogicException(exp, exp.getErrorKeyName(), exp .getMsgValues()); } finally { this.closeDAOSession(dao); } return clinicalDiagnosisList; } /** * This method fetches the required number of records from Clinical * Diagnosis List and poplulates in the Combo Box on UI. * @param limitFetch * is the limit to fetch and display the Clinical Diagnosis * records in Combo Box on UI * @param startFetch * is the position from where you fetch the Clinical Diagnosis * data from the List * @param query * holds the string which the user has typed down in combo box * for autocomplete feature * @return JSONObject which holds the list to eb poplulated on UI front */ public JSONObject getClinicalDiagnosisData(Integer limitFetch, Integer startFetch, String query, Collection<NameValueBean> clinicalDiagnosisBean,String showOption) { JSONObject jsonObject = null; JSONArray jsonArray = null; try { jsonArray = new JSONArray(); jsonObject = new JSONObject(); final List<NameValueBean> clinicalDiagnosisList; boolean showSubset = false; if(!clinicalDiagnosisBean.isEmpty() && Constants.SHOW_ALL_VALUES.equals(showOption)) { showSubset = true; } if (clinicalDiagnosisBean == null || clinicalDiagnosisBean.isEmpty() || Constants.SHOW_ALL_VALUES.equals(showOption)) { clinicalDiagnosisList = this.getClinicalDiagnosisList(query,showSubset); } else { clinicalDiagnosisList = (List<NameValueBean>) clinicalDiagnosisBean; } jsonObject.put("totalCount", new Integer(clinicalDiagnosisList.size())); final ListIterator<NameValueBean> iterator = clinicalDiagnosisList.listIterator(startFetch + 1); final Integer total = limitFetch + startFetch; // 1st record in List has value -1, so startFetch is incremented and // made to fetch data from 2nd element from the List startFetch++; boolean flag = false; while (startFetch < total + 1) { if (iterator.hasNext()) { final NameValueBean nameValueBean = iterator.next(); if (nameValueBean.getName().toLowerCase().contains(query.toLowerCase()) || query == null) { final JSONObject innerJsonObject = new JSONObject(); // nameValueBean = (NameValueBean) iterator.next(); innerJsonObject.put("id", nameValueBean.getName()); innerJsonObject.put("field", nameValueBean.getValue()); jsonArray.put(innerJsonObject); flag = true; } else if (flag) { break; } } startFetch++; } jsonObject.put("row", jsonArray); } catch (final Exception e) { this.logger.error(e.getMessage(), e); e.printStackTrace(); //System.out.println(e); } return jsonObject; } }
package gov.nih.nci.caarray.web.action.project; import static gov.nih.nci.caarray.web.action.CaArrayActionHelper.getGenericDataService; import static gov.nih.nci.caarray.web.action.CaArrayActionHelper.getProjectManagementService; import gov.nih.nci.caarray.application.project.InconsistentProjectStateException; import gov.nih.nci.caarray.application.project.ProposalWorkflowException; import gov.nih.nci.caarray.business.vocabulary.VocabularyServiceException; import gov.nih.nci.caarray.domain.AbstractCaArrayEntity; import gov.nih.nci.caarray.domain.sample.Source; import gov.nih.nci.caarray.domain.search.SourceSortCriterion; import gov.nih.nci.caarray.security.PermissionDeniedException; import gov.nih.nci.caarray.security.SecurityUtils; import gov.nih.nci.caarray.util.UsernameHolder; import gov.nih.nci.caarray.web.ui.PaginatedListImpl; import java.util.Collection; import org.apache.struts2.interceptor.validation.SkipValidation; import com.fiveamsolutions.nci.commons.web.struts2.action.ActionHelper; import com.opensymphony.xwork2.validator.annotations.CustomValidator; import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator; import com.opensymphony.xwork2.validator.annotations.Validation; import com.opensymphony.xwork2.validator.annotations.ValidationParameter; import com.opensymphony.xwork2.validator.annotations.Validations; /** * Action implementing the sources tab. * @author Dan Kokotov */ @Validation @Validations( requiredFields = @RequiredFieldValidator(fieldName = "currentSource.tissueSite", key = "struts.validator.requiredString", message = "") ) public class ProjectSourcesAction extends AbstractProjectListTabAction { private static final long serialVersionUID = 1L; private Source currentSource = new Source(); /** * Default constructor. */ public ProjectSourcesAction() { super("source", new PaginatedListImpl<Source, SourceSortCriterion>(PAGE_SIZE, SourceSortCriterion.NAME.name(), SourceSortCriterion.class)); } /** * {@inheritDoc} * @throws VocabularyServiceException */ @Override public void prepare() throws VocabularyServiceException { super.prepare(); if (this.currentSource.getId() != null) { Source retrieved = getGenericDataService().getPersistentObject(Source.class, this.currentSource.getId()); if (retrieved == null) { throw new PermissionDeniedException(this.currentSource, SecurityUtils.READ_PRIVILEGE, UsernameHolder.getUser()); } else { this.currentSource = retrieved; } } } /** * {@inheritDoc} * @throws ProposalWorkflowException */ @Override protected void doCopyItem() throws ProposalWorkflowException, InconsistentProjectStateException { getProjectManagementService().copySource(getProject(), this.currentSource.getId()); } /** * {@inheritDoc} */ @Override protected Collection<Source> getCollection() { return getProject().getExperiment().getSources(); } /** * {@inheritDoc} */ @Override protected AbstractCaArrayEntity getItem() { return getCurrentSource(); } /** * @return the currentSource */ @CustomValidator(type = "hibernate", parameters = @ValidationParameter(name = "resourceKeyBase", value = "experiment.sources")) public Source getCurrentSource() { return this.currentSource; } /** * @param currentSource the currentSource to set */ public void setCurrentSource(Source currentSource) { this.currentSource = currentSource; } /** * {@inheritDoc} */ @SkipValidation @Override public String delete() { if (!getCurrentSource().getSamples().isEmpty()) { ActionHelper.saveMessage(getText("experiment.annotations.cantdelete", new String[] {getText("experiment.source"), getText("experiment.sample") })); updatePagedList(); return "list"; } return super.delete(); } }
package com.pcalouche.spat.security.provider; import com.pcalouche.spat.config.SpatProperties; import com.pcalouche.spat.entity.User; import com.pcalouche.spat.repository.UserRepository; import com.pcalouche.spat.security.authentication.JwtAuthenticationToken; import com.pcalouche.spat.security.util.SecurityUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.HashSet; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(SpringExtension.class) @Import({ SecurityUtils.class }) @EnableConfigurationProperties(value = SpatProperties.class) @TestPropertySource("classpath:application-test.properties") public class JwtAuthenticationProviderTest { @Autowired private SecurityUtils securityUtils; private JwtAuthenticationProvider jwtAuthenticationProvider; @MockBean private UserRepository userRepository; private String validJwtToken; private String validRefreshToken; private User activeUser; @BeforeEach public void before() { Mockito.reset(userRepository); activeUser = User.builder().username("activeUser").build(); activeUser.setPassword(SecurityUtils.PASSWORD_ENCODER.encode("password")); given(userRepository.findByUsername(activeUser.getUsername())).willReturn(Optional.ofNullable(activeUser)); given(userRepository.findByUsername("bogusUser")).willReturn(Optional.empty()); jwtAuthenticationProvider = new JwtAuthenticationProvider(securityUtils, userRepository); JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken("activeUser", new HashSet<>()); validJwtToken = securityUtils.createToken(authenticationToken); validRefreshToken = securityUtils.createRefreshTokenCookie(authenticationToken.getName()).getValue(); } @Test public void testAuthenticate() { JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(validJwtToken); Authentication authentication = jwtAuthenticationProvider.authenticate(authenticationToken); assertThat(authentication.getName()).isEqualTo("activeUser"); assertThat(authentication.getCredentials()).isNull(); assertThat(authentication.getAuthorities()).isEmpty(); // User service should not be hit for non refresh token verify(userRepository, Mockito.times(0)).findByUsername("activeUser"); } @Test public void testAuthenticateThrowsBadCredentialsForNullToken() { JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(null); assertThatThrownBy(() -> jwtAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("JSON web token was empty."); } @Test public void testAuthenticateHandlesRefreshToken() { JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(validRefreshToken); Authentication authentication = jwtAuthenticationProvider.authenticate(authenticationToken); assertThat(authentication.getName()).isEqualTo("activeUser"); assertThat(authentication.getCredentials()).isNull(); assertThat(authentication.getAuthorities()).isEmpty(); // User service should be hit for non refresh token verify(userRepository, Mockito.times(1)).findByUsername("activeUser"); } @Test public void testAuthenticateRefreshTokenHandlesDisabledUserAccount() { // Disable the active user. They should not be given a refresh token activeUser.setEnabled(false); JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(validRefreshToken); // All other cases are tested in SecurityUtilsTest. This just checks that the conditional is hit assertThatThrownBy(() -> jwtAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(DisabledException.class) .hasMessage("Disabled account for username: activeUser"); // User service should be hit for non refresh token verify(userRepository, Mockito.times(1)).findByUsername("activeUser"); } @Test public void testAuthenticateRefreshTokenHandlesDeletedUserAccount() { // Simulate that the user was deleted from the database since they last received a token given(userRepository.findByUsername(activeUser.getUsername())).willReturn(Optional.empty()); JwtAuthenticationToken authenticationToken = new JwtAuthenticationToken(validRefreshToken); // All other cases are tested in SecurityUtilsTest. This just checks that the conditional is hit assertThatThrownBy(() -> jwtAuthenticationProvider.authenticate(authenticationToken)) .isInstanceOf(BadCredentialsException.class) .hasMessage("Bad credentials for username: activeUser"); // User service should be hit for non refresh token verify(userRepository, Mockito.times(1)).findByUsername("activeUser"); } @Test public void testSupportValidAuthenticationClass() { assertThat(jwtAuthenticationProvider.supports(JwtAuthenticationToken.class)).isTrue(); } @Test public void testSupportInvalidAuthenticationClass() { assertThat(jwtAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)).isFalse(); } }
package no.uio.ifi.alboc.scanner; /* * module Scanner */ import no.uio.ifi.alboc.chargenerator.CharGenerator; import no.uio.ifi.alboc.error.Error; import no.uio.ifi.alboc.log.Log; import static no.uio.ifi.alboc.scanner.Token.*; /* * Module for forming characters into tokens. */ public class Scanner { public static Token curToken, nextToken; public static String curName, nextName; public static int curNum, nextNum; public static int curLine, nextLine; public static void init() { // -- Must be changed in part 0: } public static void finish() { // -- Must be changed in part 0: } public static void readNext() { curToken = nextToken; curName = nextName; curNum = nextNum; curLine = nextLine; nextToken = null; while (nextToken == null) { nextLine = CharGenerator.curLineNum(); if (!CharGenerator.isMoreToRead()) { nextToken = eofToken; } else // burde vi sette curToken = nextToken, og s[ assigne nextToken kanskje? hmmm. // check if space if(CharGenerator.curC == ' ') { // skip it somehow } //first we pick up the simple ones: else if(CharGenerator.curC == '+') { curToken = addToken; readNextHelper(); } else if(CharGenerator.curC == '&') { curToken = ampToken; readNextHelper(); } else if(CharGenerator.curC == ',') { curToken = commaToken; readNextHelper(); } else if(CharGenerator.curC == '[') { curToken = leftBrackToken; readNextHelper(); } else if(CharGenerator.curC == '(') { curToken = leftParToken; readNextHelper(); } else if(CharGenerator.curC == '{') { curToken = leftCurlToken; readNextHelper(); } else if(CharGenerator.curC == ']') { curToken = rightBrackToken; readNextHelper(); } else if(CharGenerator.curC == ')') { curToken = rightParToken; readNextHelper(); } else if(CharGenerator.curC == '}') { curToken = rightCurlToken; readNextHelper(); } else if(CharGenerator.curC == ';') { curToken = semiColonToken; readNextHelper(); } else if(CharGenerator.curC == '*') { curToken = starToken; readNextHelper(); // we get a bit more advanced } else if(isNumber(charGenerator.curC) == true) { // do number logic } else if(CharGenerator.curC == '=') { // check if next one is equals as well } else if(CharGenerator.curC == '>') { // check if next one is equals } else if(CharGenerator.curC == '>') { // check if next one is equals } else if(isLetterAZ(CharGenerator.curC) || CharGenerator.curC == '_') { // it's a word, an int, an if, and else or } // -- Must be changed in part 0: { Error.error(nextLine, "Illegal symbol: '" + CharGenerator.curC + "'!"); } } Log.noteToken(); } private void readNextHelper() { // this method does the steps common for all happy cases of readNext } private boolean isNumber(char c) { private char[] legalNumbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; for (int i = 0 ; i < legalNumbers ; i++) if (c == legalNumbers[i]) return true; return false } private static boolean isLetterAZ(char c) { private char[] legalCharacters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; for (int i = 0 ; i < legalCharacters ; i++) if (c == legalCharacters[i]) return true; return false; } public static void check(Token t) { if (curToken != t) Error.expected("A " + t); } public static void check(Token t1, Token t2) { if (curToken != t1 && curToken != t2) Error.expected("A " + t1 + " or a " + t2); } public static void skip(Token t) { check(t); readNext(); } public static void skip(Token t1, Token t2) { check(t1, t2); readNext(); } }
package com.alecstrong.sqlite.android.gradle; import com.alecstrong.sqlite.android.SQLiteParser; import com.alecstrong.sqlite.android.model.Column; import com.alecstrong.sqlite.android.model.ColumnConstraint; import com.alecstrong.sqlite.android.model.NotNullConstraint; import com.alecstrong.sqlite.android.model.SqlStmt.Replacement; import com.google.common.base.Joiner; import java.util.Collections; import java.util.List; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.RuleContext; import org.antlr.v4.runtime.misc.Interval; public class TableGenerator extends com.alecstrong.sqlite.android.TableGenerator<ParserRuleContext, SQLiteParser.Sql_stmtContext, SQLiteParser.Create_table_stmtContext, SQLiteParser.Column_defContext, SQLiteParser.Column_constraintContext> { public TableGenerator(String fileName, SQLiteParser.ParseContext parseContext, String projectPath) { super(parseContext, Joiner.on('.').join(parseContext.package_stmt(0).name().stream() .map(RuleContext::getText).iterator()), fileName, projectPath); } @Override protected Iterable<SQLiteParser.Sql_stmtContext> sqlStatementElements( ParserRuleContext originatingElement) { if (originatingElement instanceof SQLiteParser.ParseContext) { return ((SQLiteParser.ParseContext) originatingElement).sql_stmt_list(0).sql_stmt(); } return Collections.emptyList(); } @Override protected SQLiteParser.Create_table_stmtContext tableElement( ParserRuleContext originatingElement) { if (originatingElement instanceof SQLiteParser.ParseContext) { return ((SQLiteParser.ParseContext) originatingElement).sql_stmt_list(0).create_table_stmt(); } return null; } @Override protected String identifier(SQLiteParser.Sql_stmtContext sqlStatementElement) { return sqlStatementElement.IDENTIFIER() != null ? sqlStatementElement.IDENTIFIER().getText() : null; } @Override protected Iterable<SQLiteParser.Column_defContext> columnElements( SQLiteParser.Create_table_stmtContext tableElement) { return tableElement.column_def(); } @Override protected String tableName(SQLiteParser.Create_table_stmtContext tableElement) { return tableElement.table_name().getText(); } @Override protected boolean isKeyValue(SQLiteParser.Create_table_stmtContext tableElement) { return tableElement.K_KEY_VALUE() != null; } @Override protected String columnName(SQLiteParser.Column_defContext columnElement) { return columnElement.column_name().getText(); } @Override protected String classLiteral(SQLiteParser.Column_defContext columnElement) { return columnElement.type_name().sqlite_class_name() != null ? columnElement.type_name().sqlite_class_name().STRING_LITERAL().getText() : null; } @Override protected String typeName(SQLiteParser.Column_defContext columnElement) { return columnElement.type_name().sqlite_class_name() != null ? columnElement.type_name().sqlite_class_name().getChild(0).getText() : columnElement.type_name().sqlite_type_name().getText(); } @Override protected Replacement replacementFor(SQLiteParser.Column_defContext columnElement, Column.Type type) { return new Replacement(columnElement.type_name().start.getStartIndex(), columnElement.type_name().stop.getStopIndex() + 1, type.replacement); } @Override protected Iterable<SQLiteParser.Column_constraintContext> constraintElements( SQLiteParser.Column_defContext columnElement) { return columnElement.column_constraint(); } @Override protected ColumnConstraint<ParserRuleContext> constraintFor( SQLiteParser.Column_constraintContext constraint, List<Replacement> replacements) { if (constraint.K_NOT() != null) { return new NotNullConstraint<>(constraint); } return null; } @Override protected int startOffset(ParserRuleContext sqliteStatementElement) { if (sqliteStatementElement instanceof SQLiteParser.Create_table_stmtContext) { return sqliteStatementElement.start.getStartIndex(); } return ((ParserRuleContext) sqliteStatementElement.getChild( sqliteStatementElement.getChildCount() - 1)).start.getStartIndex(); } @Override protected String text(ParserRuleContext context) { if (context instanceof SQLiteParser.Sql_stmtContext) { context = (ParserRuleContext) context.getChild(context.getChildCount() - 1); } if (context.start == null || context.stop == null || context.start.getStartIndex() < 0 || context.stop.getStopIndex() < 0) { return context.getText(); // Fallback } return context.start.getInputStream().getText(new Interval( context.start.getStartIndex(), context.stop.getStopIndex())); } }
package ch.unizh.ini.jaer.projects.gesture.virtualdrummer.microphone; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.logging.Logger; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.Mixer; import javax.sound.sampled.TargetDataLine; public class VirtualDrummerMicrophoneInput extends Thread /*implements SpikeReporter, Updateable*/{ Logger log = Logger.getLogger("VirtualDrummer"); private AudioFormat format; // private float readbufferRatio = .5f; private float sampleRate = 8000f; private float sampleTime = 1 / sampleRate; private long threadDelay = (long)10; private TargetDataLine targetDataLine; int numBits = 8; byte threshold = 10, hysteresis = 3; boolean isBeat = false; // flag to mark if mic input is presently above threshold private float tau = 30; // time const of lp filter, ms private byte[] buffer = null; DrumSoundDetectorDemo gui; private int bufferSize=1000; /** Creates a new instance of test. Opens the microphone input as the target line. * To start the reporting, {@link #start} the thread. * @throws LineUnavailableException if microphone input is not available */ public VirtualDrummerMicrophoneInput () throws LineUnavailableException{ // getAudioInfo(); // prints lots of useless information format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,sampleRate,8,1,1,sampleRate,false); DataLine.Info dlinfo = new DataLine.Info(TargetDataLine.class, format); if ( AudioSystem.isLineSupported(dlinfo) ){ targetDataLine = (TargetDataLine)AudioSystem.getLine(dlinfo); } targetDataLine.open(format,bufferSize); bufferSize=targetDataLine.getBufferSize(); gui = new DrumSoundDetectorDemo(); gui.setVirtualDrummerMicrophoneInput(this); } /** starts acquisition from microphone port and generation of {@link DrumSoundBeatEvent}'s. If line is not available it does nothing. */ public void startReporting (){ stop = false; if ( targetDataLine != null ){ targetDataLine.start(); } else{ return; } super.start(); gui.setVisible(true); } private boolean stop = false; /** removes all beat event listeners, ends thread after first stopping microphone acquisition. This ends generation of {@link DrumSoundBeatEvent}'s */ public void stopReporting (){ clearListeners(); stop = true; gui.setVisible(false); } /** grabs samples from microphone input and generates {@link DrumSoundBeatEvent}'s whenver spikes are detected. * Stopped by {@link #stopReporting} */ @Override public void run (){ float lpval = 0; buffer = new byte[ (int)( targetDataLine.getBufferSize() ) ]; // float val = 0f; // byte max = Byte.MIN_VALUE, min = Byte.MAX_VALUE; log.info("started monitoring microphone for drumbeats"); while ( !stop ){ if ( listeners.size() == 0 ){ try{ Thread.sleep(100); } catch ( InterruptedException e ){ } continue; }// don't even bother unless someone is listening if ( targetDataLine.available() < buffer.length ){ // don't process until the buffer has enough data for our external buffer // System.out.println("mic recorder: yielding (only " + targetDataLine.available() + "/" + buffer.length + " available)"); try{ sleep(threadDelay); } catch ( InterruptedException e ){ e.printStackTrace(); } continue; } float m = 1 / ( sampleRate * tau / 1000 ); long lineTime = targetDataLine.getMicrosecondPosition(); int nRead = targetDataLine.read(buffer,0,buffer.length); gui.drawSamples(); // System.out.println("mic recorder: read "+nRead+" bytes"); // System.out.println("level="+targetDataLine.getLevel()); for ( int i = 0 ; i < nRead ; i++ ){ byte b = buffer[i]; int b2 = b * b; lpval = ( 1 - m ) * lpval + m * ( b2 - lpval ); // lowpass IIR filter of squared sound signal if ( !isBeat ){ if ( lpval > threshold ){ isBeat = true; // System.out.println("mic recorder: spike"); informListeners(new DrumBeatSoundEvent(this,(long)( lineTime / 1000 + i * sampleTime * 1000 ))); } } else{ // beat if ( lpval < threshold - hysteresis ){ isBeat = false; } } // val=highpass.filter(b, sampleTime); // max=(byte)(val>max?val:max); // min=(byte)(val<min?val:min); } // System.out.println(min+"\t"+max); try{ sleep(threadDelay); } catch ( InterruptedException e ){ e.printStackTrace(); } } targetDataLine.stop(); // System.out.println("mic recorder: ended"); } void informListeners (DrumBeatSoundEvent e){ Iterator i = listeners.iterator(); while ( i.hasNext() ){ DrumBeatSoundEventListener l = (DrumBeatSoundEventListener)i.next(); l.drumBeatSoundOccurred(e); } } /** Release the line on finialization. */ @Override protected void finalize () throws Throwable{ if ( targetDataLine.isOpen() ){ targetDataLine.close(); } super.finalize(); } LinkedList listeners = new LinkedList(); /** add a listener for all spikes. Listeners are {@link SpikeListener#spikeOccurred called} when a spike occurs and are passed a {@link DrumSoundBeatEvent}. *@param listener the listener */ public void addBeatListener (DrumBeatSoundEventListener listener){ listeners.add(listener); } /** removes a listener *@param listener to remove */ public void removeBeatListener (DrumBeatSoundEventListener listener){ listeners.remove(listener); } /** remove all listeners */ public void clearListeners (){ listeners.clear(); } /** test class by just printing . when it gets beats */ public static void main (String[] args){ try{ VirtualDrummerMicrophoneInput reporter = new VirtualDrummerMicrophoneInput(); reporter.addBeatListener(new DrumBeatSoundPrinter()); reporter.startReporting(); } catch ( LineUnavailableException e ){ e.printStackTrace(); System.exit(1); } } /** @return the Collection of listeners */ public Collection getBeatListeners (){ return listeners; } // prints some audio system information void getAudioInfo (){ Mixer.Info[] mixerInfos = AudioSystem.getMixerInfo(); log.info(mixerInfos.length + " mixers"); for ( int i = 0 ; i < mixerInfos.length ; i++ ){ Mixer mixer = AudioSystem.getMixer(mixerInfos[i]); System.out.println("Mixer " + mixer); // target data lines Line.Info[] lineInfos = mixer.getTargetLineInfo(); System.out.println("\t" + lineInfos.length + " lineInfos"); for ( int j = 0 ; j < lineInfos.length ; j++ ){ if ( lineInfos[j] instanceof DataLine.Info ){ AudioFormat[] formats = ( (DataLine.Info)lineInfos[j] ).getFormats(); System.out.println("\t\t\t" + formats.length + " formats"); for ( int k = 0 ; k < formats.length ; k++ ){ System.out.println("\t\tFormat " + formats[k]); } } Line line = null; try{ line = mixer.getLine(lineInfos[j]); System.out.println("\tLine " + line); } catch ( LineUnavailableException e ){ e.printStackTrace(); } } } } /** @return whether reporting is enabled ({@link java.lang.Thread#isAlive}) */ public boolean isReporting (){ return isAlive(); } /** * @return the tau in ms of LP filter of sound power */ public int getTau (){ return (int)tau; } /** * @param tau the tau in ms of LP filter to set */ public void setTau (int tau){ this.tau = tau; } /** * @return the buffer */ public // time const of lp filter, seconds byte[] getBuffer (){ return buffer; } /** sets the threshold for detecting beats. *@param t the threshold. */ public void setThreshold (int t){ threshold = (byte)t; } /** @return the threshold * @see #setThreshold */ public int getThreshold (){ return threshold; } /** sets the hystersis for beat detection. Set this to avoid triggering multiple beats on a noisy signal. *A new {@link DrumSoundBeatEvent} can be not generated until the input drops below the {@link #getThreshold threshold}-hystersis. */ public void setHystersis (int h){ hysteresis = (byte)h; } /** @return hysteresis *@see #setHystersis */ public int getHystersis (){ return hysteresis; } /** * @return the bufferSize */ public int getBufferSize (){ return bufferSize; } }
package org.rstudio.studio.client.workbench.views.console.shell.assist; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.js.JsUtil; import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations; import org.rstudio.studio.client.common.codetools.Completions; import org.rstudio.studio.client.common.r.RToken; import org.rstudio.studio.client.common.r.RTokenizer; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.workbench.views.source.editors.text.AceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.NavigableSourceEditor; import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeFunction; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.CodeModel; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.model.RnwChunkOptions; import org.rstudio.studio.client.workbench.views.source.model.RnwChunkOptions.RnwOptionCompletionResult; import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext; import java.util.ArrayList; public class CompletionRequester { private final CodeToolsServerOperations server_ ; private final NavigableSourceEditor editor_; private String cachedLinePrefix_ ; private CompletionResult cachedResult_ ; private RnwCompletionContext rnwContext_ ; public CompletionRequester(CodeToolsServerOperations server, RnwCompletionContext rnwContext, NavigableSourceEditor editor) { server_ = server ; rnwContext_ = rnwContext; editor_ = editor; } public void getCompletions( final String line, final int pos, final boolean implicit, final ServerRequestCallback<CompletionResult> callback) { if (cachedResult_ != null && cachedResult_.guessedFunctionName == null) { if (line.substring(0, pos).startsWith(cachedLinePrefix_)) { String diff = line.substring(cachedLinePrefix_.length(), pos) ; if (diff.length() > 0) { ArrayList<RToken> tokens = RTokenizer.asTokens("a" + diff) ; // when we cross a :: the list may actually grow, not shrink if (!diff.endsWith("::")) { while (tokens.size() > 0 && tokens.get(tokens.size()-1).getContent().equals(":")) { tokens.remove(tokens.size()-1) ; } if (tokens.size() == 1 && tokens.get(0).getTokenType() == RToken.ID) { callback.onResponseReceived(narrow(diff)) ; return ; } } } } } doGetCompletions(line, pos, new ServerRequestCallback<Completions>() { @Override public void onError(ServerError error) { callback.onError(error); } @Override public void onResponseReceived(Completions response) { cachedLinePrefix_ = line.substring(0, pos); String token = response.getToken(); JsArrayString comp = response.getCompletions(); JsArrayString pkgs = response.getPackages(); ArrayList<QualifiedName> newComp = new ArrayList<QualifiedName>(); for (int i = 0; i < comp.length(); i++) newComp.add(new QualifiedName(comp.get(i), pkgs.get(i))); // Get completions from the current scope as well. AceEditor editor = (AceEditor) editor_; // NOTE: this will be null in the console, so protect against that if (editor != null) { Position cursorPosition = editor.getSession().getSelection().getCursor(); CodeModel codeModel = editor.getSession().getMode().getCodeModel(); JsArray<ScopeFunction> scopedFunctions = codeModel.getArgumentsFromFunctionsInScope(cursorPosition); for (int i = 0; i < scopedFunctions.length(); i++) { ScopeFunction scopedFunction = scopedFunctions.get(i); String functionName = scopedFunction.getFunctionName(); JsArrayString argNames = scopedFunction.getFunctionArgs(); for (int j = 0; j < argNames.length(); j++) { String argName = argNames.get(j); if (argName.startsWith(token)) { // TODO: Include function name if we can resolve docs newComp.add(new QualifiedName( argName, "" )); } } // We might also want to auto-complete functions names if (functionName.startsWith(token)) { // TODO: Include function name if we can resolve docs newComp.add(new QualifiedName( functionName, "" )); } } } CompletionResult result = new CompletionResult( response.getToken(), newComp, response.getGuessedFunctionName(), response.getSuggestOnAccept()); cachedResult_ = response.isCacheable() ? result : null; if (!implicit || result.completions.size() != 0) callback.onResponseReceived(result); } }) ; } private void doGetCompletions( String line, int pos, ServerRequestCallback<Completions> requestCallback) { int optionsStartOffset; if (rnwContext_ != null && (optionsStartOffset = rnwContext_.getRnwOptionsStart(line, pos)) >= 0) { doGetSweaveCompletions(line, optionsStartOffset, pos, requestCallback); } else { server_.getCompletions(line, pos, requestCallback); } } private void doGetSweaveCompletions( final String line, final int optionsStartOffset, final int cursorPos, final ServerRequestCallback<Completions> requestCallback) { rnwContext_.getChunkOptions(new ServerRequestCallback<RnwChunkOptions>() { @Override public void onResponseReceived(RnwChunkOptions options) { RnwOptionCompletionResult result = options.getCompletions( line, optionsStartOffset, cursorPos, rnwContext_ == null ? null : rnwContext_.getActiveRnwWeave()); Completions response = Completions.createCompletions( result.token, result.completions, JsUtil.createEmptyArray(result.completions.length()) .<JsArrayString>cast(), null); // Unlike other completion types, Sweave completions are not // guaranteed to narrow the candidate list (in particular // true/false). response.setCacheable(false); if (result.completions.length() > 0 && result.completions.get(0).endsWith("=")) { response.setSuggestOnAccept(true); } requestCallback.onResponseReceived(response); } @Override public void onError(ServerError error) { requestCallback.onError(error); } }); } public void flushCache() { cachedLinePrefix_ = null ; cachedResult_ = null ; } private CompletionResult narrow(String diff) { assert cachedResult_.guessedFunctionName == null ; String token = cachedResult_.token + diff ; ArrayList<QualifiedName> newCompletions = new ArrayList<QualifiedName>() ; for (QualifiedName qname : cachedResult_.completions) if (qname.name.startsWith(token)) newCompletions.add(qname) ; return new CompletionResult(token, newCompletions, null, cachedResult_.suggestOnAccept) ; } public static class CompletionResult { public CompletionResult(String token, ArrayList<QualifiedName> completions, String guessedFunctionName, boolean suggestOnAccept) { this.token = token ; this.completions = completions ; this.guessedFunctionName = guessedFunctionName ; this.suggestOnAccept = suggestOnAccept ; } public final String token ; public final ArrayList<QualifiedName> completions ; public final String guessedFunctionName ; public final boolean suggestOnAccept ; } public static class QualifiedName implements Comparable<QualifiedName> { public QualifiedName(String name, String pkgName) { this.name = name ; this.pkgName = pkgName ; } @Override public String toString() { return DomUtils.textToHtml(name) + getFormattedPackageName(); } private String getFormattedPackageName() { return pkgName == null || pkgName.length() == 0 ? "" : " <span class=\"packageName\">{" + DomUtils.textToHtml(pkgName) + "}</span>"; } public static QualifiedName parseFromText(String val) { String name, pkgName = null; int idx = val.indexOf('{') ; if (idx < 0) { name = val ; } else { name = val.substring(0, idx).trim() ; pkgName = val.substring(idx + 1, val.length() - 1) ; } return new QualifiedName(name, pkgName) ; } public int compareTo(QualifiedName o) { if (name.endsWith("=") ^ o.name.endsWith("=")) return name.endsWith("=") ? -1 : 1 ; int result = String.CASE_INSENSITIVE_ORDER.compare(name, o.name) ; if (result != 0) return result ; String pkg = pkgName == null ? "" : pkgName ; String opkg = o.pkgName == null ? "" : o.pkgName ; return pkg.compareTo(opkg) ; } public final String name ; public final String pkgName ; } }
package com.wandrell.tabletop.business.model.pendragon.character; import java.util.Collection; import com.wandrell.tabletop.business.model.character.Gender; import com.wandrell.tabletop.business.model.pendragon.stats.Skill; import com.wandrell.tabletop.business.model.pendragon.stats.SpecialtySkill; import com.wandrell.tabletop.business.model.valuebox.SkillBox; public interface PendragonHumanCharacter extends PendragonBaseCharacter { public void addDirectedTrait(final SkillBox directedTrait); public void addPassion(final SkillBox passion); public void addSkill(final Skill skill); public void addSpecialtySkill(final SpecialtySkill skill); public void clearDirectedTraits(); public void clearPassions(); public void clearSkills(); public void clearSpecialtySkills(); @Override public PendragonHumanCharacter createNewInstance(); public Integer getAppearance(); public Integer getArbitrary(); public Integer getChaste(); public Integer getCowardly(); public Integer getCruel(); public Integer getDeceitful(); public Collection<SkillBox> getDirectedTraits(); public Integer getEnergetic(); public Integer getForgiving(); public Gender getGender(); public Integer getGenerous(); public Integer getHonest(); public Integer getIndulgent(); public Integer getJust(); public Integer getLazy(); public Integer getLustful(); public Integer getMerciful(); public Integer getModest(); public Collection<SkillBox> getPassions(); public Integer getPious(); public Integer getProud(); public Integer getPrudent(); public Integer getReckless(); public Integer getSelfish(); public Collection<Skill> getSkills(); public Collection<SpecialtySkill> getSpecialtySkills(); public Integer getSuspicious(); public Integer getTemperate(); public Integer getTrusting(); public Integer getValorous(); public Integer getVengeful(); public Integer getWorldly(); public void removeDirectedTrait(final SkillBox directedTrait); public void removePassion(final SkillBox passion); public void removeSkill(final Skill skill); public void removeSpecialtySkill(final SpecialtySkill skill); public void setAppearance(final Integer appearance); public void setArbitrary(final Integer arbitrary); public void setChaste(final Integer chaste); public void setCowardly(final Integer cowardly); public void setCruel(final Integer cruel); public void setDeceitful(final Integer deceitful); public void setDirectedTraits(final Collection<SkillBox> directedTraits); public void setEnergetic(final Integer energetic); public void setForgiving(final Integer forgiving); public void setGenerous(final Integer generous); public void setHonest(final Integer honest); public void setIndulgent(final Integer indulgent); public void setJust(final Integer just); public void setLazy(final Integer lazy); public void setLustful(final Integer lustful); public void setMerciful(final Integer merciful); public void setModest(final Integer modest); public void setPassions(final Collection<SkillBox> passions); public void setPious(final Integer pious); public void setProud(final Integer proud); public void setPrudent(final Integer prudent); public void setReckless(final Integer reckless); public void setSelfish(final Integer selfish); public void setSkills(final Collection<Skill> skills); public void setSpecialtySkills(final Collection<SpecialtySkill> skills); public void setSuspicious(final Integer suspicious); public void setTemperate(final Integer temperate); public void setTrusting(final Integer trusting); }
package hr.dlatecki.algorithms.gen_alg.codecs.abstracts; import hr.dlatecki.algorithms.gen_alg.codecs.interfaces.IByteArrayCodec; public abstract class AbstractDoubleArrayToBinaryCodec implements IByteArrayCodec<double[]> { /** * Mask for the lowest byte. */ private static final long BYTE_MASK = 0xFFL; /** * Minimal number of bits per value. */ private static final int MIN_BITS_PER_VALUE = 8; /** * Maximum number of bits per value. */ private static final int MAX_BITS_PER_VALUE = 32; /** * Number of code bits per single <code>double</code> value. */ protected int bitsPerValue; /** * Minimum value which will be encoded. All values smaller than this will have bits set to all zeroes. */ protected double lowerBound; /** * Maximum value which will be encoded. All values greater than this will have bits set to all ones. */ protected double upperBound; /** * Minimum difference between two values when encoding and decoding. */ protected double step; public AbstractDoubleArrayToBinaryCodec(int bitsPerNumber, double lowerBound, double upperBound) { if (bitsPerNumber < MIN_BITS_PER_VALUE || bitsPerNumber > MAX_BITS_PER_VALUE) { throw new IllegalArgumentException("Valid range for number of bits is [" + MIN_BITS_PER_VALUE + ", " + MAX_BITS_PER_VALUE + "]. Provided value was " + bitsPerNumber + "."); } if (lowerBound >= upperBound) { throw new IllegalArgumentException( "Upper bound must be greater than lower bound. Provided values were: lowerBound = " + lowerBound + ", upperBound = " + upperBound + "."); } this.bitsPerValue = bitsPerNumber; this.lowerBound = lowerBound; this.upperBound = upperBound; step = (upperBound - lowerBound) / Math.pow(2.0, bitsPerNumber); } @Override public byte[] encode(double[] item) { int numOfBytes = (int) Math.ceil((item.length * bitsPerValue) / 8.0); byte[] output = new byte[numOfBytes]; if (bitsPerValue == 8) { encode8Bits(item, output); } else if (bitsPerValue < 16) { encode9To15Bits(item, output); } else if (bitsPerValue == 16) { encode16Bits(item, output); } else if (bitsPerValue < 24) { encode17To23Bits(item, output); } else if (bitsPerValue == 24) { encode24Bits(item, output); } else if (bitsPerValue < 32) { encode25To31Bits(item, output); } else { encode32Bits(item, output); } return output; } /** * Used to encode and store values when each value is assigned exactly 8 bits. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode8Bits(double values[], byte[] bytes) { int i = 0; for (double value : values) { long encodedValue = encodeValue(value); bytes[i] = (byte) encodedValue; i++; } } /** * Used to encode and store values when each value is between 9 and 15 bits, inclusive. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode9To15Bits(double[] values, byte[] bytes) { int i = 0; int bitPosition = 0; for (double value : values) { int rot = bitsPerValue + bitPosition - 8; long encodedValue = encodeValue(value); bitPosition = rot; bytes[i] |= (byte) (encodedValue >>> rot); rot = 8 - rot; bytes[i + 1] |= (byte) ((encodedValue << rot) & BYTE_MASK); i++; } } /** * Used to encode and store values when each value is assigned exactly 16 bits. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode16Bits(double values[], byte[] bytes) { int i = 0; for (double value : values) { long encodedValue = encodeValue(value); bytes[i] = (byte) (encodedValue >>> 8L); bytes[i + 1] = (byte) (encodedValue & BYTE_MASK); i += 2; } } /** * Used to encode and store values when each value is between 17 and 23 bits, inclusive. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode17To23Bits(double[] values, byte[] bytes) { int i = 0; int bitPosition = 0; for (double value : values) { int rot = bitsPerValue + bitPosition - 8; long encodedValue = encodeValue(value); bytes[i] |= (byte) (encodedValue >>> rot); rot = bitsPerValue + bitPosition - 16; bitPosition = rot; bytes[i + 1] |= (byte) ((encodedValue >>> rot) & BYTE_MASK); rot = 8 - rot; bytes[i + 2] |= (byte) ((encodedValue << rot) & BYTE_MASK); i += 2; } } /** * Used to encode and store values when each value is assigned exactly 24 bits. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode24Bits(double values[], byte[] bytes) { int i = 0; for (double value : values) { long encodedValue = encodeValue(value); bytes[i] = (byte) (encodedValue >>> 16L); bytes[i + 1] = (byte) ((encodedValue >>> 8L) & BYTE_MASK); bytes[i + 2] = (byte) (encodedValue & BYTE_MASK); i += 3; } } /** * Used to encode and store values when each value is between 25 and 31 bits, inclusive. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode25To31Bits(double[] values, byte[] bytes) { int i = 0; int bitPosition = 0; for (double value : values) { int rot = bitsPerValue + bitPosition - 8; long encodedValue = encodeValue(value); bytes[i] |= (byte) (encodedValue >>> rot); rot = bitsPerValue + bitPosition - 16; bytes[i + 1] |= (byte) ((encodedValue >>> rot) & BYTE_MASK); rot = bitsPerValue + bitPosition - 24; bitPosition = rot; bytes[i + 2] |= (byte) ((encodedValue >>> rot) & BYTE_MASK); rot = 8 - rot; bytes[i + 3] |= (byte) ((encodedValue << rot) & BYTE_MASK); i += 3; } } /** * Used to encode and store values when each value is assigned exactly 24 bits. * * @param values values to encode and store. * @param bytes array in which encoded bits will be written. */ private void encode32Bits(double values[], byte[] bytes) { int i = 0; for (double value : values) { long encodedValue = encodeValue(value); bytes[i] = (byte) (encodedValue >>> 24L); bytes[i + 1] = (byte) ((encodedValue >>> 16L) & BYTE_MASK); bytes[i + 2] = (byte) ((encodedValue >>> 8L) & BYTE_MASK); bytes[i + 3] = (byte) (encodedValue & BYTE_MASK); i += 4; } } @Override public double[] decode(byte[] bytes) { int numOfValues = (int) Math.floor((bytes.length * 8.0) / bitsPerValue); double[] output = new double[numOfValues]; if (bitsPerValue == 8) { decode8Bits(output, bytes); } else if (bitsPerValue < 16) { decode9To15Bits(output, bytes); } else if (bitsPerValue == 16) { decode16Bits(output, bytes); } else if (bitsPerValue < 24) { decode17To23Bits(output, bytes); } else if (bitsPerValue == 24) { decode24Bits(output, bytes); } else if (bitsPerValue < 32) { decode25To31Bits(output, bytes); } else { decode32Bits(output, bytes); } return output; } /** * Used to decode stored <code>byte</code>s into values when each value is assigned exactly 8 bits. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode8Bits(double[] values, byte[] bytes) { for (int i = 0; i < values.length; i++) { values[i] = decodeValue(bytes[i]); } } /** * Used to decode stored <code>byte</code>s into values when each value is between 9 and 15 bits, inclusive. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode9To15Bits(double[] values, byte[] bytes) { int j = 0; int bitPosition = 0; for (int i = 0; i < values.length; i++) { int rot = bitsPerValue - 8; int oldBitPosition = bitPosition; long temp = (bytes[j] << bitPosition) & BYTE_MASK; long valueBits = 0L; bitPosition = (rot + bitPosition) % 8; valueBits |= temp << rot; rot = 8 - rot - oldBitPosition; valueBits |= bytes[j + 1] >>> rot; values[i] = decodeValue(valueBits); j++; } } /** * Used to decode stored <code>byte</code>s into values when each value is assigned exactly 16 bits. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode16Bits(double[] values, byte[] bytes) { int j = 0; for (int i = 0; i < values.length; i++) { values[i] = decodeValue((bytes[j] << 8) & bytes[j + 1]); j += 2; } } /** * Used to decode stored <code>byte</code>s into values when each value is between 17 and 23 bits, inclusive. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode17To23Bits(double[] values, byte[] bytes) { int j = 0; int bitPosition = 0; for (int i = 0; i < values.length; i++) { int rot = bitsPerValue - 8; int oldBitPosition = bitPosition; long temp = (bytes[j] << bitPosition) & BYTE_MASK; long valueBits = 0L; bitPosition = (rot + bitPosition) % 8; valueBits |= temp << rot; rot = bitsPerValue - 16 + oldBitPosition; valueBits |= bytes[j + 1] << rot; rot = 8 - rot; valueBits |= bytes[j + 2] >>> rot; values[i] = decodeValue(valueBits); j += 2; } } /** * Used to decode stored <code>byte</code>s into values when each value is assigned exactly 24 bits. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode24Bits(double[] values, byte[] bytes) { int j = 0; for (int i = 0; i < values.length; i++) { values[i] = decodeValue((bytes[j] << 16) & (bytes[j + 1] << 8) & bytes[j + 2]); j += 3; } } /** * Used to decode stored <code>byte</code>s into values when each value is between 25 and 31 bits, inclusive. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode25To31Bits(double[] values, byte[] bytes) { int j = 0; int bitPosition = 0; for (int i = 0; i < values.length; i++) { int rot = bitsPerValue - 8; int oldBitPosition = bitPosition; long temp = (bytes[j] << bitPosition) & BYTE_MASK; long valueBits = 0L; bitPosition = (rot + bitPosition) % 8; valueBits |= temp << rot; rot = bitsPerValue - 24 + oldBitPosition; valueBits |= bytes[j + 1] << rot; rot = bitsPerValue - 16 + oldBitPosition; valueBits |= bytes[j + 2] << rot; rot = 8 - rot; valueBits |= bytes[j + 3] >>> rot; values[i] = decodeValue(valueBits); j += 3; } } /** * Used to decode stored <code>byte</code>s into values when each value is assigned exactly 32 bits. * * @param values in which decoded values will be stored. * @param bytes array to decode. */ private void decode32Bits(double[] values, byte[] bytes) { int j = 0; for (int i = 0; i < values.length; i++) { values[i] = decodeValue((bytes[j] << 24) & (bytes[j + 1] << 16) & (bytes[j + 2] << 8) & (bytes[j + 3])); j += 4; } } /** * Encodes the given <code>double</code> value into the bits which are stored in a <code>long</code> variable. * * @param value value to encode. * @return Bits of the encoded value stored in <code>long</code> variable. */ protected abstract long encodeValue(double value); /** * Decodes the given <code>long</code> value into the <code>double</code> value. * * @param value value to decode. * @return <code>double</code> value which was decoded from the <code>long</code> value. */ protected abstract double decodeValue(long value); }
package il.ac.bgu.cs.bp.bpjs.model.eventselection; import il.ac.bgu.cs.bp.bpjs.model.BSyncStatement; import il.ac.bgu.cs.bp.bpjs.model.BEvent; import il.ac.bgu.cs.bp.bpjs.model.eventsets.ComposableEventSet; import il.ac.bgu.cs.bp.bpjs.model.eventsets.EventSet; import il.ac.bgu.cs.bp.bpjs.model.eventsets.EventSets; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import java.util.List; import java.util.OptionalInt; import java.util.Set; import java.util.stream.Collectors; import static java.util.stream.Collectors.toSet; import org.mozilla.javascript.Context; /** * An event selection strategy that prefers events requested by BSync statements with higher priority. * BSync statement priority is determined by an integer added to the BSync metadata field, like so: * * <code> * bsync({ request:..., waitFor:... }, 2); * </code> * * @author michael */ public class PrioritizedBSyncEventSelectionStrategy extends AbstractEventSelectionStrategy { public PrioritizedBSyncEventSelectionStrategy(long seed) { super(seed); } public PrioritizedBSyncEventSelectionStrategy() { } @Override public Set<BEvent> selectableEvents(Set<BSyncStatement> statements, List<BEvent> externalEvents) { EventSet blocked = ComposableEventSet.anyOf(statements.stream() .filter( stmt -> stmt!=null ) .map( BSyncStatement::getBlock ) .filter( r -> r != EventSets.none ) .collect( Collectors.toSet() ) ); OptionalInt maxValueOpt = statements.stream() .filter( s -> !getRequestedAndNotBlocked(s, blocked).isEmpty() ) .mapToInt(this::getValue) .max(); try { Context.enter(); if ( maxValueOpt.isPresent() ) { int maxValue = maxValueOpt.getAsInt(); return statements.stream().filter( s -> getValue(s) == maxValue ) .flatMap( s -> getRequestedAndNotBlocked(s, blocked).stream() ) .collect( toSet() ); } else { // Can't select any internal event, defer to the external, non-blocked ones. return externalEvents.stream().filter( e->!blocked.contains(e) ) // No internal events requested, defer to externals. .findFirst().map( e->singleton(e) ).orElse(emptySet()); } } finally { Context.exit(); } } private int getValue( BSyncStatement stmt ) { return (stmt.hasData() && (stmt.getData() instanceof Number))? ((Number)stmt.getData()).intValue() : Integer.MIN_VALUE; } }
package hudson.model; import antlr.ANTLRException; import static hudson.Util.fixNull; import hudson.model.labels.LabelAtom; import hudson.model.labels.LabelExpression; import hudson.model.labels.LabelExpression.And; import hudson.model.labels.LabelExpression.Binary; import hudson.model.labels.LabelExpression.Iff; import hudson.model.labels.LabelExpression.Implies; import hudson.model.labels.LabelExpression.Not; import hudson.model.labels.LabelExpression.Or; import hudson.model.labels.LabelExpression.Paren; import hudson.model.labels.LabelExpressionLexer; import hudson.model.labels.LabelExpressionParser; import hudson.model.labels.LabelOperatorPrecedence; import hudson.model.labels.LabelVisitor; import hudson.slaves.NodeProvisioner; import hudson.slaves.Cloud; import hudson.util.QuotedStringTokenizer; import hudson.util.VariableResolver; import jenkins.model.Jenkins; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Collection; import java.util.TreeSet; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.HierarchicalStreamReader; /** * Group of {@link Node}s. * * @author Kohsuke Kawaguchi * @see Jenkins#getLabels() * @see Jenkins#getLabel(String) */ @ExportedBean public abstract class Label extends Actionable implements Comparable<Label>, ModelObject { /** * Display name of this label. */ protected transient final String name; private transient volatile Set<Node> nodes; private transient volatile Set<Cloud> clouds; @Exported public transient final LoadStatistics loadStatistics; public transient final NodeProvisioner nodeProvisioner; public Label(String name) { this.name = name; // passing these causes an infinite loop - getTotalExecutors(),getBusyExecutors()); this.loadStatistics = new LoadStatistics(0,0) { @Override public int computeIdleExecutors() { return Label.this.getIdleExecutors(); } @Override public int computeTotalExecutors() { return Label.this.getTotalExecutors(); } @Override public int computeQueueLength() { return Jenkins.getInstance().getQueue().countBuildableItemsFor(Label.this); } }; this.nodeProvisioner = new NodeProvisioner(this, loadStatistics); } /** * Alias for {@link #getDisplayName()}. */ @Exported public final String getName() { return getDisplayName(); } /** * Returns a human-readable text that represents this label. */ public String getDisplayName() { return name; } /** * Returns a label expression that represents this label. */ public abstract String getExpression(); /** * Relative URL from the context path, that ends with '/'. */ public String getUrl() { return "label/"+name+'/'; } public String getSearchUrl() { return getUrl(); } /** * Evaluates whether the label expression is true given the specified value assignment. * IOW, returns true if the assignment provided by the resolver matches this label expression. */ public abstract boolean matches(VariableResolver<Boolean> resolver); /** * Evaluates whether the label expression is true when an entity owns the given set of * {@link LabelAtom}s. */ public final boolean matches(final Collection<LabelAtom> labels) { return matches(new VariableResolver<Boolean>() { public Boolean resolve(String name) { for (LabelAtom a : labels) if (a.getName().equals(name)) return true; return false; } }); } public final boolean matches(Node n) { return matches(n.getAssignedLabels()); } /** * Returns true if this label is a "self label", * which means the label is the name of a {@link Node}. */ public boolean isSelfLabel() { Set<Node> nodes = getNodes(); return nodes.size() == 1 && nodes.iterator().next().getSelfLabel() == this; } /** * Gets all {@link Node}s that belong to this label. */ @Exported public Set<Node> getNodes() { Set<Node> nodes = this.nodes; if(nodes!=null) return nodes; Set<Node> r = new HashSet<Node>(); Jenkins h = Jenkins.getInstance(); if(this.matches(h)) r.add(h); for (Node n : h.getNodes()) { if(this.matches(n)) r.add(n); } return this.nodes = Collections.unmodifiableSet(r); } /** * Gets all {@link Cloud}s that can launch for this label. */ @Exported public Set<Cloud> getClouds() { if(clouds==null) { Set<Cloud> r = new HashSet<Cloud>(); Jenkins h = Jenkins.getInstance(); for (Cloud c : h.clouds) { if(c.canProvision(this)) r.add(c); } clouds = Collections.unmodifiableSet(r); } return clouds; } /** * Can jobs be assigned to this label? * <p> * The answer is yes if there is a reasonable basis to believe that Hudson can have * an executor under this label, given the current configuration. This includes * situations such as (1) there are offline slaves that have this label (2) clouds exist * that can provision slaves that have this label. */ public boolean isAssignable() { for (Node n : getNodes()) if(n.getNumExecutors()>0) return true; return !getClouds().isEmpty(); } /** * Number of total {@link Executor}s that belong to this label. * <p> * This includes executors that belong to offline nodes, so the result * can be thought of as a potential capacity, whereas {@link #getTotalExecutors()} * is the currently functioning total number of executors. * <p> * This method doesn't take the dynamically allocatable nodes (via {@link Cloud}) * into account. If you just want to test if there's some executors, use {@link #isAssignable()}. */ public int getTotalConfiguredExecutors() { int r=0; for (Node n : getNodes()) r += n.getNumExecutors(); return r; } /** * Number of total {@link Executor}s that belong to this label that are functioning. * <p> * This excludes executors that belong to offline nodes. */ @Exported public int getTotalExecutors() { int r=0; for (Node n : getNodes()) { Computer c = n.toComputer(); if(c!=null && c.isOnline()) r += c.countExecutors(); } return r; } /** * Number of busy {@link Executor}s that are carrying out some work right now. */ @Exported public int getBusyExecutors() { int r=0; for (Node n : getNodes()) { Computer c = n.toComputer(); if(c!=null && c.isOnline()) r += c.countBusy(); } return r; } /** * Number of idle {@link Executor}s that can start working immediately. */ @Exported public int getIdleExecutors() { int r=0; for (Node n : getNodes()) { Computer c = n.toComputer(); if(c!=null && (c.isOnline() || c.isConnecting()) && c.isAcceptingTasks()) r += c.countIdle(); } return r; } /** * Returns true if all the nodes of this label is offline. */ @Exported public boolean isOffline() { for (Node n : getNodes()) { Computer c = n.toComputer(); if(c != null && !c.isOffline()) return false; } return true; } /** * Returns a human readable text that explains this label. */ @Exported public String getDescription() { Set<Node> nodes = getNodes(); if(nodes.isEmpty()) { Set<Cloud> clouds = getClouds(); if(clouds.isEmpty()) return Messages.Label_InvalidLabel(); return Messages.Label_ProvisionedFrom(toString(clouds)); } if(nodes.size()==1) return nodes.iterator().next().getNodeDescription(); return Messages.Label_GroupOf(toString(nodes)); } private String toString(Collection<? extends ModelObject> model) { boolean first=true; StringBuilder buf = new StringBuilder(); for (ModelObject c : model) { if(buf.length()>80) { buf.append(",..."); break; } if(!first) buf.append(','); else first=false; buf.append(c.getDisplayName()); } return buf.toString(); } /** * Returns projects that are tied on this node. */ @Exported public List<AbstractProject> getTiedJobs() { List<AbstractProject> r = new ArrayList<AbstractProject>(); for (AbstractProject<?,?> p : Jenkins.getInstance().getItems(AbstractProject.class)) { if(this.equals(p.getAssignedLabel())) r.add(p); } return r; } public boolean contains(Node node) { return getNodes().contains(node); } /** * If there's no such label defined in {@link Node} or {@link Cloud}. * This is usually used as a signal that this label is invalid. */ public boolean isEmpty() { return getNodes().isEmpty() && getClouds().isEmpty(); } /*package*/ void reset() { nodes = null; clouds = null; } /** * Expose this object to the remote API. */ public Api getApi() { return new Api(this); } /** * Accepts a visitor and call its respective "onXYZ" method based no the actual type of 'this'. */ public abstract <V,P> V accept(LabelVisitor<V,P> visitor, P param); /** * Lists up all the atoms contained in in this label. * * @since 1.420 */ public Set<LabelAtom> listAtoms() { Set<LabelAtom> r = new HashSet<LabelAtom>(); accept(ATOM_COLLECTOR,r); return r; } /** * Returns the label that represents "this&amp;rhs" */ public Label and(Label rhs) { return new LabelExpression.And(this,rhs); } /** * Returns the label that represents "this|rhs" */ public Label or(Label rhs) { return new LabelExpression.Or(this,rhs); } /** * Returns the label that represents "this&lt;->rhs" */ public Label iff(Label rhs) { return new LabelExpression.Iff(this,rhs); } /** * Returns the label that represents "this->rhs" */ public Label implies(Label rhs) { return new LabelExpression.Implies(this,rhs); } /** * Returns the label that represents "!this" */ public Label not() { return new LabelExpression.Not(this); } /** * Returns the label that represents "(this)" * This is a pointless operation for machines, but useful * for humans who find the additional parenthesis often useful */ public Label paren() { return new LabelExpression.Paren(this); } /** * Precedence of the top most operator. */ public abstract LabelOperatorPrecedence precedence(); @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; return name.equals(((Label)that).name); } @Override public int hashCode() { return name.hashCode(); } public int compareTo(Label that) { return this.name.compareTo(that.name); } @Override public String toString() { return name; } public static final class ConverterImpl implements Converter { public ConverterImpl() { } public boolean canConvert(Class type) { return Label.class.isAssignableFrom(type); } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { Label src = (Label) source; writer.setValue(src.getExpression()); } public Object unmarshal(HierarchicalStreamReader reader, final UnmarshallingContext context) { return Jenkins.getInstance().getLabel(reader.getValue()); } } /** * Convers a whitespace-separate list of tokens into a set of {@link Label}s. * * @param labels * Strings like "abc def ghi". Can be empty or null. * @return * Can be empty but never null. A new writable set is always returned, * so that the caller can add more to the set. * @since 1.308 */ public static Set<LabelAtom> parse(String labels) { Set<LabelAtom> r = new TreeSet<LabelAtom>(); labels = fixNull(labels); if(labels.length()>0) for( String l : new QuotedStringTokenizer(labels).toArray()) r.add(Jenkins.getInstance().getLabelAtom(l)); return r; } /** * Obtains a label by its {@linkplain #getName() name}. */ public static Label get(String l) { return Jenkins.getInstance().getLabel(l); } /** * Parses the expression into a label expression tree. * * TODO: replace this with a real parser later */ public static Label parseExpression(String labelExpression) throws ANTLRException { LabelExpressionLexer lexer = new LabelExpressionLexer(new StringReader(labelExpression)); return new LabelExpressionParser(lexer).expr(); } /** * Collects all the atoms in the expression. */ private static final LabelVisitor<Void,Set<LabelAtom>> ATOM_COLLECTOR = new LabelVisitor<Void,Set<LabelAtom>>() { @Override public Void onAtom(LabelAtom a, Set<LabelAtom> param) { param.add(a); return null; } @Override public Void onParen(Paren p, Set<LabelAtom> param) { return p.base.accept(this,param); } @Override public Void onNot(Not p, Set<LabelAtom> param) { return p.base.accept(this,param); } @Override public Void onAnd(And p, Set<LabelAtom> param) { return onBinary(p,param); } @Override public Void onOr(Or p, Set<LabelAtom> param) { return onBinary(p,param); } @Override public Void onIff(Iff p, Set<LabelAtom> param) { return onBinary(p,param); } @Override public Void onImplies(Implies p, Set<LabelAtom> param) { return onBinary(p,param); } private Void onBinary(Binary b, Set<LabelAtom> param) { b.lhs.accept(this,param); b.rhs.accept(this,param); return null; } }; }
/** * IdealRfCavity.java * * Author : Christopher K. Allen * Since : Dec 3, 2014 */ package xal.model.elem; import java.util.Iterator; import xal.model.IComponent; import xal.model.IProbe; import xal.model.ModelException; import xal.model.elem.sync.IRfCavity; import xal.model.elem.sync.IRfCavityCell; import xal.model.elem.sync.IRfGap; import xal.sim.scenario.LatticeElement; import xal.smf.AcceleratorNode; import xal.smf.impl.RfCavity; /** * <p> * This class represents a general RF cavity being an composition of * RF gaps and cavity drifts. The types and parameters of the internal * elements define the operation (and configuration) of the cavity. * </p> * <p> * The propagation is done via the base class <code>ElementSeq</code> which * just runs through the child elements propagating (or back propagating) * in order. Thus, currently at least, this element is really just a * container of elements. * </p> * * @author Christopher K. Allen * @since Dec 3, 2014 */ public class IdealRfCavity extends ElementSeq implements IRfCavity { /* * Global Constants */ /** the string type identifier for all Sector objects */ public static final String STR_TYPEID = "RfCavity"; /* * Local Attributes */ /** The current operating phase with respect to the arriving particle (in radians) */ private double dblPhase; /** The amplitude of the RF signal at the cavity RF window, i.e., the klystron amplitude (in Volts) */ private double dblAmp; /** The frequency of the enclosing cavity (in Hertz) */ private double dblFreq; /** The mode constant (1/2 the mode number) of the cavity which we are exciting */ private double dblModeConst; /* * Initialization */ /** * Zero constructor for <code>IdealRfCavity</code>. * * @param strType * * @author Christopher K. Allen * @since Dec 3, 2014 */ public IdealRfCavity() { super(STR_TYPEID); } /** * Constructor for <code>IdealRfCavity</code> with string identifier. * * @param strId string identifier for the RF cavity * * @author Christopher K. Allen * @since Dec 3, 2014 */ public IdealRfCavity(String strId) { super(STR_TYPEID, strId); } /** * Constructor for IdealRfCavity. * * @param strId string identifier for the RF cavity * @param szReserve number of initial element positions to allocate * (marginally increases performance, maybe) * * @author Christopher K. Allen * @since Dec 3, 2014 */ public IdealRfCavity(String strId, int szReserve) { super(STR_TYPEID, strId, szReserve); } /** * <p> * Set the operating mode constant &lambda; for the RF cavity design. The constant * is half of the mode number <i>q</i>. Specifically, * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 0 &nbsp; (<i>q</i>=0) &rArr; 0 mode cavity structure (e.g. DTL) * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 1/2 (<i>q</i>=1) &rArr; &pi;/2 mode structure (bi-periodic structures, e.g., SideCC) * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 1 &nbsp; (<i>q</i>=2) &rArr; &pi;-mode cavity (e.g. CCL, super-conducting) * </p> * * @param dblModeConst the new mode constant &lambda; for the cavity drift */ public void setCavityModeConstant(double dblModeConst) { this.dblModeConst = dblModeConst; } /* * Attribute Query */ /** * <p> * Get the operating mode constant &lambda; for the RF cavity design. The constant * is half of the mode number <i>q</i>. Specifically, * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 0 &nbsp; (<i>q</i>=0) &rArr; 0 mode cavity structure (e.g. DTL) * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 1/2 (<i>q</i>=1) &rArr; &pi;/2 mode structure (bi-periodic structures, e.g., SideCC) * <br/> * <br/> * &nbsp; &nbsp; &lambda; = 1 &nbsp; (<i>q</i>=2) &rArr; &pi;-mode cavity (e.g. CCL, super-conducting) * </p> * * @return the operating mode constant &lambda; for the cavity drift */ public double getCavityModeConstant() { return this.dblModeConst; } /* * IRfCavity Interface */ /** * Get the operating frequency of the RF cavity in Hertz. * * @return the fundamental mode frequency <i>f</i><sub>0</sub> of the RF cavity */ @Override public double getCavFrequency() { return this.dblFreq; } /** * Get the amplitude of the RF signal feeding the cavity. Specifically, * the voltage of the RF at the cavity RF window. * * @return high-power signal level at the cavity (in Volts) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public double getCavAmp() { return this.dblAmp; } /** * Get the RF phase of the cavity with respect to the propagating probe. * Specifically, this is the RF phase seen by the probe as it first enters * the cavity. * * @return RF phase of the cavity upon probe arrival (in radians) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public double getCavPhase() { return this.dblPhase; } /** * Set the operating frequency of the RF cavity in Hertz. * * @param dblFreq fundamental RF frequency of the RF cavity (in Hertz) */ @Override public void setCavFrequency(double dblFreq) { this.dblFreq = dblFreq; } /** * Sets the amplitude of the RF signal feeding the cavity. Specifically, * the voltage of the RF at the cavity RF window. * * @param dblAmp high-power signal level at the cavity (in Volts) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public void setCavAmp(double dblAmp) { this.dblAmp = dblAmp; } /** * Sets the RF phase of the cavity with respect to the propagating probe. * Specifically, this is the RF phase seen by the probe as it first enters * the cavity. * * @param dblPhase RF phase of the cavity upon probe arrival (in radians) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public void setCavPhase(double dblPhase) { this.dblPhase = dblPhase; } /* * IComposite Interface */ /** * Initializes the frequency and cavity mode constant from the given proxy * element. The SMF node is taken from the proxy then queried directly. * Eh, I don't like this. * * @see xal.model.elem.ElementSeq#initializeFrom(xal.sim.scenario.LatticeElement) * * @since Dec 5, 2014 @author Christopher K. Allen */ @Override public void initializeFrom(LatticeElement latticeElement) { super.initializeFrom(latticeElement); AcceleratorNode smfNode = latticeElement.getHardwareNode(); // If this the underlying node is not an RF Cavity there is nothing we can do if ( !(smfNode instanceof RfCavity) ) return; RfCavity smfRfCav = (RfCavity)smfNode; double dblFreq = 1.0e6 * smfRfCav.getCavFreq(); // convert to Hertz double dblAmp = 1.0e3 * smfRfCav.getDfltCavAmp(); // convert to Volts double dblPhase = (Math.PI/180.0) * smfRfCav.getDfltCavPhase(); // convert to radians double dblModeConst = smfRfCav.getStructureMode(); this.setCavFrequency( dblFreq ); this.setCavAmp( dblAmp ); this.setCavPhase( dblPhase ); this.setCavityModeConstant( dblModeConst ); } /** * <p> * Sets the probes longitudinal phase to the phase of this cavity * upon entrance. Then we propagate the probe through the * composite structure as usual by calling the base class * <code>propagate</code> method. * </p> * <p> * It is unnecessary to override the <code>{@link #propagate(IProbe, double)}</code> * method since that method simply defers to the * <code>{@link #propagate(IProbe)}</code> method ignoring the * position parameter. * </p> * * @see xal.model.elem.ElementSeq#propagate(xal.model.IProbe) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public void propagate(IProbe probe) throws ModelException { // This is the non-preferred way to do things - modeling elements // should not modify probes. But right now I need to get my foot // into this RF cavity door. // TODO : modify this to conform to the Element/Algorithm/Probe design // probe.setLongitudinalPhase( this.getPhase() ); // This action is okay - it distributes parameters to the child // modeling ELEMENTS of this cavity. We are not acting on the // probe component. this.distributeCavityProperties(); this.distributeCellIndices(); // Now we propagate the probe through this composite modeling element // as usual. super.propagate(probe); } /** * <p> * I am overriding this method even though a proper back propagation * <b>is impossible</b>. We set the longitudinal phase of the probe to the * phase of the cavity as it backs into the exit. The true phase * should be the phase of the particle as it leaves the cavity when * forward propagating, however, we have no way of knowing that * phase a priori. * </p> * <p> * It may be useful to use this setup during back propagations to * explore various beam exit times and their effect. * </p> * <p> * It is unnecessary to override the * <code>{@link #backPropagate(IProbe, double)}</code> * method since that method simply defers to the * <code>{@link #backPropagate(IProbe)}</code> method ignoring the * position parameter. * </p> * * @see xal.model.elem.ElementSeq#backPropagate(xal.model.IProbe) * * @since Dec 16, 2014 by Christopher K. Allen */ @Override public void backPropagate(IProbe probe) throws ModelException { probe.setLongitudinalPhase( this.getCavPhase() ); this.distributeCavityProperties(); this.distributeCellIndices(); super.backPropagate(probe); } /* * Support Methods */ /** * Iterate through each direct child modeling element and check if it * exposes the <code>IRfCavityCell</code> interface. If so, then * it is an accelerating cell within this cavity and we need to set * its index within the cavity and the cavity structure mode * constant for the cell. Together these parameters allow the cavity * cell to adjust its field spatially in order to account for its position * in the cavity and the operating mode field structure. * * @since Jan 9, 2015 by Christopher K. Allen */ private void distributeCavityProperties() { // Initialize the loop Iterator<IComponent> iterCmps = super.localIterator(); while ( iterCmps.hasNext() ) { IComponent cmp = iterCmps.next(); // The child component is a cavity cell if (cmp instanceof IRfCavityCell) { IRfCavityCell mdlCavCell = (IRfCavityCell)cmp; mdlCavCell.setCavityModeConstant( this.getCavityModeConstant() ); } // The child component is the first RF gap // if (cmp instanceof IRfGap) { // IRfGap mdlCavGap = (IRfGap)cmp; // if (mdlCavGap.isFirstGap()) // mdlCavGap.setPhase( this.getCavPhase() ); // The child component is a drift space within an RF cavity if (cmp instanceof IdealRfCavityDrift) { IdealRfCavityDrift mdlCavDrift = (IdealRfCavityDrift)cmp; mdlCavDrift.setFrequency( this.getCavFrequency() ); mdlCavDrift.setCavityModeConstant( this.getCavityModeConstant() ); } } } /** * Compute the indices of the component cavity cells and distribute the values * across all the children. The indices are computed according to the cell order, * its position within a cell bank (e.g., and end cell), and its position within * the entire cavity (e.g., the first cell). * * @since Jan 23, 2015 by Christopher K. Allen */ private void distributeCellIndices() { boolean bolInCellBank = false; int indCell = 0; Iterator<IComponent> iterCmps = super.localIterator(); String lastNodeId = null; while ( iterCmps.hasNext() ) { IComponent cmp = iterCmps.next(); // If the child component is not a cavity cell skip it if (!(cmp instanceof IRfCavityCell) ) continue; IRfCavityCell mdlCavCell = (IRfCavityCell)cmp; if (lastNodeId != null && lastNodeId.equals(cmp.getHardwareNodeId())) continue; else lastNodeId = cmp.getHardwareNodeId(); // SET THE CELL INDEX mdlCavCell.setCavityCellIndex( indCell ); // Compute next index // We are at either end of a bank of cavity cells if (mdlCavCell.isEndCell()) // We've hit the last cell in a cell bank if (bolInCellBank) { indCell += 2; // the cell banks remain in phase bolInCellBank = false; // We've hit the first cell in a cell bank } else { indCell++; bolInCellBank = true; } // We are in the middle of a cell bank else indCell++; } } }
package info.ata4.util.io.lzma; import info.ata4.io.buffer.ByteBufferInputStream; import info.ata4.io.buffer.ByteBufferOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import lzma.LzmaDecoder; import lzma.LzmaEncoder; /** * LZMA byte buffer utility class. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class LzmaBufferUtils { private LzmaBufferUtils() { } public static ByteBuffer decode(ByteBuffer bb) throws IOException { ByteBuffer bbc = bb.duplicate(); bbc.order(ByteOrder.LITTLE_ENDIAN); byte[] lzmaProps = new byte[5]; bbc.get(lzmaProps); long lzmaSize = bbc.getLong(); if (lzmaSize < 0) { throw new IOException("Invalid LZMA size"); } else if (lzmaSize > Integer.MAX_VALUE) { throw new IOException("Uncompressed LZMA buffer is too large for byte buffers"); } ByteBuffer bbu = ByteBuffer.allocateDirect((int) lzmaSize); LzmaDecoder dec = new LzmaDecoder(); if (!dec.setDecoderProperties(lzmaProps)) { throw new IOException("Invalid LZMA props"); } InputStream is = new ByteBufferInputStream(bbc); OutputStream os = new ByteBufferOutputStream(bbu); if (!dec.code(is, os, lzmaSize)) { throw new IOException("LZMA decoding error"); } bbu.flip(); bbu.order(bb.order()); return bbu; } public static ByteBuffer encode(ByteBuffer bb, int lc, int lp, int pb, int dictSize) throws IOException { ByteBuffer bbu = bb.duplicate(); ByteBuffer bbc = ByteBuffer.allocateDirect(bbu.limit() + 13); bbc.order(ByteOrder.LITTLE_ENDIAN); LzmaEncoder enc = new LzmaEncoder(); if (!enc.setLcLpPb(lc, lp, pb)) { throw new IOException("Invalid LZMA props"); } if (!enc.setDictionarySize(dictSize)) { throw new IOException("Invalid dictionary size"); } enc.setEndMarkerMode(true); bbc.put(enc.getCoderProperties()); bbc.putLong(bbu.limit()); InputStream is = new ByteBufferInputStream(bbu); OutputStream os = new ByteBufferOutputStream(bbc); enc.code(is, os); bbc.flip(); bbc.order(bb.order()); return bbc; } public static ByteBuffer encode(ByteBuffer bb) throws IOException { return encode(bb, 3, 0, 2, 1 << 19); } }
package com.passel.data; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Value; /** * Used instead of Android's location class for efficiency. * We make a lot of these and send them all over so we want less overhead. * Also, we'll probably add some of those features back but make them optional. */ @Value public final class Location implements Parcelable { public static final Parcelable.Creator<Location> CREATOR = new Parcelable.Creator<Location>() { public Location createFromParcel(Parcel in) { final double latitude = in.readDouble(); final double longitude = in.readDouble(); return new Location(latitude, longitude); } @Override public Location[] newArray(final int size) { return new Location[size]; } }; double latitude; double longitude; @JsonCreator public Location(@JsonProperty("latitude") final double latitude, @JsonProperty("longitude") final double longitude) { if (Math.abs(latitude) > 90 || Math.abs(longitude) > 90) { throw new IllegalArgumentException(String.format( "(%f, %f) is out of earthly bounds", latitude, longitude)); } this.latitude = latitude; this.longitude = longitude; } public Location(final android.location.Location location) { this.latitude = location.getLatitude(); this.longitude = location.getLongitude(); } @Override public String toString() { return Double.toString(latitude) + "," + Double.toString(longitude); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeDouble(latitude); dest.writeDouble(longitude); } }
package org.wikipedia.util.log; import android.util.Log; import androidx.annotation.NonNull; import org.wikipedia.WikipediaApp; import org.wikipedia.util.ReleaseUtil; /** Logging utility like {@link Log} but with implied tags. */ public final class L { private static final LogLevel LEVEL_V = new LogLevel() { @Override public void logLevel(String tag, String msg, Throwable t) { Log.v(tag, msg, t); } }; private static final LogLevel LEVEL_D = new LogLevel() { @Override public void logLevel(String tag, String msg, Throwable t) { Log.d(tag, msg, t); } }; private static final LogLevel LEVEL_I = new LogLevel() { @Override public void logLevel(String tag, String msg, Throwable t) { Log.i(tag, msg, t); } }; private static final LogLevel LEVEL_W = new LogLevel() { @Override public void logLevel(String tag, String msg, Throwable t) { Log.w(tag, msg, t); } }; private static final LogLevel LEVEL_E = new LogLevel() { @Override public void logLevel(String tag, String msg, Throwable t) { Log.e(tag, msg, t); } }; public static void v(CharSequence msg) { LEVEL_V.log(msg, null); } public static void d(CharSequence msg) { LEVEL_D.log(msg, null); } public static void i(CharSequence msg) { LEVEL_I.log(msg, null); } public static void w(CharSequence msg) { LEVEL_W.log(msg, null); } public static void e(CharSequence msg) { LEVEL_E.log(msg, null); } public static void v(Throwable t) { LEVEL_V.log("", t); } public static void d(Throwable t) { LEVEL_D.log("", t); } public static void i(Throwable t) { LEVEL_I.log("", t); } public static void w(Throwable t) { LEVEL_W.log("", t); } public static void e(Throwable t) { LEVEL_E.log("", t); } public static void v(CharSequence msg, Throwable t) { LEVEL_V.log(msg, t); } public static void d(CharSequence msg, Throwable t) { LEVEL_D.log(msg, t); } public static void i(CharSequence msg, Throwable t) { LEVEL_I.log(msg, t); } public static void w(CharSequence msg, Throwable t) { LEVEL_W.log(msg, t); } public static void e(CharSequence msg, Throwable t) { LEVEL_E.log(msg, t); } public static void logRemoteErrorIfProd(@NonNull Throwable t) { if (ReleaseUtil.isProdRelease()) { logRemoteError(t); } else { throw new RuntimeException(t); } } // Favor logRemoteErrorIfProd(). If it's worth consuming bandwidth and developer hours, it's // worth crashing on everything but prod public static void logRemoteError(@NonNull Throwable t) { LEVEL_E.log("", t); if (!ReleaseUtil.isPreBetaRelease()) { WikipediaApp.getInstance().logCrashManually(t); } } private abstract static class LogLevel { private static final int STACK_INDEX = 4; public abstract void logLevel(String tag, String msg, Throwable t); public final void log(CharSequence msg, Throwable t) { StackTraceElement element = Thread.currentThread().getStackTrace()[STACK_INDEX]; logLevel(element.getClassName(), stackTraceElementToMessagePrefix(element) + msg, t); } private String stackTraceElementToMessagePrefix(StackTraceElement element) { return element.getMethodName() + "():" + element.getLineNumber() + ": "; } } private L() { } }
package de.dakror.vloxlands; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.FPSLogger; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.math.Vector3; import de.dakror.vloxlands.game.voxel.Voxel; import de.dakror.vloxlands.game.world.Chunk; import de.dakror.vloxlands.game.world.World; public class Vloxlands extends ApplicationAdapter { public static Vloxlands currentGame; public PerspectiveCamera camera; World world; ModelBatch modelBatch; Environment lights; CameraInputController controller; FPSLogger logger; long last; Vector3 worldMiddle; @Override public void create() { currentGame = this; Voxel.loadVoxels(); modelBatch = new ModelBatch(); DefaultShader.defaultCullFace = GL20.GL_FRONT; camera = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.near = 0.5f; camera.far = 1000; controller = new CameraInputController(camera); Gdx.input.setInputProcessor(controller); lights = new Environment(); lights.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f)); lights.add(new DirectionalLight().set(255, 255, 255, 0, -1, 1)); world = new World(8, 8, 8); worldMiddle = world.size.cpy().scl(0.5f * Chunk.SIZE); camera.position.set(worldMiddle.cpy()); camera.position.y += world.size.y; camera.position.z += 10; camera.rotate(new Vector3(1, 0, 0), -45); logger = new FPSLogger(); controller.target = worldMiddle; controller.translateTarget = false; controller.forwardTarget = false; controller.rotateLeftKey = 0; controller.rotateRightKey = 0; } @Override public void render() { Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); modelBatch.begin(camera); modelBatch.render(world, lights); modelBatch.end(); controller.update(); if (last == 0) last = System.currentTimeMillis(); logger.log(); if (System.currentTimeMillis() - last >= 1000) { Gdx.app.log("Chunks", world.visibleChunks + " / " + world.chunks.length); last = System.currentTimeMillis(); } } }
package io.cloudchaser.murmur; import io.cloudchaser.murmur.parser.MurmurParser; import io.cloudchaser.murmur.parser.MurmurParserBaseVisitor; import io.cloudchaser.murmur.symbol.LetSymbol; import io.cloudchaser.murmur.symbol.Symbol; import io.cloudchaser.murmur.symbol.SymbolContext; import io.cloudchaser.murmur.types.InvokableType; import io.cloudchaser.murmur.types.MurmurArray; import io.cloudchaser.murmur.types.MurmurBoolean; import io.cloudchaser.murmur.types.MurmurCharacter; import io.cloudchaser.murmur.types.MurmurComponent; import io.cloudchaser.murmur.types.MurmurComponent.ComponentField; import io.cloudchaser.murmur.types.MurmurComponent.ComponentFunction; import io.cloudchaser.murmur.types.MurmurDecimal; import io.cloudchaser.murmur.types.MurmurFunction; import io.cloudchaser.murmur.types.MurmurInstance; import io.cloudchaser.murmur.types.MurmurInteger; import io.cloudchaser.murmur.types.MurmurNull; import io.cloudchaser.murmur.types.MurmurObject; import io.cloudchaser.murmur.types.MurmurReturn; import io.cloudchaser.murmur.types.MurmurString; import static io.cloudchaser.murmur.types.MurmurType.TYPE; import io.cloudchaser.murmur.types.MurmurVoid; import io.cloudchaser.murmur.types.ReferenceType; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Mihail K * @since 0.1 */ public class MurmurASTVisitor extends MurmurParserBaseVisitor { private static class MurmurBaseContext implements SymbolContext { private final Map<String, Symbol> symbols; public MurmurBaseContext() { symbols = new HashMap<>(); } @Override public SymbolContext getParent() { return null; } @Override public void addSymbol(Symbol symbol) { symbols.put(symbol.getName(), symbol); } @Override public Symbol getSymbol(String name) { return symbols.get(name); } @Override public Symbol getLocal(String name) { return symbols.get(name); } } private final Deque<SymbolContext> context; public MurmurASTVisitor() { context = new LinkedList<>(); } /** * Removes symbol binding from a murmur value, if present. * * @param object The object to de-symbolize. * @return A murmur object. */ private static MurmurObject desymbolize(MurmurObject object) { return object instanceof Symbol ? ((Symbol)object).getValue() : object; } @Override public MurmurObject visitCompilationUnit(MurmurParser.CompilationUnitContext ctx) { // Push initial context. context.push(new MurmurBaseContext()); // Visit children. ctx.statement().stream().forEach(this::visitStatement); // Pop initial context. context.pop(); return null; } @Override public MurmurObject visitStatement(MurmurParser.StatementContext ctx) { if(ctx.keywordStatement() != null) { return visitKeywordStatement(ctx.keywordStatement()); } else if(ctx.typeStatement() != null) { return visitTypeStatement(ctx.typeStatement()); } else { // Print results for debug. System.out.println(visitExpression(ctx.expression())); } return null; } /* - Statements - */ public MurmurObject visitLeftArrowStatement(MurmurParser.KeywordStatementContext ctx) { // Get the current instance context. Symbol symbol = context.peek().getSymbol("this"); MurmurInstance instance = (MurmurInstance)symbol.getValue(); ctx.identifierList().Identifier() .stream().forEach((identifier) -> { String name = identifier.getText(); MurmurObject target = instance.getMember(name); Symbol source = context.peek().getLocal(name); // Check that the symbol exists. if(source == null || target == null || !(target instanceof Symbol)) { throw new NullPointerException(); } // Bind the symbol, by name. ((Symbol)target).setValue(source.getValue()); }); // Return void value. return MurmurVoid.VOID; } public MurmurObject visitRightArrowStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitBreakStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitContinueStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } public MurmurObject visitLetInitializerList(MurmurParser.InitializerListContext ctx) { ctx.initializerElement().stream().forEach((element) -> { String name = element.Identifier().getText(); MurmurObject value = visitExpression(element.expression()); // Create a symbol entry. context.peek().addSymbol(new LetSymbol(name, value)); }); // Return void value. return MurmurVoid.VOID; } public MurmurObject visitLetStatement(MurmurParser.KeywordStatementContext ctx) { // Let with an initializer list. if(ctx.initializerList() != null) { return visitLetInitializerList(ctx.initializerList()); } // Unsupported. throw new UnsupportedOperationException(); } public MurmurObject visitReturnStatement(MurmurParser.KeywordStatementContext ctx) { // Wrap return value. MurmurObject value = visitExpression(ctx.expression()); return new MurmurReturn(desymbolize(value)); } public MurmurObject visitThrowStatement(MurmurParser.KeywordStatementContext ctx) { // TODO return null; } @Override public MurmurObject visitKeywordStatement(MurmurParser.KeywordStatementContext ctx) { if(ctx.operator != null) { // Keyword/operator. switch(ctx.operator.getText()) { case "<-": return visitLeftArrowStatement(ctx); case "->": return visitRightArrowStatement(ctx); case "break": return visitBreakStatement(ctx); case "continue": return visitContinueStatement(ctx); case "let": return visitLetStatement(ctx); case "return": return visitReturnStatement(ctx); case "throw": return visitThrowStatement(ctx); default: // Unknown operation. throw new UnsupportedOperationException(); } } // Something went wrong. throw new RuntimeException(); } /* - Interfaces - */ public MurmurObject visitITypeFunction(MurmurParser.ITypeElementContext ctx) { // TODO return null; } @Override public MurmurObject visitITypeElement(MurmurParser.ITypeElementContext ctx) { // TODO return null; } /* - Component Types - */ public MurmurComponent.ComponentField visitTypeField(MurmurParser.TypeElementContext ctx) { String name = ctx.name.getText(); // Validate field name. if(name.equals("this")) { throw new UnsupportedOperationException(); } // Create the field. return new ComponentField(name); } public MurmurComponent.ComponentFunction visitTypeFunction(MurmurParser.TypeElementContext ctx) { String name = ctx.name.getText(); MurmurObject value = visitExpression(ctx.expression()); // Adjust names. if(name.equals("this")) { name = "~ctor"; } // Check that this is a function. if(!(value instanceof MurmurFunction)) { throw new UnsupportedOperationException(); } // Create the function. MurmurFunction function = (MurmurFunction)value; return new ComponentFunction(name, function); } @Override public MurmurComponent.ComponentField visitTypeElement(MurmurParser.TypeElementContext ctx) { // Determine the element type. if(ctx.expression() != null) { return visitTypeFunction(ctx); } else { return visitTypeField(ctx); } } @Override public MurmurObject visitTypeDeclaration(MurmurParser.TypeDeclarationContext ctx) { // Create a local component type. MurmurComponent component = new MurmurComponent( "<local>", context.peek()); // Build component members list. if(ctx.typeElement() != null) { ctx.typeElement().stream().forEach((element) -> { MurmurComponent.ComponentField symbol = visitTypeElement(element); component.getMembers().put(symbol.getName(), symbol); }); } // Return the component. return component; } public List<MurmurComponent> visitTypeParents(MurmurParser.TypeStatementContext ctx) { if(ctx.parents == null) return new ArrayList<>(); List<MurmurComponent> types = new ArrayList<>(); ctx.parents.stream().forEach((identifier) -> { // Resolve component type name. Symbol symbol = context.peek().getSymbol(identifier.getText()); // Check that the type exists. if(symbol == null) { throw new NullPointerException(); } // Check that this is a component type. MurmurObject object = symbol.getValue(); if(object.getType() != TYPE) { throw new UnsupportedOperationException(); } // Add it to the list. types.add((MurmurComponent)object); }); return types; } @Override public MurmurObject visitTypeStatement(MurmurParser.TypeStatementContext ctx) { Symbol symbol; String name = ctx.name.getText(); // Visit parent and local types. List<MurmurComponent> types = visitTypeParents(ctx); types.add((MurmurComponent)visitTypeDeclaration(ctx.typeDeclaration())); // Build the finished Murmur component object. MurmurObject component = new MurmurComponent(name, context.peek(), types); context.peek().addSymbol(symbol = new LetSymbol(name, component)); // Return void value. return MurmurVoid.VOID; } /* - Expressions - */ public MurmurObject visitPositiveExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); return right.opPositive(); } public MurmurObject visitPreIncrementExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); // Must be a symbol to increment. if(!(right instanceof Symbol)) { throw new UnsupportedOperationException(); } // Increment and return value. Symbol symbol = (Symbol)right; symbol.setValue(right.opIncrement()); return symbol.getValue(); } public MurmurObject visitPostIncrementExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); // Must be a symbol to increment. if(!(left instanceof Symbol)) { throw new UnsupportedOperationException(); } // Increment and return old value. Symbol symbol = (Symbol)left; MurmurObject old = symbol.getValue(); symbol.setValue(left.opIncrement()); return old; } public MurmurObject visitAdditionExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opPlus(desymbolize(right)); } public MurmurObject visitNegativeExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); return right.opNegative(); } public MurmurObject visitPreDecrementExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); // Must be a symbol to decrement. if(!(right instanceof Symbol)) { throw new UnsupportedOperationException(); } // Decrement and return value. Symbol symbol = (Symbol)right; symbol.setValue(right.opDecrement()); return symbol.getValue(); } public MurmurObject visitPostDecrementExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); // Must be a symbol to decrement. if(!(left instanceof Symbol)) { throw new UnsupportedOperationException(); } // Decrement and return old value. Symbol symbol = (Symbol)left; MurmurObject old = symbol.getValue(); symbol.setValue(left.opDecrement()); return old; } public MurmurObject visitSubtractionExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opMinus(desymbolize(right)); } public MurmurObject visitMultiplicationExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opMultiply(desymbolize(right)); } public MurmurObject visitDivisionExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opDivide(desymbolize(right)); } public MurmurObject visitModuloExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opModulo(desymbolize(right)); } public MurmurObject visitEqualExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opEquals(desymbolize(right)); } public MurmurObject visitNotEqualExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opNotEquals(desymbolize(right)); } public MurmurObject visitLogicalNotExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); return right.opLogicalNot(); } public MurmurObject visitLogicalAndExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opLogicalAnd(desymbolize(right)); } public MurmurObject visitLogicalOrExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opLogicalOr(desymbolize(right)); } public MurmurObject visitBinaryNotExpression(MurmurParser.ExpressionContext ctx) { MurmurObject right = visitExpression(ctx.right); return right.opBitNot(); } public MurmurObject visitBinaryAndExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opBitAnd(desymbolize(right)); } public MurmurObject visitBinaryXorExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opBitXor(desymbolize(right)); } public MurmurObject visitBinaryOrExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opBitOr(desymbolize(right)); } public MurmurObject visitLessThanExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opLessThan(desymbolize(right)); } public MurmurObject visitGreaterThanExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opGreaterThan(desymbolize(right)); } public MurmurObject visitLessOrEqualExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opLessOrEqual(desymbolize(right)); } public MurmurObject visitGreaterOrEqualExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opGreaterOrEqual(desymbolize(right)); } public MurmurObject visitShiftLeftExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opShiftLeft(desymbolize(right)); } public MurmurObject visitShiftRightExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opShiftRight(desymbolize(right)); } public MurmurObject visitTernaryExpression(MurmurParser.ExpressionContext ctx) { MurmurObject clause = desymbolize(visitExpression(ctx.clause)); // Check that the clause is boolean. if(!(clause instanceof MurmurBoolean)) { throw new UnsupportedOperationException(); } // Check the clause. if(((MurmurBoolean)clause).getValue()) { // True; evaluate left. return visitExpression(ctx.expression(1)); } else { // False; evaluate right. return visitExpression(ctx.expression(2)); } } public MurmurObject visitConcatExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Dereference symbols. return left.opConcat(desymbolize(right)); } public MurmurObject visitArrayIndexExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject index = visitExpression(ctx.index); // Dereference symbols. return left.opIndex(desymbolize(index)); } public List<MurmurObject> visitArrayInitializerList(MurmurParser.ExpressionListContext ctx) { if(ctx == null) return new ArrayList<>(); List<MurmurObject> elements = new ArrayList<>(); ctx.expression().stream().forEach((expression) -> elements.add(desymbolize(visitExpression(expression)))); return elements; } public MurmurObject visitArrayValueExpression(MurmurParser.ExpressionContext ctx) { List<MurmurObject> elements = visitArrayInitializerList(ctx.expressionList()); return new MurmurArray(elements); } public List<MurmurObject> visitFunctionArguments(MurmurParser.ExpressionListContext ctx) { if(ctx == null) return null; List<MurmurObject> args = new ArrayList<>(); ctx.expression().stream().forEach((argument) -> args.add(desymbolize(visitExpression(argument)))); return args; } @Override public MurmurObject visitBlock(MurmurParser.BlockContext ctx) { // Execute statements in sequence. for(MurmurParser.StatementContext statement : ctx.statement()) { MurmurObject result = visitStatement(statement); // Check for a return value. if(result instanceof MurmurReturn) { return ((MurmurReturn)result).getValue(); } } // Return void value. return MurmurVoid.VOID; } public MurmurObject visitFunctionCallExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = desymbolize(visitExpression(ctx.left)); List<MurmurObject> args = visitFunctionArguments(ctx.expressionList()); // Check that this is an invokable type. if(!(left instanceof InvokableType)) { throw new UnsupportedOperationException(); } // Invoke and return the result. InvokableType invoke = (InvokableType)left; return invoke.opInvoke((local, body) -> { // Step into the local context. context.push(local); // Execute the function. MurmurObject result = visitBlock(body); // Step out of the context. context.pop(); return result; }, args); } public MurmurObject visitAssignmentExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = visitExpression(ctx.right); // Check that this is an lvalue. if(!(left instanceof Symbol)) { throw new UnsupportedOperationException(); } // Assign the value to the symbol. MurmurObject value = desymbolize(right); ((Symbol)left).setValue(value); return value; } public MurmurObject visitCompoundAssignmentExpression(MurmurParser.ExpressionContext ctx) { MurmurObject left = visitExpression(ctx.left); MurmurObject right = desymbolize(visitExpression(ctx.right)); // Check that this is a reference type. if(!(left instanceof ReferenceType)) { throw new UnsupportedOperationException(); } // Invoke the relevant operator. ReferenceType ref = (ReferenceType)left; switch(ctx.operator.getText()) { case "+=": return ref.opPlusAssign(right); case "-=": return ref.opMinusAssign(right); case "*=": return ref.opMultiplyAssign(right); case "/=": return ref.opDivideAssign(right); case "%=": return ref.opModuloAssign(right); case "&=": return ref.opBitAndAssign(right); case "^=": return ref.opBitXorAssign(right); case "|=": return ref.opBitOrAssign(right); case "<<=": return ref.opShiftLeftAssign(right); case ">>=": return ref.opShiftRightAssign(right); case "~=": return ref.opConcatAssign(right); default: // Unsupported assignment type. throw new UnsupportedOperationException(); } } public MurmurObject visitMemberExpression(MurmurParser.ExpressionContext ctx) { String name = ctx.Identifier().getText(); MurmurObject left = visitExpression(ctx.left); // Find and return the member. return left.getMember(name); } public MurmurObject visitSetNotationExpression(MurmurParser.ExpressionContext ctx) { // TODO return null; } public MurmurObject visitIdentifierExpression(MurmurParser.ExpressionContext ctx) { Symbol symbol = context.peek().getSymbol(ctx.getText()); // Check that the symbol exists. if(symbol == null) { // TODO throw new NullPointerException(); } // Return the symbol. return symbol; } public List<String> visitLambdaParameterList(MurmurParser.IdentifierListContext ctx) { if(ctx == null) return null; List<String> parameters = new ArrayList<>(); ctx.Identifier().stream().forEach((parameter) -> parameters.add(parameter.getText())); return parameters; } @Override public MurmurObject visitLambda(MurmurParser.LambdaContext ctx) { List<String> parameters = visitLambdaParameterList(ctx.identifierList()); return new MurmurFunction(context.peek(), parameters, ctx.block()); } public MurmurObject visitInstantiationExpression(MurmurParser.ExpressionContext ctx) { Symbol symbol = context.peek().getSymbol(ctx.Identifier().getText()); // Check that the symbol exists. if(symbol == null) { // TODO throw new NullPointerException(); } // Check that this is a type. MurmurObject object = symbol.getValue(); if(!(object instanceof MurmurComponent)) { throw new UnsupportedOperationException(); } // Return the type. return object; } @Override public MurmurObject visitExpression(MurmurParser.ExpressionContext ctx) { // Skip null elements. if(ctx == null) return null; // Literals. if(ctx.literal() != null) { return visitLiteral(ctx.literal()); } if(ctx.operator != null) { // Operator types. switch(ctx.operator.getText()) { case ".": // Expression: a.b return visitMemberExpression(ctx); case "..": // Expression: [a .. b] return visitSetNotationExpression(ctx); case "+": if(ctx.left != null) // Expression: a + b return visitAdditionExpression(ctx); // Expression: +a return visitPositiveExpression(ctx); case "-": if(ctx.left != null) // Expression: a - b return visitSubtractionExpression(ctx); // Expression: -a return visitNegativeExpression(ctx); case "*": // Expression: a * b return visitMultiplicationExpression(ctx); case "/": // Expression: a / b return visitDivisionExpression(ctx); case "%": // Expression: a % b return visitModuloExpression(ctx); case "!": // Expression: !a return visitLogicalNotExpression(ctx); case "~": if(ctx.left != null) // Expression: a ~ b return visitConcatExpression(ctx); // Expression: ~a return visitBinaryNotExpression(ctx); case "&": // Expression: a & b return visitBinaryAndExpression(ctx); case "^": // Expression: a ^ b return visitBinaryXorExpression(ctx); case "|": // Expression: a | b return visitBinaryOrExpression(ctx); case "<": // Expression: a < b return visitLessThanExpression(ctx); case ">": // Expression: a > b return visitGreaterThanExpression(ctx); case "=": // Expression: a = b return visitAssignmentExpression(ctx); case "?": // Expression: a ? b : c return visitTernaryExpression(ctx); case "(": // Expression: a(b, c, ...) return visitFunctionCallExpression(ctx); case "[": if(ctx.left != null) // Expression: a[b] return visitArrayIndexExpression(ctx); // Expression: [a, b, c, ...] return visitArrayValueExpression(ctx); case "++": if(ctx.left != null) // Expression: a++ return visitPostIncrementExpression(ctx); // Expression: ++a return visitPreIncrementExpression(ctx); case " if(ctx.left != null) // Expression: a-- return visitPostDecrementExpression(ctx); // Expression: --a return visitPreDecrementExpression(ctx); case "&&": // Expression: a && b return visitLogicalAndExpression(ctx); case "||": // Expression: a || b return visitLogicalOrExpression(ctx); case "==": // Expression: a == b return visitEqualExpression(ctx); case "!=": // Expression: a != b return visitNotEqualExpression(ctx); case "<=": // Expression: a <= b return visitLessOrEqualExpression(ctx); case ">=": // Expression: a >= b return visitGreaterOrEqualExpression(ctx); case "<<": // Expression: a << b return visitShiftLeftExpression(ctx); case ">>": // Expression: a >> b return visitShiftRightExpression(ctx); case "new": // Expression: new a return visitInstantiationExpression(ctx); default: // Expression: a compound b return visitCompoundAssignmentExpression(ctx); } } // Identifier. if(ctx.Identifier() != null) { return visitIdentifierExpression(ctx); } // Lambda. if(ctx.lambda() != null) { return visitLambda(ctx.lambda()); } // Parenthesized. if(ctx.inner != null) { return visitExpression(ctx.inner); } throw new RuntimeException(); } /* - Literal Types - */ public MurmurInteger visitIntegerLiteral(MurmurParser.LiteralContext ctx) { long value; String text = ctx.getText().toLowerCase(); // Check for base. if(text.startsWith("0x")) { // Hexadecimal text = text.replaceAll("(0x|_|l)", ""); value = Long.parseLong(text, 16); } else if(text.startsWith("0b")) { // Binary text = text.replaceAll("(0b|_|l)", ""); value = Long.parseLong(text, 2); } else if(text.startsWith("0")) { // Octal value = Long.parseLong(text, 8); } else { // Decimal text = text.replaceAll("(_|l)", ""); value = Long.parseLong(text); } return MurmurInteger.create(value); } public MurmurObject visitDecimalLiteral(MurmurParser.LiteralContext ctx) { String text = ctx.getText().toLowerCase(); double value = Double.parseDouble(text); return MurmurDecimal.create(value); } public MurmurObject visitBooleanLiteral(MurmurParser.LiteralContext ctx) { return MurmurBoolean.create(Boolean.parseBoolean(ctx.getText())); } public MurmurObject visitCharacterLiteral(MurmurParser.LiteralContext ctx) { Pattern pattern = Pattern.compile("\\'(?:([^\\\\])|(\\\\[bfnrt0\\\\'\"])|(?:\\\\([0-3]?[0-7]?[0-7])))\\'", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(ctx.getText()); // Sanity check. if(!matcher.find()) { throw new RuntimeException(); } String group; if((group = matcher.group(1)) != null) { // Simple character literal. return new MurmurCharacter(group.charAt(0)); } else if((group = matcher.group(2)) != null) { // Simple escape sequence. switch(group.charAt(1)) { case 'b': return new MurmurCharacter('\b'); case 'f': return new MurmurCharacter('\f'); case 'n': return new MurmurCharacter('\n'); case 'r': return new MurmurCharacter('\r'); case 't': return new MurmurCharacter('\t'); case '0': return new MurmurCharacter('\0'); case '\\': return new MurmurCharacter('\\'); case '\'': return new MurmurCharacter('\''); case '"': return new MurmurCharacter('"'); // Invalid character escape sequence. default: return new MurmurCharacter(group.charAt(1)); } } else if((group = matcher.group(3)) != null) { // Octal escape sequence. int value = Integer.parseInt(group, 8); return new MurmurCharacter(value); } else { // Something went wrong. throw new RuntimeException(); } } public MurmurObject visitStringLiteral(MurmurParser.LiteralContext ctx) { // Create a string and trim outer quotes. String value = ctx.getText(); return new MurmurString(value.substring(1, value.length() - 1)); } public MurmurObject visitNullLiteral(MurmurParser.LiteralContext ctx) { // Return the null literal. return MurmurNull.NULL; } @Override public MurmurObject visitLiteral(MurmurParser.LiteralContext ctx) { // Integer literals. if(ctx.IntegerLiteral() != null) { return visitIntegerLiteral(ctx); } // Decimal literals. if(ctx.DecimalLiteral() != null) { return visitDecimalLiteral(ctx); } // Boolean literals. if(ctx.BooleanLiteral() != null) { return visitBooleanLiteral(ctx); } // Character literals. if(ctx.CharacterLiteral() != null) { return visitCharacterLiteral(ctx); } // String literals. if(ctx.StringLiteral() != null) { return visitStringLiteral(ctx); } // Null literals. if(ctx.NullLiteral() != null) { return visitNullLiteral(ctx); } // 'this' literal. if(ctx.getText().equals("this")) { Symbol symbol = context.peek().getSymbol("this"); // Check that there is a 'this' defined. if(symbol == null) { throw new UnsupportedOperationException(); } // Return the symbol. return symbol; } // Unknown literal type. throw new RuntimeException(); } }
package io.miti.beetle.processor; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import io.miti.beetle.cache.DBTypeCache; import io.miti.beetle.cache.UserDBCache; import io.miti.beetle.dbutil.ConnManager; import io.miti.beetle.dbutil.Database; import io.miti.beetle.exporters.CsvDBFileWriter; import io.miti.beetle.exporters.DBFileWriter; import io.miti.beetle.exporters.JsonDBFileWriter; import io.miti.beetle.exporters.MarkdownDBFileWriter; import io.miti.beetle.exporters.SQLDBFileWriter; import io.miti.beetle.exporters.TabDBFileWriter; import io.miti.beetle.exporters.TomlDBFileWriter; import io.miti.beetle.exporters.XmlDBFileWriter; import io.miti.beetle.exporters.YamlDBFileWriter; import io.miti.beetle.model.ContentType; import io.miti.beetle.model.DbType; import io.miti.beetle.model.Session; import io.miti.beetle.model.UserDb; import io.miti.beetle.util.FakeNode; import io.miti.beetle.util.FakeSpecParser; import io.miti.beetle.util.Logger; import io.miti.beetle.util.Utility; public final class DataProcessor { private Session session = null; private int runCount = 1; public DataProcessor() { super(); } public DataProcessor(final Session pSession) { session = pSession; } public void setRunCount(final int nRunCount) { runCount = nRunCount; } public void run() { // Check the session if (session == null) { Logger.error("Error: The session is null or invalid"); return; } // Check for SQL imports if (session.getSourceTypeId() == ContentType.SQL.getId()) { importSQL(); } else if (session.getSourceTypeId() == ContentType.FAKE.getId()) { saveFakeData(); } else { Logger.error("Error: Only SQL imports are supported for now; type = " + session.getSourceTypeId()); } } public void saveFakeData() { final ContentType cType = ContentType.getById(session.getTargetTypeId()); if ((cType != ContentType.JSON) && (cType != ContentType.CSV) && (cType != ContentType.YAML) && (cType != ContentType.TOML) && (cType != ContentType.XML) && (cType != ContentType.SQL_FILE) && (cType != ContentType.MARKDOWN) && (cType != ContentType.TSV) && (cType != ContentType.JAVA)) { Logger.error("Only supported export formats: CSV, JSON, YAML, TOML, XML, SQL, TSV, Markdown, Java"); return; } // Parse the specification in the source name. // It should store the list of column names, their class type, and a pointer to // the function call to generate the fake data for that column final FakeSpecParser spec = new FakeSpecParser(); if (!spec.parse(session.getSourceName())) { Logger.error("Invalid specification for fake data"); return; } if (cType == ContentType.JAVA) { writeJavaClass(spec); } else { // Configure the data target final DBFileWriter writer = getFileWriter(cType, session.getTargetName(), session.getTargetData(), spec); // Write the header writer.writeHeader(); // Iterate over the data for exporting for (int i = 0; i < runCount; ++i) { // Write out the data writer.writeObject(spec); } // Write the footer writer.writeFooter(); // Force out any pending data writer.writeString(true); } } /** * Generate a Java class based on a fake data spec. * * @param spec the fake spec */ private void writeJavaClass(final FakeSpecParser spec) { generateJavaClass(new File("."), session.getTargetData(), session.getTargetName(), spec.getNodes(), session.getTargetName()); } /** * Generate a Java class for a database table. */ private void writeJavaClassFromSQL() { // Generate the class name final String className = Utility.toTitleCaseWithSplit(session.getTargetName().toLowerCase(), '_', true, true); // Populate by getting the metadata for the table name List<FakeNode> nodes = Database.getColumnInfo(session.getTargetName()); for (FakeNode node : nodes) { final String name = Utility.generateFieldFromColumn(node.getName()); node.setName(name); } // Call the method generateJavaClass(new File("."), session.getTargetData(), session.getTargetName(), nodes, className); } public void importSQL() { final ContentType cType = ContentType.getById(session.getTargetTypeId()); if ((cType != ContentType.JSON) && (cType != ContentType.CSV) && (cType != ContentType.YAML) && (cType != ContentType.TOML) && (cType != ContentType.XML) && (cType != ContentType.SQL_FILE) && (cType != ContentType.MARKDOWN) && (cType != ContentType.TSV) && (cType != ContentType.JAVA)) { Logger.error("Only supported export formats: CSV, JSON, YAML, TOML, XML, SQL, TSV, Markdown, Java"); return; } // Find the user DB with the specified ID final UserDb userDb = UserDBCache.get().find(session.getSourceId()); if (userDb == null) { Logger.error("Error: Invalid database ID in the session"); return; } // Make sure the JDBC DB's driver class is loaded final DbType dbType = DBTypeCache.get().find(userDb.getDbTypeId()); ConnManager.get().addDriverClass(dbType); // Open a connection to the database Logger.debug("Initializing the database " + userDb.getUrl()); ConnManager.get().init(userDb.getUrl(), userDb.getUserId(), userDb.getUserPw()); if (!ConnManager.get().create()) { Logger.error("Unable to connect to database " + userDb.getUrl()); return; } if (cType == ContentType.JAVA) { writeJavaClassFromSQL(); } else { // Get the metadata PreparedStatement stmt = null; try { // Prepare the statement stmt = ConnManager.get().getConn().prepareStatement(session.getSourceName()); // Verify it's not null if (stmt != null) { // Execute the statement and check the result final boolean result = stmt.execute(); if (!result) { Logger.error("The statement did not execute correctly"); } else { // Get the result set of executing the query ResultSet rs = stmt.getResultSet(); // Verify the result set is not null if (rs != null) { // Get the metadata ResultSetMetaData rsmd = rs.getMetaData(); // Configure the data target final DBFileWriter writer = getFileWriter(cType, session.getTargetName(), session.getTargetData(), rsmd); // Write the header writer.writeHeader(); // Iterate over the data for exporting Database.executeSelect(rs, writer); // Write the footer writer.writeFooter(); // Force out any pending data writer.writeString(true); // Close the result set rs.close(); rs = null; } else { Logger.error("The database result set is null"); } } // Close the statement stmt.close(); stmt = null; } else { Logger.error("The database statement is null"); } } catch (SQLException e) { Logger.error("SQL Exception: " + e.getMessage()); e.printStackTrace(); } } // Close the connection ConnManager.get().close(); } private static DBFileWriter getFileWriter(final ContentType cType, final String outName, final String outData, final ResultSetMetaData rsmd) { // Create the appropriate file writer object if (cType == ContentType.JSON) { return new JsonDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.CSV) { return new CsvDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.TSV) { return new TabDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.YAML) { return new YamlDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.TOML) { return new TomlDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.SQL_FILE) { return new SQLDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.MARKDOWN) { return new MarkdownDBFileWriter(outName, outData, rsmd); } else if (cType == ContentType.XML) { return new XmlDBFileWriter(outName, outData, rsmd); } else { return null; } } private static DBFileWriter getFileWriter(final ContentType cType, final String outName, final String outData, final FakeSpecParser spec) { // Create the appropriate file writer object if (cType == ContentType.JSON) { return new JsonDBFileWriter(outName, outData, spec); } else if (cType == ContentType.CSV) { return new CsvDBFileWriter(outName, outData, spec); } else if (cType == ContentType.TSV) { return new TabDBFileWriter(outName, outData, spec); } else if (cType == ContentType.YAML) { return new YamlDBFileWriter(outName, outData, spec); } else if (cType == ContentType.TOML) { return new TomlDBFileWriter(outName, outData, spec); } else if (cType == ContentType.SQL_FILE) { return new SQLDBFileWriter(outName, outData, spec); } else if (cType == ContentType.MARKDOWN) { return new MarkdownDBFileWriter(outName, outData, spec); } else if (cType == ContentType.XML) { return new XmlDBFileWriter(outName, outData, spec); } else { return null; } } /** * Generate the Java class for the table. * * @param outputDir the output directory * @param packageName the package name of the class * @param tableName the table name * @param nodes the list of columns and types */ private void generateJavaClass(final File outputDir, final String packageName, final String tableName, final List<FakeNode> nodes, final String className) { final String lineSep = DBFileWriter.EOL; // The output file File file = new File(outputDir, className + ".java"); // Write to the file BufferedWriter out = null; try { // Open the output writer out = new BufferedWriter(new FileWriter(file)); // Build the date SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss"); String dateStr = sdf.format(new Date()); // Write the header comment out.write("/*" + lineSep); out.write(" * Java class for the " + tableName + " object." + lineSep); out.write(" * Generated on " + dateStr + " by Beetle." + lineSep); out.write(" */" + lineSep + lineSep); // Write the package name (if any) if ((packageName != null) && (packageName.length() > 0)) { out.write("package " + packageName + ";" + lineSep + lineSep); } // If there are any Date fields, import the class now if (hasDateFields(nodes)) { out.write("import java.util.Date;" + lineSep + lineSep); } // Write the class comment out.write("/**" + lineSep); out.write(" * Java class to encapsulate the " + tableName + " object." + lineSep); out.write(" *" + lineSep); out.write(" * @version 1.0" + lineSep); out.write(" */" + lineSep); // Write the class declaration out.write("public final class " + className); out.write(lineSep + "{" + lineSep); // Write the field declarations for (FakeNode col : nodes) { out.write(" /**" + lineSep); out.write(" * The field " + col.getName() + "." + lineSep); out.write(" */" + lineSep); out.write(" private " + col.getTypeAsJavaClass() + " " + col.getName() + " = " + col.getDefaultValue() + ";" + lineSep + " " + lineSep); } // Write the default constructor out.write(" " + lineSep); out.write(" /**" + lineSep); out.write(" * Default constructor." + lineSep); out.write(" */" + lineSep); out.write(" public " + className + "()" + lineSep); out.write(" {" + lineSep); out.write(" super();" + lineSep); out.write(" }" + lineSep); // Write the getters/setters for (FakeNode col : nodes) { // The field name with the first character in uppercase final String fieldInUC = Utility.setFirstCharacter(col.getName(), true); // Write the getter out.write(" " + lineSep); out.write(" " + lineSep); out.write(" /**" + lineSep); out.write(" * Get the value for " + col.getName() + "." + lineSep); out.write(" *" + lineSep); out.write(" * @return the " + col.getName() + lineSep); out.write(" */" + lineSep); out.write(" public " + col.getTypeAsJavaClass() + " get" + fieldInUC + "()" + lineSep); out.write(" {" + lineSep); out.write(" return " + col.getName() + ";" + lineSep); out.write(" }" + lineSep); // Write the setter out.write(" " + lineSep); out.write(" " + lineSep); out.write(" /**" + lineSep); out.write(" * Update the value for " + col.getName() + "." + lineSep); out.write(" *" + lineSep); out.write(" * @param p" + fieldInUC + " the new value for " + col.getName() + lineSep); out.write(" */" + lineSep); out.write(" public void set" + fieldInUC + "(final " + col.getTypeAsJavaClass() + " p" + fieldInUC + ")" + lineSep); out.write(" {" + lineSep); out.write(" " + col.getName() + " = p" + fieldInUC + ";" + lineSep); out.write(" }" + lineSep); } // Write the class declaration out.write("}" + lineSep); // Close the writer out.close(); out = null; } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } /** * Return whether the list of nodes has any of type Date. * * @param nodes the list of nodes * @return if any have a type of Date */ private static boolean hasDateFields(final List<FakeNode> nodes) { boolean result = false; for (FakeNode node : nodes) { if (node.getClazz().equals(java.util.Date.class)) { result = true; break; } } return result; } }
// $Id: MessageBundle.java,v 1.2 2002/02/09 01:35:26 mdb Exp $ package com.threerings.util; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; import com.samskivert.util.StringUtil; /** * A message bundle provides an easy mechanism by which to obtain * translated message strings from a resource bundle. It uses the {@link * MessageFormat} class to substitute arguments into the translation * strings. Message bundles would generally be obtained via the {@link * MessageManager}, but could be constructed individually if so desired. */ public class MessageBundle { /** * Constructs a message bundle which will obtain localized messages * from the supplied resource bundle. The path is provided purely for * reporting purposes. */ public MessageBundle (String path, ResourceBundle bundle) { _path = path; _bundle = bundle; } /** * Obtains the translation for the specified message key. No arguments * are substituted into the translated string. If a translation * message does not exist for the specified key, an error is logged * and the key itself is returned so that the caller need not worry * about handling a null response. */ public String get (String key) { try { return _bundle.getString(key); } catch (MissingResourceException mre) { Log.warning("Missing translation message " + "[bundle=" + _path + ", key=" + key + "]."); return key; } } /** * Obtains the translation for the specified message key. The * specified argument is substituted into the translated string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the argument) is returned so that the caller need not worry about * handling a null response. */ public String get (String key, Object arg1) { return get(key, new Object[] { arg1 }); } /** * Obtains the translation for the specified message key. The * specified arguments are substituted into the translated string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String get (String key, Object arg1, Object arg2) { return get(key, new Object[] { arg1, arg2 }); } /** * Obtains the translation for the specified message key. The * specified arguments are substituted into the translated string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String get (String key, Object arg1, Object arg2, Object arg3) { return get(key, new Object[] { arg1, arg2, arg3 }); } /** * Obtains the translation for the specified message key. The * specified arguments are substituted into the translated string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String get (String key, Object[] args) { try { String message = _bundle.getString(key); return MessageFormat.format(message, args); } catch (MissingResourceException mre) { Log.warning("Missing translation message " + "[bundle=" + _path + ", key=" + key + "]."); return key + StringUtil.toString(args); } } /** * Obtains the translation for the specified compound message key. A * compound key contains the message key followed by a tab separated * list of message arguments which will be subsituted into the * translation string. * * <p> See {@link MessageFormat} for more information on how the * substitution is performed. If a translation message does not exist * for the specified key, an error is logged and the key itself (plus * the arguments) is returned so that the caller need not worry about * handling a null response. */ public String xlate (String compoundKey) { // to be more efficient about creating unnecessary objects, we // do some checking before splitting int tidx = compoundKey.indexOf("\t"); if (tidx == -1) { return get(compoundKey); } else { String key = compoundKey.substring(0, tidx); String argstr = compoundKey.substring(tidx+1); String[] args = StringUtil.split(argstr, "\t"); return get(key, args); } } /** The path that identifies the resource bundle we are using to * obtain our messages. */ protected String _path; /** The resource bundle from which we obtain our messages. */ protected ResourceBundle _bundle; }
package org.spoofax.interpreter; import aterm.AFun; import aterm.ATerm; import aterm.ATermAppl; import aterm.ATermInt; import aterm.ATermList; import aterm.ATermReal; import aterm.pure.PureFactory; public class Tools { public static String stringAt(ATerm t, int i) { return ((ATermAppl) t.getChildAt(i)).getName(); } public static ATermAppl applAt(ATerm t, int i) { return (ATermAppl) ((ATermAppl) t).getChildAt(i); } public static ATermAppl applAt(ATermList t, int i) { return (ATermAppl) t.getChildAt(i); } public static ATermInt intAt(ATerm t, int i) { return (ATermInt) ((ATermAppl) t).getChildAt(i); } public static ATermInt intAt(ATermList t, int i) { return (ATermInt) t.getChildAt(i); } public ATerm implode(PureFactory factory, ATermAppl t) throws FatalError { if (t.getName().equals("Anno")) { return implode(factory, applAt(t, 0)); } else if (t.getName().equals("Op")) { String ctr = stringAt(t, 0); ATermList children = (ATermList) t.getChildAt(1); AFun afun = factory.makeAFun(ctr, children.getLength(), false); ATermList kids = factory.makeList(); for (int i = 0; i < children.getLength(); i++) { kids = kids.append(implode(factory, (ATermAppl) children .elementAt(i))); } return factory.makeApplList(afun, kids); } else if (t.getName().equals("Int")) { ATermAppl x = (ATermAppl) t.getChildAt(0); return factory.makeInt(new Integer(x.getName())); } else if (t.getName().equals("Str")) { ATermAppl x = (ATermAppl) t.getChildAt(0); return x; } throw new FatalError("Unknown build constituent '" + t.getName() + "'"); } public static ATermList listAt(ATerm t, int i) { return (ATermList) ((ATermAppl) t).getChildAt(i); } public static ATermList listAt(ATermList t, int i) { return (ATermList) t.getChildAt(i); } public static ATerm termAt(ATermAppl t, int i) { return (ATerm) t.getChildAt(i); } public static ATermReal realAt(ATermList tvars, int i) { return (ATermReal) tvars.getChildAt(i); } public static ATerm termAt(ATermList tvars, int i) { return (ATerm) tvars.getChildAt(i); } public static boolean termType(ATermAppl p, String n) { return p.getName().equals(n); } public static ATermList consToList(PureFactory factory, ATermAppl cons) { if (cons.getName().equals("Nil")) return factory.makeList(); ATermList tail = consToList(factory, Tools.applAt(cons, 1)); ATerm head = Tools.termAt(cons, 0); return tail.insert(head); } public static ATermList consToListDeep(TermFactory factory, ATermAppl cons) { if (cons.getName().equals("Nil")) return factory.makeList(); ATermList tail = consToListDeep(factory, Tools.applAt(cons, 1)); ATerm head = Tools.termAt(cons, 0); if (Tools.isCons(head)) head = consToListDeep(factory,(ATermAppl) head); return tail.insert(head); } private static boolean isCons(ATerm head) { return (head.getType() == ATerm.APPL && ((ATermAppl)head).getName().equals("Cons")); } }
// Clirr: compares two versions of a java library for binary compatibility // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sf.clirr.checks; import java.util.Arrays; import java.util.Comparator; import net.sf.clirr.framework.ClassChangeCheck; import net.sf.clirr.framework.AbstractDiffReporter; import net.sf.clirr.framework.ApiDiffDispatcher; import net.sf.clirr.event.ApiDifference; import net.sf.clirr.event.Severity; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Field; /** * Checks the fields of a class. * * @author lkuehne */ public class FieldSetCheck extends AbstractDiffReporter implements ClassChangeCheck { private static final class FieldNameComparator implements Comparator { public int compare(Object o1, Object o2) { Field f1 = (Field) o1; Field f2 = (Field) o2; final String name1 = f1.getName(); final String name2 = f2.getName(); return name1.compareTo(name2); } } private Comparator comparator = new FieldNameComparator(); public FieldSetCheck(ApiDiffDispatcher dispatcher) { super(dispatcher); } public final void check(JavaClass compatBaseline, JavaClass currentVersion) { final Field[] baselineFields = compatBaseline.getFields(); final Field[] currentFields = currentVersion.getFields(); // Sigh... BCEL 5.1 hands out it's internal datastructure, // so we have to make a copy here to make sure we don't mess up BCEL by sorting final Field[] bFields = createSortedCopy(baselineFields); final Field[] cFields = createSortedCopy(currentFields); checkForChanges(bFields, cFields, compatBaseline, currentVersion); } private void checkForChanges( Field[] bFields, Field[] cFields, JavaClass baseLineClass, JavaClass currentClass) { boolean[] newInCurrent = new boolean[cFields.length]; Arrays.fill(newInCurrent, true); for (int i = 0; i < bFields.length; i++) { Field bField = bFields[i]; if (!bField.isPublic() && !bField.isProtected()) { continue; } int cIdx = Arrays.binarySearch(cFields, bField, comparator); if (cIdx < 0) { final String name = bField.getName(); fireDiff("Field " + name + " has been removed", Severity.ERROR, baseLineClass, bField); } else { Field cField = cFields[cIdx]; newInCurrent[cIdx] = false; checkForModifierChange(bField, cField, currentClass); checkForVisibilityChange(bField, cField, currentClass); checkForReturnTypeChange(bField, cField, currentClass); } } for (int i = 0; i < newInCurrent.length; i++) { Field field = cFields[i]; if (newInCurrent[i] && (field.isPublic() || field.isProtected())) { String scope = field.isPublic() ? "public" : "protected"; final String fieldName = field.getName(); fireDiff("Added " + scope + " field " + fieldName, Severity.INFO, currentClass, field); } } // TODO: Check field types // TODO: warn about constant value changes (see JLS, section 13.4.8) } private void checkForReturnTypeChange(Field bField, Field cField, JavaClass currentClass) { final String bSig = bField.getType().toString(); final String cSig = cField.getType().toString(); if (!bSig.equals(cSig)) { fireDiff("Changed type of field " + bField.getName() + " from " + bSig + " to " + cSig, Severity.ERROR, currentClass, bField); } } private void checkForModifierChange(Field bField, Field cField, JavaClass clazz) { if (bField.isFinal() && !cField.isFinal()) { fireDiff("Field " + bField.getName() + " is now non-final", Severity.INFO, clazz, cField); } if (!bField.isFinal() && cField.isFinal()) { fireDiff("Field " + bField.getName() + " is now final", Severity.ERROR, clazz, cField); } if (bField.isStatic() && !cField.isStatic()) { fireDiff("Field " + bField.getName() + " is now non-static", Severity.ERROR, clazz, cField); } if (!bField.isStatic() && cField.isStatic()) { fireDiff("Field " + bField.getName() + " is now static", Severity.ERROR, clazz, cField); } // JLS, 13.4.10: Adding or deleting a transient modifier of a field // does not break compatibility with pre-existing binaries // TODO: What about volatile? } private void checkForVisibilityChange(Field bField, Field cField, JavaClass clazz) { if (bField.isProtected() && cField.isPublic()) { fireDiff("Field " + bField.getName() + " is now public", Severity.INFO, clazz, cField); } else if (bField.isProtected() && !(cField.isProtected() || cField.isPublic()) || bField.isPublic() && !cField.isPublic()) { fireDiff("Accessibility of field " + bField.getName() + " has been weakened", Severity.ERROR, clazz, cField); } } private void fireDiff(String report, Severity severity, JavaClass clazz, Field field) { final String className = clazz.getClassName(); final ApiDifference diff = new ApiDifference(report + " in " + className, severity, className, null, field.getName()); getApiDiffDispatcher().fireDiff(diff); } private Field[] createSortedCopy(final Field[] orig) { final Field[] fields = new Field[orig.length]; System.arraycopy(orig, 0, fields, 0, orig.length); Arrays.sort(fields, comparator); return fields; } }
package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Abstract superclass for type-safe enums. * <p> * One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern. * <p> * <em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing Enum objects * should always be done using the equals() method, not ==. The equals() method will * try == first so in most cases the effect is the same. * <p> * To use this class, it must be subclassed. For example: * * <pre> * public final class ColorEnum extends Enum { * public static final ColorEnum RED = new ColorEnum("Red"); * public static final ColorEnum GREEN = new ColorEnum("Green"); * public static final ColorEnum BLUE = new ColorEnum("Blue"); * * private ColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ColorEnum.class); * } * } * </pre> * <p> * As shown, each enum has a name. This can be accessed using <code>getName</code>. * <p> * The <code>getEnum</code> and <code>iterator</code> methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class. * <p> * <em>NOTE:</em> This class originated in the Jakarta Avalon project. * </p> * * @author <a href="mailto:scolebourne@joda.org">Stephen Colebourne</a> * @version $Id: Enum.java,v 1.2 2002/08/31 10:51:02 scolebourne Exp $ */ public abstract class Enum implements Comparable, Serializable { /** * Map, key of class name, value of Entry. */ private static final Map cEnumClasses = new HashMap(); /** * The string representation of the Enum. */ private final String iName; /** * Enable the iterator to retain the source code order */ private static class Entry { /** Map of Enum name to Enum */ final Map map = new HashMap(50); /** List of Enums in source code order */ final List list = new ArrayList(25); /** * Restrictive constructor */ private Entry() { } } protected Enum(String name) { super(); if (name == null || name.length() == 0) { throw new IllegalArgumentException("The Enum name must not be empty"); } iName = name; Entry entry = (Entry) cEnumClasses.get(getClass().getName()); if (entry == null) { entry = new Entry(); cEnumClasses.put(getClass().getName(), entry); } entry.map.put(name, this); entry.list.add(this); } protected Object readResolve() { return Enum.getEnum(getClass(), getName()); } protected static Enum getEnum(Class enumClass, String name) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return null; } return (Enum) entry.map.get(name); } protected static Map getEnumMap(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return Collections.EMPTY_MAP; } return Collections.unmodifiableMap(entry.map); } protected static List getEnumList(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass.getName()); if (entry == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(entry.list); } protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } /** * Retrieve the name of this Enum item, set in the constructor. * * @return the <code>String</code> name of this Enum item */ public final String getName() { return iName; } /** * Tests for equality. Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast. * * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // shouldn't happen, but... return iName.equals(((Enum) other).iName); } else if (other.getClass().getName().equals(this.getClass().getName())) { // different classloaders try { // try to avoid reflection return iName.equals(((Enum) other).iName); } catch (ClassCastException ex) { // use reflection try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return iName.equals(name); } catch (NoSuchMethodException ex2) { // ignore - should never happen } catch (IllegalAccessException ex2) { // ignore - should never happen } catch (InvocationTargetException ex2) { // ignore - should never happen } return false; } } else { return false; } } /** * Returns a suitable hashCode for the enumeration. * * @return a hashcode based on the name */ public final int hashCode() { return 7 + iName.hashCode(); } /** * Tests for order. The default ordering is alphabetic by name, but this * can be overridden by subclasses. * * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { return iName.compareTo(((Enum) other).iName); } /** * Human readable description of this Enum item. For use when debugging. * * @return String in the form <code>type[name]</code>, for example: * <code>Color[Red]</code>. Note that the package name is stripped from * the type name. */ public String toString() { String shortName = getClass().getName(); int pos = shortName.lastIndexOf('.'); if (pos != -1) { shortName = shortName.substring(pos + 1); } return shortName + "[" + getName() + "]"; } }
package org.jdesktop.swingx; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.*; /** * Common Error Dialog. Composed of a title, message, and details. * @author Richard Bair */ public class JXErrorDialog extends JDialog { /** * Text representing expanding the details section of the dialog */ private static final String DETAILS_EXPAND_TEXT = "Details >>"; /** * Text representing contracting the details section of the dialog */ private static final String DETAILS_CONTRACT_TEXT = "Details <<"; /** * Text for the Ok button. */ private static final String OK_BUTTON_TEXT = "Ok"; /** * Icon for the error dialog (stop sign, etc) */ private static final Icon icon = UIManager.getIcon("OptionPane.warningIcon"); /** * Error message label */ private JLabel errorMessage; /** * details text area */ private JTextArea details; /** * detail button */ private JButton detailButton; /** * details scroll pane */ private JScrollPane detailsScrollPane; /** * String- and PrintWriter needed to format and print an exception. * They are to be initialized and used in appropriate method */ private static StringWriter sw; private static PrintWriter pw; /** * Create a new ErrorDialog with the given Frame as the owner * @param owner */ public JXErrorDialog(Frame owner) { super(owner, true); initGui(); } /** * Create a new ErrorDialog with the given Dialog as the owner * @param owner */ private JXErrorDialog(Dialog owner) { super(owner, true); initGui(); } /** * initialize the gui. */ private void initGui() { //initialize the gui GridBagLayout layout = new GridBagLayout(); this.getContentPane().setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.insets = new Insets(22, 12, 11, 17); this.getContentPane().add(new JLabel(icon), gbc); errorMessage = new JLabel(); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.BOTH; gbc.gridheight = 1; gbc.gridwidth = 2; gbc.gridx = 1; gbc.weightx = 1.0; gbc.insets = new Insets(12, 0, 0, 11); this.getContentPane().add(errorMessage, gbc); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 0.0; gbc.anchor = GridBagConstraints.EAST; gbc.insets = new Insets(12, 0, 11, 5); JButton okButton = new JButton(OK_BUTTON_TEXT); this.getContentPane().add(okButton, gbc); detailButton = new JButton(DETAILS_EXPAND_TEXT); gbc.gridx = 2; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 11); this.getContentPane().add(detailButton, gbc); details = new JTextArea(7, 60); detailsScrollPane = new JScrollPane(details); details.setEditable(false); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 3; gbc.gridx = 0; gbc.gridy = 2; gbc.weighty = 1.0; gbc.insets = new Insets(6, 11, 11, 11); this.getContentPane().add(detailsScrollPane, gbc); //make the buttons the same size int buttonLength = detailButton.getPreferredSize().width; int buttonHeight = detailButton.getPreferredSize().height; Dimension buttonSize = new Dimension(buttonLength, buttonHeight); okButton.setPreferredSize(buttonSize); detailButton.setPreferredSize(buttonSize); //set the event handling okButton.addActionListener(new OkClickEvent()); detailButton.addActionListener(new DetailsClickEvent()); } /** * Set the details section of the error dialog. If the details are either * null or an empty string, then hide the details button and hide the detail * scroll pane. Otherwise, just set the details section. * @param details */ private void setDetails(String details) { if (details == null || details.equals("")) { setDetailsVisible(false); detailButton.setVisible(false); } else { this.details.setText(details); setDetailsVisible(false); detailButton.setVisible(true); } } /** * Set the details section to be either visible or invisible. Set the * text of the Details button accordingly. * @param b */ private void setDetailsVisible(boolean b) { if (b) { details.setCaretPosition(0); detailsScrollPane.setVisible(true); detailButton.setText(DETAILS_CONTRACT_TEXT); /** * increase the width and height of the dialog according to the following algorithm: * Double the width and height. * FUTURE check to see what width and height would be necessary to show all of the contents * of the details text area. If the width and height are below some given threshold * (for instance, 2x the original size) then set the dialog to the optimal width/height. * If above that threshold, then set the dialog to be the threshold */ } else { detailsScrollPane.setVisible(false); detailButton.setText(DETAILS_EXPAND_TEXT); } pack(); } /** * Set the error message for the dialog box * @param errorMessage */ private void setErrorMessage(String errorMessage) { this.errorMessage.setText(errorMessage); } /** * Listener for Ok button click events * @author Richard Bair */ private final class OkClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { //close the window setVisible(false); } } /** * Listener for Details click events. Alternates whether the details section * is visible or not. * @author Richard Bair */ private final class DetailsClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { setDetailsVisible(!detailsScrollPane.isVisible()); } } /** * Constructs and shows the error dialog for the given exception. The exceptions message will be the * errorMessage, and the stacktrace will be the details. * @param owner * @param title * @param e */ public static void showDialog(Window owner, String title, Throwable e) { if(sw == null) { sw = new StringWriter(); pw = new PrintWriter(sw); } e.printStackTrace(pw); showDialog(owner, title, e.getLocalizedMessage(), sw.toString()); } /** * Show the error dialog. * @param owner Owner of this error dialog. This cannot be null. * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ public static void showDialog(Window owner, String title, String errorMessage, String details) { JXErrorDialog dlg; if (owner instanceof Dialog) { dlg = new JXErrorDialog((Dialog)owner); } else { dlg = new JXErrorDialog((Frame)owner); } dlg.setTitle(title); dlg.setErrorMessage(errorMessage); dlg.setDetails(details); dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dlg.pack(); dlg.setLocationRelativeTo(owner); dlg.setVisible(true); } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.io.StringWriter; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; import org.jdesktop.swingx.util.WindowUtils; /** * Common Error Dialog, suitable for representing information about * errors and exceptions happened in application. The common usage of the * <code>JXErrorDialog</code> is to show collected data about the incident and * probably ask customer for a feedback. The data about the incident consists * from the title which will be displayed in the dialog header, short * description of the problem that will be immediately seen after dialog is * became visible, full description of the problem which will be visible after * user clicks "Details" button and Throwable that contains stack trace and * another usable information that may be displayed in the dialog.<p> * * To ask user for feedback extend abstract class <code>ErrorReporter</code> and * set your reporter using <code>setReporter</code> method. Report button will * be added to the dialog automatically.<br> * See {@link MailErrorReporter MailErrorReporter} documentation for the * example of error reporting usage.<p> * For example, to show simple <code>JXErrorDialog</code> call <br> * <code>JXErrorDialog.showDialog(null, "Application Error", * "The application encountered the unexpected error, * please contact developers")</code> * @author Richard Bair * @author Alexander Zuev */ public class JXErrorDialog extends JDialog { /** * Text representing expanding the details section of the dialog */ private static final String DETAILS_EXPAND_TEXT = "Details >>"; /** * Text representing contracting the details section of the dialog */ private static final String DETAILS_CONTRACT_TEXT = "Details <<"; /** * Text for the Ok button. */ private static final String OK_BUTTON_TEXT = "Ok"; /** * Icon for the error dialog (stop sign, etc) */ private static final Icon icon = UIManager.getIcon("OptionPane.warningIcon"); /** * Text for the reportError button */ private static final String REPORT_BUTTON_TEXT = "Report..."; /** * Error message label */ private JLabel errorMessage; /** * details text area */ private JTextArea details; /** * detail button */ private JButton detailButton; /** * details scroll pane */ private JScrollPane detailsScrollPane; /** * report an error button */ private JButton reportButton; /** * Error reporting engine assigned for error reporting for all error dialogs */ private static ErrorReporter reporter; /** * IncidentInfo that contains all the information prepared for * reporting. */ private IncidentInfo incidentInfo; /** * Create a new ErrorDialog with the given Frame as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Frame owner) { super(owner, true); initGui(); } /** * Create a new ErrorDialog with the given Dialog as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Dialog owner) { super(owner, true); initGui(); } /** * initialize the gui. */ private void initGui() { //initialize the gui GridBagLayout layout = new GridBagLayout(); this.getContentPane().setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.insets = new Insets(22, 12, 11, 17); this.getContentPane().add(new JLabel(icon), gbc); errorMessage = new JLabel(); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.BOTH; gbc.gridheight = 1; gbc.gridwidth = 2; gbc.gridx = 1; gbc.weightx = 1.0; gbc.insets = new Insets(12, 0, 0, 11); this.getContentPane().add(errorMessage, gbc); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 0.0; gbc.anchor = GridBagConstraints.EAST; gbc.insets = new Insets(12, 0, 11, 5); JButton okButton = new JButton(OK_BUTTON_TEXT); this.getContentPane().add(okButton, gbc); reportButton = new JButton(new ReportAction()); gbc.gridx = 2; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 5); this.getContentPane().add(reportButton, gbc); reportButton.setVisible(false); // not visible by default detailButton = new JButton(DETAILS_EXPAND_TEXT); gbc.gridx = 3; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 11); this.getContentPane().add(detailButton, gbc); details = new JTextArea(7, 60); detailsScrollPane = new JScrollPane(details); detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); details.setEditable(false); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 4; gbc.gridx = 0; gbc.gridy = 2; gbc.weighty = 1.0; gbc.insets = new Insets(6, 11, 11, 11); this.getContentPane().add(detailsScrollPane, gbc); /* * Here i'm going to add invisible empty container to the bottom of the * content pane to fix minimal width of the dialog. It's quite a hack, * but i have not found anything better. */ Dimension spPredictedSize = detailsScrollPane.getPreferredSize(); Dimension newPanelSize = new Dimension(spPredictedSize.width+15, 0); Container widthHolder = new Container(); widthHolder.setMinimumSize(newPanelSize); widthHolder.setPreferredSize(newPanelSize); widthHolder.setMaximumSize(newPanelSize); gbc.gridy = 3; gbc.insets = new Insets(0, 11, 11, 0); this.getContentPane().add(widthHolder, gbc); //make the buttons the same size int buttonLength = detailButton.getPreferredSize().width; int buttonHeight = detailButton.getPreferredSize().height; Dimension buttonSize = new Dimension(buttonLength, buttonHeight); okButton.setPreferredSize(buttonSize); reportButton.setPreferredSize(buttonSize); detailButton.setPreferredSize(buttonSize); //set the event handling okButton.addActionListener(new OkClickEvent()); detailButton.addActionListener(new DetailsClickEvent()); } /** * Set the details section of the error dialog. If the details are either * null or an empty string, then hide the details button and hide the detail * scroll pane. Otherwise, just set the details section. * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ private void setDetails(String details) { if (details == null || details.equals("")) { setDetailsVisible(false); detailButton.setVisible(false); } else { this.details.setText(details); setDetailsVisible(false); detailButton.setVisible(true); } } /** * Set the details section to be either visible or invisible. Set the * text of the Details button accordingly. * @param b if true details section will be visible */ private void setDetailsVisible(boolean b) { if (b) { details.setCaretPosition(0); detailsScrollPane.setVisible(true); detailButton.setText(DETAILS_CONTRACT_TEXT); } else { detailsScrollPane.setVisible(false); detailButton.setText(DETAILS_EXPAND_TEXT); } pack(); } /** * Set the error message for the dialog box * @param errorMessage Message for the error dialog */ private void setErrorMessage(String errorMessage) { this.errorMessage.setText(errorMessage); } /** * Sets the IncidentInfo for this dialog * * @param info IncidentInfo that incorporates all the details about the error */ private void setIncidentInfo(IncidentInfo info) { this.incidentInfo = info; this.reportButton.setVisible(getReporter() != null); } /** * Get curent dialog's IncidentInfo * * @return <code>IncidentInfo</code> assigned to this dialog */ private IncidentInfo getIncidentInfo() { return incidentInfo; } /** * Listener for Ok button click events * @author Richard Bair */ private final class OkClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { //close the window setVisible(false); } } /** * Listener for Details click events. Alternates whether the details section * is visible or not. * @author Richard Bair */ private final class DetailsClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { setDetailsVisible(!detailsScrollPane.isVisible()); } } /** * Constructs and shows the error dialog for the given exception. The exceptions message will be the * errorMessage, and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, Throwable e) { IncidentInfo ii = new IncidentInfo(title, null, null, e); showDialog(owner, ii); } /** * Constructs and shows the error dialog for the given exception. The exceptions message is specified, * and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, String errorMessage, Throwable e) { IncidentInfo ii = new IncidentInfo(title, errorMessage, null, e); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ public static void showDialog(Component owner, String title, String errorMessage, String details) { IncidentInfo ii = new IncidentInfo(title, errorMessage, details); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param info <code>IncidentInfo</code> that incorporates all the information about the error */ public static void showDialog(Component owner, IncidentInfo info) { JXErrorDialog dlg; Window window = WindowUtils.findWindow(owner); if (owner instanceof Dialog) { dlg = new JXErrorDialog((Dialog)owner); } else { dlg = new JXErrorDialog((Frame)owner); } dlg.setTitle(info.getHeader()); dlg.setErrorMessage(info.getBasicErrorMessage()); String details = info.getDetailedErrorMessage(); if(details == null) { if(info.getErrorException() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); info.getErrorException().printStackTrace(pw); details = sw.toString(); } else { details = ""; } } dlg.setDetails(details); dlg.setIncidentInfo(info); dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dlg.pack(); dlg.setLocationRelativeTo(owner); dlg.setVisible(true); } /** * Returns the current reporting engine that will be used to report a problem if * user clicks on 'Report' button or <code>null</code> if no reporting engine set. * * @return reporting engine */ public static ErrorReporter getReporter() { return reporter; } /** * Set reporting engine which will handle error reporting if user clicks 'report' button. * * @param rep <code>ErrorReporter</code> to be used or <code>null</code> to turn reporting facility off. */ public static void setReporter(ErrorReporter rep) { reporter = rep; } /** * Action for report button */ public class ReportAction extends AbstractAction { public boolean isEnabled() { return (getReporter() != null); } public void actionPerformed(ActionEvent e) { getReporter().reportIncident(getIncidentInfo()); } public Object getValue(String key) { if(key == Action.NAME) { if(getReporter() != null && getReporter().getActionName() != null) { return getReporter().getActionName(); } else { return REPORT_BUTTON_TEXT; } } return super.getValue(key); } } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Enumeration; import java.util.ResourceBundle; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; import org.jdesktop.swingx.util.WindowUtils; /** * Common Error Dialog, suitable for representing information about * errors and exceptions happened in application. The common usage of the * <code>JXErrorDialog</code> is to show collected data about the incident and * probably ask customer for a feedback. The data about the incident consists * from the title which will be displayed in the dialog header, short * description of the problem that will be immediately seen after dialog is * became visible, full description of the problem which will be visible after * user clicks "Details" button and Throwable that contains stack trace and * another usable information that may be displayed in the dialog.<p> * * To ask user for feedback extend abstract class <code>ErrorReporter</code> and * set your reporter using <code>setReporter</code> method. Report button will * be added to the dialog automatically.<br> * See {@link MailErrorReporter MailErrorReporter} documentation for the * example of error reporting usage.<p> * For example, to show simple <code>JXErrorDialog</code> call <br> * <code>JXErrorDialog.showDialog(null, "Application Error", * "The application encountered the unexpected error, * please contact developers")</code> * * <p>Internationalization is handled via a resource bundle or via the UIManager * bidi orientation (usefull for right to left languages) is determined in the * same way as the JOptionPane where the orientation of the parent component is * picked. So when showDialog(Component cmp, ...) is invoked the component * orientation of the error dialog will match the component orientation of cmp. * @author Richard Bair * @author Alexander Zuev * @author Shai Almog */ public class JXErrorDialog extends JDialog { /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME; /** * Icon for the error dialog (stop sign, etc) */ private static final Icon icon = UIManager.getIcon("OptionPane.warningIcon"); /** * Error message label */ private JLabel errorMessage; /** * details text area */ private JTextArea details; /** * detail button */ private EqualSizeJButton detailButton; /** * details scroll pane */ private JScrollPane detailsScrollPane; /** * report an error button */ private EqualSizeJButton reportButton; /** * Error reporting engine assigned for error reporting for all error dialogs */ private static ErrorReporter reporter; /** * IncidentInfo that contains all the information prepared for * reporting. */ private IncidentInfo incidentInfo; /** * Creates initialize the UIManager with localized strings */ static { // Popuplate UIDefaults with the localizable Strings we will use // in the Login panel. CLASS_NAME = JXErrorDialog.class.getCanonicalName(); String lookup; ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.plaf.resources.ErrorDialog"); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); lookup = CLASS_NAME + "." + key; if (UIManager.getString(lookup) == null) { UIManager.put(lookup, res.getString(key)); } } } /** * Create a new ErrorDialog with the given Frame as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Frame owner) { super(owner, true); initGui(); } /** * Create a new ErrorDialog with the given Dialog as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Dialog owner) { super(owner, true); initGui(); } /** * initialize the gui. */ private void initGui() { //initialize the gui GridBagLayout layout = new GridBagLayout(); this.getContentPane().setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.insets = new Insets(22, 12, 11, 17); this.getContentPane().add(new JLabel(icon), gbc); errorMessage = new JLabel(); gbc.anchor = GridBagConstraints.LINE_START; gbc.fill = GridBagConstraints.BOTH; gbc.gridheight = 1; gbc.gridwidth = 2; gbc.gridx = 1; gbc.weightx = 1.0; gbc.insets = new Insets(12, 0, 0, 11); this.getContentPane().add(errorMessage, gbc); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 0.0; gbc.anchor = GridBagConstraints.LINE_END; gbc.insets = new Insets(12, 0, 11, 5); EqualSizeJButton okButton = new EqualSizeJButton(UIManager.getString(CLASS_NAME + ".ok_button_text")); this.getContentPane().add(okButton, gbc); reportButton = new EqualSizeJButton(new ReportAction()); gbc.gridx = 2; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 5); this.getContentPane().add(reportButton, gbc); reportButton.setVisible(false); // not visible by default detailButton = new EqualSizeJButton(UIManager.getString(CLASS_NAME + ".details_expand_text")); gbc.gridx = 3; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 11); this.getContentPane().add(detailButton, gbc); details = new JTextArea(7, 60); detailsScrollPane = new JScrollPane(details); detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); details.setEditable(false); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 4; gbc.gridx = 0; gbc.gridy = 2; gbc.weighty = 1.0; gbc.insets = new Insets(6, 11, 11, 11); this.getContentPane().add(detailsScrollPane, gbc); /* * Here i'm going to add invisible empty container to the bottom of the * content pane to fix minimal width of the dialog. It's quite a hack, * but i have not found anything better. */ Dimension spPredictedSize = detailsScrollPane.getPreferredSize(); Dimension newPanelSize = new Dimension(spPredictedSize.width+15, 0); Container widthHolder = new Container(); widthHolder.setMinimumSize(newPanelSize); widthHolder.setPreferredSize(newPanelSize); widthHolder.setMaximumSize(newPanelSize); gbc.gridy = 3; gbc.insets = new Insets(0, 11, 11, 0); this.getContentPane().add(widthHolder, gbc); //make the buttons the same size EqualSizeJButton[] buttons = new EqualSizeJButton[] { detailButton, okButton, reportButton }; okButton.setGroup(buttons); reportButton.setGroup(buttons); detailButton.setGroup(buttons); //set the event handling okButton.addActionListener(new OkClickEvent()); detailButton.addActionListener(new DetailsClickEvent()); } /** * Set the details section of the error dialog. If the details are either * null or an empty string, then hide the details button and hide the detail * scroll pane. Otherwise, just set the details section. * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ private void setDetails(String details) { if (details == null || details.equals("")) { setDetailsVisible(false); detailButton.setVisible(false); } else { this.details.setText(details); setDetailsVisible(false); detailButton.setVisible(true); } } /** * Set the details section to be either visible or invisible. Set the * text of the Details button accordingly. * @param b if true details section will be visible */ private void setDetailsVisible(boolean b) { if (b) { details.setCaretPosition(0); detailsScrollPane.setVisible(true); detailButton.setText(UIManager.getString(CLASS_NAME + ".details_contract_text")); detailsScrollPane.applyComponentOrientation(detailButton.getComponentOrientation()); // workaround for bidi bug, if the text is not set "again" and the component orientation has changed // then the text won't be aligned correctly. To reproduce this (in JDK 1.5) show two dialogs in one // use LTOR orientation and in the second use RTOL orientation and press "details" in both. // Text in the text box should be aligned to right/left respectively, without this line this doesn't // occure I assume because bidi properties are tested when the text is set and are not updated later // on when setComponentOrientation is invoked. details.setText(details.getText()); } else { detailsScrollPane.setVisible(false); detailButton.setText(UIManager.getString(CLASS_NAME + ".details_expand_text")); } pack(); repaint(); } /** * Set the error message for the dialog box * @param errorMessage Message for the error dialog */ private void setErrorMessage(String errorMessage) { this.errorMessage.setText(errorMessage); } /** * Sets the IncidentInfo for this dialog * * @param info IncidentInfo that incorporates all the details about the error */ private void setIncidentInfo(IncidentInfo info) { this.incidentInfo = info; this.reportButton.setVisible(getReporter() != null); } /** * Get curent dialog's IncidentInfo * * @return <code>IncidentInfo</code> assigned to this dialog */ private IncidentInfo getIncidentInfo() { return incidentInfo; } /** * Listener for Ok button click events * @author Richard Bair */ private final class OkClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { //close the window setVisible(false); dispose(); } } /** * Listener for Details click events. Alternates whether the details section * is visible or not. * @author Richard Bair */ private final class DetailsClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { setDetailsVisible(!detailsScrollPane.isVisible()); } } /** * Constructs and shows the error dialog for the given exception. The exceptions message will be the * errorMessage, and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, Throwable e) { IncidentInfo ii = new IncidentInfo(title, null, null, e); showDialog(owner, ii); } /** * Constructs and shows the error dialog for the given exception. The exceptions message is specified, * and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, String errorMessage, Throwable e) { IncidentInfo ii = new IncidentInfo(title, errorMessage, null, e); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ public static void showDialog(Component owner, String title, String errorMessage, String details) { IncidentInfo ii = new IncidentInfo(title, errorMessage, details); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param info <code>IncidentInfo</code> that incorporates all the information about the error */ public static void showDialog(Component owner, IncidentInfo info) { JXErrorDialog dlg; Window window = WindowUtils.findWindow(owner); if (owner instanceof Dialog) { dlg = new JXErrorDialog((Dialog)owner); } else { dlg = new JXErrorDialog((Frame)owner); } dlg.setTitle(info.getHeader()); dlg.setErrorMessage(info.getBasicErrorMessage()); String details = info.getDetailedErrorMessage(); if(details == null) { if(info.getErrorException() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); info.getErrorException().printStackTrace(pw); details = sw.toString(); } else { details = ""; } } dlg.setDetails(details); dlg.setIncidentInfo(info); dlg.applyComponentOrientation(owner.getComponentOrientation()); dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dlg.pack(); dlg.setLocationRelativeTo(owner); dlg.setVisible(true); } /** * Returns the current reporting engine that will be used to report a problem if * user clicks on 'Report' button or <code>null</code> if no reporting engine set. * * @return reporting engine */ public static ErrorReporter getReporter() { return reporter; } /** * Set reporting engine which will handle error reporting if user clicks 'report' button. * * @param rep <code>ErrorReporter</code> to be used or <code>null</code> to turn reporting facility off. */ public static void setReporter(ErrorReporter rep) { reporter = rep; } /** * Action for report button */ public class ReportAction extends AbstractAction { public boolean isEnabled() { return (getReporter() != null); } public void actionPerformed(ActionEvent e) { getReporter().reportIncident(getIncidentInfo()); } public Object getValue(String key) { if(key == Action.NAME) { if(getReporter() != null && getReporter().getActionName() != null) { return getReporter().getActionName(); } else { return UIManager.getString(CLASS_NAME + ".report_button_text"); } } return super.getValue(key); } } /** * This is a button that maintains the size of the largest button in the button * group by returning the largest size from the getPreferredSize method. * This is better than using setPreferredSize since this will work regardless * of changes to the text of the button and its language. */ private static class EqualSizeJButton extends JButton { public EqualSizeJButton() { } public EqualSizeJButton(String text) { super(text); } public EqualSizeJButton(Action a) { super(a); } /** * Buttons whose size should be taken into consideration */ private EqualSizeJButton[] group; public void setGroup(EqualSizeJButton[] group) { this.group = group; } /** * Returns the actual preferred size on a different instance of this button */ private Dimension getRealPreferredSize() { return super.getPreferredSize(); } /** * If the <code>preferredSize</code> has been set to a * non-<code>null</code> value just returns it. * If the UI delegate's <code>getPreferredSize</code> * method returns a non <code>null</code> value then return that; * otherwise defer to the component's layout manager. * * @return the value of the <code>preferredSize</code> property * @see #setPreferredSize * @see ComponentUI */ public Dimension getPreferredSize() { int width = 0; int height = 0; for(int iter = 0 ; iter < group.length ; iter++) { Dimension size = group[iter].getRealPreferredSize(); width = Math.max(size.width, width); height = Math.max(size.height, height); } return new Dimension(width, height); } } }
package org.mtransit.parser.ca_strathcona_county_transit_bus; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class StrathconaCountyTransitBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-strathcona-county-transit-bus-android/res/raw/"; args[2] = ""; // files-prefix } new StrathconaCountyTransitBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating Strathcona County Transit bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating Strathcona County Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludingAll() { return this.serviceIds != null && this.serviceIds.isEmpty(); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeRoute(GRoute gRoute) { return super.excludeRoute(gRoute); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } private static final Pattern DIGITS = Pattern.compile("[\\d]+"); private static final String A = "A"; private static final String B = "B"; private static final long RID_EW_A = 10_000L; private static final long RID_EW_B = 20_000L; @Override public long getRouteId(GRoute gRoute) { if (Utils.isDigitsOnly(gRoute.getRouteShortName())) { return Long.parseLong(gRoute.getRouteShortName()); } Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName()); if (matcher.find()) { long id = Long.parseLong(matcher.group()); if (gRoute.getRouteShortName().endsWith(A)) { return RID_EW_A + id; } else if (gRoute.getRouteShortName().endsWith(B)) { return RID_EW_B + id; } } System.out.printf("\nUnexpected route ID %s!\n", gRoute); System.exit(-1); return -1l; } private static final String SLASH = " / "; private static final String BETHEL = "Bethel"; private static final String BETHEL_TT = BETHEL + " TT"; private static final String ORDZE_TC = "Ordze TC"; private static final String DOWNTOWN = "Downtown"; private static final String DAB = "Dial-A-Bus"; private static final String EDM_CITY_CTR = "Edm City Ctr"; private static final String GOV_CTR = "Gov Ctr"; private static final String NAIT = "NAIT"; private static final String GOV_CTR_NAIT = GOV_CTR + SLASH + NAIT; private static final String U_OF_ALBERTA = "U of Alberta"; private static final String MILLENNIUM_PLACE = "Millennium Pl"; private static final String EMERALD_HILLS = "Emerald Hls"; private static final String ABJ = "ABJ Sch"; private static final String EMERALD_HILLS_ABJ = EMERALD_HILLS + SLASH + ABJ; private static final String SUMMERWOOD = "Summerwood"; private static final String CLARKDALE = "Clarkdale"; private static final String HERITAGE_HILLS = "Heritage Hls"; private static final String NOTTINGHAM = "Nottingham"; private static final String BRENTWOOD = "Brentwood"; private static final String GLEN_ALLAN = "Glen Allan"; private static final String VILLAGE = "Village"; private static final String BROADMOOR = "Broadmoor"; private static final String CITP = "Ctr in the Park"; private static final String REGENCY = "Regency"; private static final String RLN_401 = ORDZE_TC + " - " + EDM_CITY_CTR; private static final String RLN_403 = ORDZE_TC + " - " + GOV_CTR; private static final String RLN_404 = ORDZE_TC + " - " + U_OF_ALBERTA; private static final String RLN_411 = BETHEL_TT + " - " + EDM_CITY_CTR; private static final String RLN_413 = BETHEL_TT + " - " + GOV_CTR_NAIT; private static final String RLN_414 = BETHEL_TT + " - " + U_OF_ALBERTA; private static final String RLN_420 = BETHEL_TT + " - " + MILLENNIUM_PLACE; private static final String RLN_430 = BETHEL_TT + " - " + EMERALD_HILLS + " CW"; private static final String RLN_431 = BETHEL_TT + " - " + EMERALD_HILLS + " CCW"; private static final String RLN_432 = BETHEL_TT + " -" + SUMMERWOOD; private static final String RLN_433 = BETHEL_TT + " - " + CLARKDALE; private static final String RLN_441A = BETHEL_TT + " - " + REGENCY; private static final String RLN_433A = CLARKDALE + " - " + ABJ; private static final String RLN_440 = BETHEL_TT + " - " + HERITAGE_HILLS; private static final String RLN_441 = BETHEL_TT + " - " + ORDZE_TC + " - Regency"; private static final String RLN_442 = BETHEL_TT + " - " + NOTTINGHAM; private static final String RLN_443 = BETHEL_TT + " - " + ORDZE_TC + " - Glen Allan"; private static final String RLN_443A = BETHEL_TT + " - " + BRENTWOOD; private static final String RLN_443B = BETHEL_TT + " - " + GLEN_ALLAN; private static final String RLN_450 = BETHEL_TT + " - " + CITP; private static final String RLN_451 = BETHEL_TT + " - " + ORDZE_TC + " - Mills Haven / Westboro"; private static final String RLN_451A = BETHEL_TT + " - Woodbridge"; private static final String RLN_451B = BETHEL_TT + " - Mills Haven"; private static final String RLN_490 = DAB + " A"; private static final String RLN_491 = DAB + " B"; private static final String RLN_492 = DAB + " C"; private static final String RLN_493 = DAB + " D"; private static final String RLN_494 = DAB + " E"; private static final String RLN_495 = DAB + " F"; @Override public String getRouteLongName(GRoute gRoute) { if (StringUtils.isEmpty(gRoute.getRouteLongName())) { if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) { // @formatter:off if (RSN_441A.equals(gRoute.getRouteShortName())) { return RLN_441A; } else if (RSN_433A.equals(gRoute.getRouteShortName())) { return RLN_433A; } else if (RSN_443A.equals(gRoute.getRouteShortName())) { return RLN_443A; } else if (RSN_443B.equals(gRoute.getRouteShortName())) { return RLN_443B; } else if (RSN_451A.equals(gRoute.getRouteShortName())) { return RLN_451A; } else if (RSN_451B.equals(gRoute.getRouteShortName())) { return RLN_451B; // @formatter:on } else { System.out.printf("\nUnexpected route long name %s!\n", gRoute); System.exit(-1); return null; } } int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 401: return RLN_401; case 403: return RLN_403; case 404: return RLN_404; case 411: return RLN_411; case 413: return RLN_413; case 414: return RLN_414; case 420: return RLN_420; case 430: return RLN_430; case 431: return RLN_431; case 432: return RLN_432; case 433: return RLN_433; case 440: return RLN_440; case 441: return RLN_441; case 442: return RLN_442; case 443: return RLN_443; case 450: return RLN_450; case 451: return RLN_451; case 490: return RLN_490; case 491: return RLN_491; case 492: return RLN_492; case 493: return RLN_493; case 494: return RLN_494; case 495: return RLN_495; // @formatter:on default: System.out.printf("\nUnexpected route long name %s!\n", gRoute); System.exit(-1); return null; } } return cleanRouteLongName(gRoute); } private String cleanRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); routeLongName = CleanUtils.cleanSlashes(routeLongName); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "559820"; // GREEN (from map PDF) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } private static final String RSN_441A = "441A"; private static final String RSN_433A = "433A"; private static final String RSN_443A = "443A"; private static final String RSN_443B = "443B"; private static final String RSN_451A = "451A"; private static final String RSN_451B = "451B"; private static final String COLOR_ED0E58 = "ED0E58"; private static final String COLOR_231F20 = "231F20"; private static final String COLOR_00A34E = "00A34E"; private static final String COLOR_6E6EAB = "6E6EAB"; private static final String COLOR_D04CAE = "D04CAE"; private static final String COLOR_F78F20 = "F78F20"; private static final String COLOR_9F237E = "9F237E"; private static final String COLOR_FFC745 = "FFC745"; private static final String COLOR_6BC7B9 = "6BC7B9"; private static final String COLOR_0076BC = "0076BC"; private static final String COLOR_F16278 = "F16278"; private static final String COLOR_ED1C24 = "ED1C24"; private static final String COLOR_FFF30C = "FFF30C"; private static final String COLOR_08796F = "08796F"; private static final String COLOR_652290 = "652290"; private static final String COLOR_7BC928 = "7BC928"; private static final String COLOR_832B30 = "832B30"; private static final String COLOR_2E3192 = "2E3192"; private static final String COLOR_006A2F = "006A2F"; private static final String COLOR_EC008C = "EC008C"; private static final String COLOR_F57415 = "F57415"; private static final String COLOR_1270BB = "1270BB"; private static final String COLOR_ED2D32 = "ED2D32"; private static final String COLOR_0F6B3B = "0F6B3B"; private static final String COLOR_61CACA = "61CACA"; private static final String COLOR_E59A12 = "E59A12"; @Override public String getRouteColor(GRoute gRoute) { if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) { // @formatter:off if (RSN_441A.equals(gRoute.getRouteShortName())) { return COLOR_832B30; } else if (RSN_433A.equals(gRoute.getRouteShortName())) { return COLOR_ED0E58; } else if (RSN_443A.equals(gRoute.getRouteShortName())) { return COLOR_231F20; } else if (RSN_443B.equals(gRoute.getRouteShortName())) { return COLOR_00A34E; } else if (RSN_451A.equals(gRoute.getRouteShortName())) { return COLOR_6E6EAB; } else if (RSN_451B.equals(gRoute.getRouteShortName())) { return COLOR_D04CAE; // @formatter:on } else { System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } } int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 401: return COLOR_F78F20; case 403: return COLOR_9F237E; case 404: return COLOR_FFC745; case 411: return COLOR_6BC7B9; case 413: return COLOR_0076BC; case 414: return COLOR_F16278; case 420: return COLOR_ED1C24; case 430: return COLOR_2E3192; case 431: return COLOR_FFF30C; case 432: return COLOR_08796F; case 433: return COLOR_652290; case 440: return COLOR_7BC928; case 441: return COLOR_832B30; case 442: return COLOR_2E3192; case 443: return COLOR_006A2F; case 450: return COLOR_EC008C; case 451: return COLOR_F57415; case 490: return COLOR_1270BB; case 491: return COLOR_ED2D32; case 492: return COLOR_0F6B3B; case 493: return COLOR_61CACA; case 494: return COLOR_E59A12; case 495: return null; // @formatter:on default: System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } } @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } mTrip.setHeadsignString(cleanTripHeadsign(gTrip.getTripHeadsign()), gTrip.getDirectionId()); } @Override public boolean mergeHeadsign(MTrip mTrip, MTrip mTripToMerge) { System.out.printf("\nUnexpected trips to merge: %s & %s!\n", mTrip, mTripToMerge); System.exit(-1); return false; } private static final Pattern TRANSIT_TERMINAL = Pattern.compile("(transit terminal)", Pattern.CASE_INSENSITIVE); private static final String TRANSIT_TERMINAL_REPLACEMENT = "TT"; private static final Pattern TRANSIT_CENTER = Pattern.compile("(transit (center|centre))", Pattern.CASE_INSENSITIVE); private static final String TRANSIT_CENTER_REPLACEMENT = "TC"; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = TRANSIT_TERMINAL.matcher(tripHeadsign).replaceAll(TRANSIT_TERMINAL_REPLACEMENT); tripHeadsign = TRANSIT_CENTER.matcher(tripHeadsign).replaceAll(TRANSIT_CENTER_REPLACEMENT); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); map2.put(401L, new RouteTripSpec(401L, 0, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC, 1, MTrip.HEADSIGN_TYPE_STRING, DOWNTOWN) .addTripSort(0, Arrays.asList(new String[] { "1973", // 107 St & 104 Av "1292", "4000", // Ordze Transit Centre })) .addTripSort(1, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "1457", "1973", // 107 St & 104 Av })) .compileBothTripSort()); map2.put(403L, new RouteTripSpec(403L, 0, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC, 1, MTrip.HEADSIGN_TYPE_STRING, GOV_CTR) .addTripSort(0, Arrays.asList(new String[] { "1732", // 107 St & 103 Av "1629", "4000", // Ordze Transit Centre })) .addTripSort(1, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "1794", "1973", // 107 St & 104 Av })) .compileBothTripSort()); map2.put(404L, new RouteTripSpec(404L, 0, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC, 1, MTrip.HEADSIGN_TYPE_STRING, U_OF_ALBERTA) .addTripSort(0, Arrays.asList(new String[] { "2636", // University Transit Centre "2722", "4000", // Ordze Transit Centre })) .addTripSort(1, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "2752", "2638", // 114 St & 85 Av "2625", "2636", // University Transit Centre })) .compileBothTripSort()); map2.put(411L, new RouteTripSpec(411L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, DOWNTOWN) .addTripSort(0, Arrays.asList(new String[] { "1973", // 107 St & 104 Av "1292", // 100 St & 102A Av "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "2289", "1973", // 107 St & 104 Av })) .compileBothTripSort()); map2.put(413L, new RouteTripSpec(413L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, GOV_CTR_NAIT) .addTripSort(0, Arrays.asList(new String[] { "1223", // NAIT 106 St & 117 Av "1973", // <> GOV 107 St & 104 Av "1732", // GOV 107 St & 103 Av "1643", "1629", "8005", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8004", "1728", "1898", "1973", // <> GOV 107 St & 104 Av "1227", // NAIT 106 St & 117 Av })) .compileBothTripSort()); map2.put(414L, new RouteTripSpec(414L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, U_OF_ALBERTA) .addTripSort(0, Arrays.asList(new String[] { "2636", // University Transit Centre "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "2636", // University Transit Centre })) .compileBothTripSort()); map2.put(420L, new RouteTripSpec(420L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, MILLENNIUM_PLACE) .addTripSort(0, Arrays.asList(new String[] { "8800", // Premier Wy & Millennium Place "8811", // Strathmoor Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8700", "8800", // Premier Wy & Millennium Place })) .compileBothTripSort()); map2.put(430L, new RouteTripSpec(430L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, EMERALD_HILLS_ABJ) .addTripSort(0, Arrays.asList(new String[] { "7921", // Emerald Dr & ABJ "7436", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8304", "7921", // Emerald Dr & ABJ })) .compileBothTripSort()); map2.put(431L, new RouteTripSpec(431L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, EMERALD_HILLS) // EMERALD_HILLS_ABJ .addTripSort(0, Arrays.asList(new String[] { "7920", // Emerald Dr & ABJ "8849", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "7437", // Dawson Dr & Donnely Terr "7920", // Emerald Dr & ABJ })) .compileBothTripSort()); map2.put(432L, new RouteTripSpec(432L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, SUMMERWOOD) .addTripSort(0, Arrays.asList(new String[] { "7870", // Lakeland Dr & Aspen Tr "7508", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8304", "7870", // Lakeland Dr & Aspen Tr })) .compileBothTripSort()); map2.put(433L, new RouteTripSpec(433L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, "Davidson Crk") // SUMMERWOOD .addTripSort(0, Arrays.asList(new String[] { "7272", // Primrose Blvd & Clover Bar Rd "7431", // Davidson Dr & Darlington Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8135", "7272", // Primrose Blvd & Clover Bar Rd })) .compileBothTripSort()); map2.put(433L + RID_EW_A, new RouteTripSpec(433L + RID_EW_A, // 433A 0, MTrip.HEADSIGN_TYPE_STRING, "Charlton Hts", // CLOVER_BAR, // 1, MTrip.HEADSIGN_TYPE_STRING, ABJ) .addTripSort(0, Arrays.asList(new String[] { "7921", // Emerald Dr & ABJ "7330", "8114", // Jim Common Dr & Crystal Ln })) .addTripSort(1, Arrays.asList(new String[] { "8113", // Jim Common Dr & Crystal Ln "7319", "7920", // Emerald Dr & ABJ })) .compileBothTripSort()); map2.put(440L, new RouteTripSpec(440L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, HERITAGE_HILLS) .addTripSort(0, Arrays.asList(new String[] { "8000", // != xx Bethel Transit Terminal #WTF! "7199", // Highland Wy & Heritage Dr "7124", // == Highland Dr & Heritage Lake Wy "7011", "1068", "7102", "8000", // xx Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // == Bethel Transit Terminal "1090", "7024", "7199", // == Highland Wy & Heritage Dr })) .compileBothTripSort()); map2.put(441L, new RouteTripSpec(441L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC) .addTripSort(0, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "9157", // Ritchie Wy & Regency Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "9240", // Foxhaven Dr & Foxhaven Pl "9115", // Ritchie Wy & Rainbow Cr "4939", // Salisbury Way & Mitchell St "4000", // Ordze Transit Centre })) .compileBothTripSort()); map2.put(441L + RID_EW_A, new RouteTripSpec(441L + RID_EW_A, // 441A 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, REGENCY) .addTripSort(0, Arrays.asList(new String[] { "9115", // != Ritchie Wy & Rainbow Cr <= "9157", // != Ritchie Wy & Regency Dr <= "9239", // != Foxhaven Dr & Foxhaven Ct "9160", // == Clover Bar Rd & Foxhaven Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "9150", // == Foxhaven Dr & Foxhaven Pl "9240", // != Foxhaven Dr & Foxhaven Pl "9115", // != Ritchie Wy & Rainbow Cr => "9157", // != Ritchie Wy & Regency Dr => })) .compileBothTripSort()); map2.put(442L, new RouteTripSpec(442L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, NOTTINGHAM) .addTripSort(0, Arrays.asList(new String[] { "9015", // Nottingham Blvd & Nottingham Rd "9180", // Granada Blvd & Forrest Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "1002", "9015", // Nottingham Blvd & Nottingham Rd })) .compileBothTripSort()); map2.put(443L, new RouteTripSpec(443L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC) .addTripSort(0, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "6012", // Fir St & Willow St "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "1088", // Gatewood Blvd & Galaxy Wy "6065", // Fir St & Willow St "4000", // Ordze Transit Centre })) .compileBothTripSort()); map2.put(443L + RID_EW_A, new RouteTripSpec(443L + RID_EW_A, // 443A 0, MTrip.HEADSIGN_TYPE_STRING, "AM", 1, MTrip.HEADSIGN_TYPE_STRING, "PM") .addTripSort(0, Arrays.asList(new String[] { "8000", // xx Bethel Transit Terminal "1013", "2001", "6035", // Oak St & Conifer St "6126", "1009", "1011", "8000", // xx Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // xx Bethel Transit Terminal "1013", "6079", "6115", "2000", // Festival Ln & Festival Av "1011", "8000", // xx Bethel Transit Terminal })) .compileBothTripSort()); map2.put(443L + RID_EW_B, new RouteTripSpec(443L + RID_EW_B, // 443B 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, CITP) // Glen Allan .addTripSort(0, Arrays.asList(new String[] { "6048", // Oak St & Sherwood Dr "1024", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "1033", "6029", // Oak St & Glenmore Av })) .compileBothTripSort()); map2.put(450L, new RouteTripSpec(450L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, CITP) .addTripSort(0, Arrays.asList(new String[] { "2001", // Festival Ln & Festival Av "6072", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8105", "2001", // Festival Ln & Festival Av })) .compileBothTripSort()); map2.put(451L, new RouteTripSpec(451L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC) .addTripSort(0, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "5040", // Village Dr & Village Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "5005", // Main Blvd & Mardale Cr "5115", // Village Dr & Village Dr "4000", // Ordze Transit Centre })) .compileBothTripSort()); map2.put(451L + RID_EW_A, new RouteTripSpec(451L + RID_EW_A, // 451A 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, VILLAGE) .addTripSort(0, Arrays.asList(new String[] { "5040", // Village Dr & Village Dr "5078", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "5083", "5115", // Village Dr & Village Dr })) .compileBothTripSort()); map2.put(451L + RID_EW_B, new RouteTripSpec(451L + RID_EW_B, // 451B 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, BROADMOOR) .addTripSort(0, Arrays.asList(new String[] { "5041", // Kaska Rd Chippewa Rd "5138", "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "5005", // Main Blvd & Mardale Cr "5041", // Kaska Rd Chippewa Rd })) .compileBothTripSort()); map2.put(490L, new RouteTripSpec(490L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, MILLENNIUM_PLACE) .addTripSort(0, Arrays.asList(new String[] { "8800", // == Premier Wy & Millennium Place "8806", // Premier Wy & Prairie Dr "8812", // Strathmoor Dr "8814", // Streambank Av "8803", // Prairie Dr & Premier Wy "7526", // Summerland Dr & Lakeland Dr "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // Bethel Transit Terminal "8816", // != Streambank Av => "8010", // != Broadway Blvd at Robin Hood CONTINUE "8700", "8800", // == Premier Wy & Millennium Place })) .compileBothTripSort()); map2.put(491L, new RouteTripSpec(491L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, SUMMERWOOD) .addTripSort(0, Arrays.asList(new String[] { "7807", // Clover Bar Rd & Jubilee Dr "7508", // Summerwood Blvd & Clover Bar Rd "7406", // Davidson Dr & Darlington Dr "7312", // Meadowview Dr & Clarkdale Dr "7229", // Primrose Blvd & Clover Bar Rd "8138", // Summerwood Blvd & Clover Bar Rd "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // == Bethel Transit Terminal "8010", // != Broadway Blvd at Robin Hood "8816", // != Streambank Av => "8101", // != Bethel Dr & Broadview Rd "7604", // Jim Common Dr & Cache Pl "7807", // Clover Bar Rd & Jubilee Dr })) .compileBothTripSort()); map2.put(492L, new RouteTripSpec(492L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, REGENCY) .addTripSort(0, Arrays.asList(new String[] { "9157", // Ritchie Wy & Regency Dr "9225", // Regency Dr & Ridgeland Cr "7199", // Highland Wy & Heritage Dr "7011", // Craigavon Dr & Carmel Rd "1042", // Galloway Dr & Glengarry Cr "1052", // Georgian Wy "1001", // Sherwood Dr & Granada Blvd "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // == Bethel Transit Terminal "8010", // != Broadway Blvd at Robin Hood "8816", // != Streambank Av => "8101", // != Broadway Blvd at Robin Hood "1002", // Sherwood Dr & Oak St "9015", // Nottingham Blvd & Nottingham Rd "9157", // Ritchie Wy & Regency Dr })) .compileBothTripSort()); map2.put(493L, new RouteTripSpec(493L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, BRENTWOOD) .addTripSort(0, Arrays.asList(new String[] { "6097", // Alder Av & Alderwood Cr "6115", // Alder Av & Ivy Cr "6065", // Fir St & Willow St "6048", // Oak St & Sherwood Dr "1004", // Sherwood Dr & Oak St "1090", // Galloway Dr & Glenbrook Blvd "7006", // Glencoe Blvd & Courtenay By "8111", // Sherwood Dr & Cranford Wy "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // == Bethel Transit Terminal "8010", // != Broadway Blvd at Robin Hood "8816", // != Streambank Av => "8101", // != Broadway Blvd at Robin Hood "7011", // Fir St & Willow St "1042", // Galloway Dr & Glengarry Cr "1071", // Georgian Wy & Glenbrook Blvd "2001", // Festival Ln & Festival Av "6079", // Raven Dr & Crane Rd "6091", // Heron Rd & Falcon Dr "6097", // Alder Av & Alderwood Cr })) .compileBothTripSort()); map2.put(494L, new RouteTripSpec(494L, 0, MTrip.HEADSIGN_TYPE_STRING, BETHEL_TT, 1, MTrip.HEADSIGN_TYPE_STRING, ORDZE_TC) // Woodbridge .addTripSort(0, Arrays.asList(new String[] { "4000", // Ordze Transit Centre "6012", // Fir St & Willow St "9353", // Clover Bar Rd & Wye Rd "9180", // Granada Blvd & Forrest Dr "1001", // Sherwood Dr & Granada Blvd "1004", // != Sherwood Dr & Oak St "5005", // <> Main Blvd & Mardale Cr "5023", // <> Main Blvd & Marion Dr "4036", // <> Broadmoor Blvd & Main Blvd "8013", // != Broadview Rd & Broadmoor Blvd "8000", // Bethel Transit Terminal })) .addTripSort(1, Arrays.asList(new String[] { "8000", // == Bethel Transit Terminal "8010", // != Broadway Blvd at Robin Hood "8816", // != Streambank Av => "1013", // != Sherwood Dr & Baseline Rd "1014", // != Sherwood Dr & Main Blvd "5005", // <> Main Blvd & Mardale Cr "5011", // != Main Blvd & Millers Rd "5023", // <> Main Blvd & Marion Dr "4036", // <> Broadmoor Blvd & Main Blvd "5041", // != Kaska Rd Chippewa Rd "5065", // Broadmoor Blvd & Sioux Rd "5089", // Haythorne Rd & Haythorne Pl "5115", // Village Dr & Village Dr "4000", // Ordze Transit Centre })) .compileBothTripSort()); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } @Override public String cleanStopName(String gStopName) { gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); return CleanUtils.cleanLabel(gStopName); } @Override public String getStopCode(GStop gStop) { if ("0".equals(gStop.getStopCode())) { return null; } return super.getStopCode(gStop); } }
package com.softwareonpurpose.gauntlet; import com.softwareonpurpose.gauntlet.anobject.AnObject; import com.softwareonpurpose.gauntlet.anobject.AnObjectCalibrator; import com.softwareonpurpose.gauntlet.anobject.AnObjectExpected; import org.testng.Assert; import org.testng.annotations.Test; @Test(groups={GauntletTest.TestSuite.UNIT}) public class VerifyCountSingleTestSingleExecNodeCalibratorTest extends GauntletTest { public void verificationCount_singleTestMethodExecution() { AnObjectExpected expectedObject = AnObjectExpected.getInstance(); AnObject actualObject = AnObject.getInstance(); AnObjectCalibrator calibrator = AnObjectCalibrator.getInstance(expectedObject, actualObject); long expected = 3; then(calibrator); long actual = getVerificationCount(); Assert.assertEquals(actual, expected, "FAILED to calculate accurate verification count"); } }
package org.pentaho.platform.dataaccess.datasource.wizard.service.impl; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; import junit.framework.Assert; import org.junit.*; import org.pentaho.agilebi.modeler.ModelerWorkspace; import org.pentaho.agilebi.modeler.gwt.GwtModelerWorkspaceHelper; import org.pentaho.agilebi.modeler.util.TableModelerSource; import org.pentaho.database.model.IDatabaseConnection; import org.pentaho.di.core.KettleEnvironment; import org.pentaho.di.core.Props; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.olap.OlapDimension; import org.pentaho.metadata.repository.IMetadataDomainRepository; import org.pentaho.platform.api.data.IDBDatasourceService; import org.pentaho.platform.api.engine.IAuthorizationPolicy; import org.pentaho.platform.api.engine.IPentahoDefinableObjectFactory; import org.pentaho.platform.api.engine.IPentahoSession; import org.pentaho.platform.api.engine.IPluginResourceLoader; import org.pentaho.platform.api.engine.ISecurityHelper; import org.pentaho.platform.api.engine.ISolutionEngine; import org.pentaho.platform.api.engine.IUserRoleListService; import org.pentaho.platform.api.repository.IClientRepositoryPathsStrategy; import org.pentaho.platform.api.repository.datasource.DatasourceMgmtServiceException; import org.pentaho.platform.api.repository.datasource.DuplicateDatasourceException; import org.pentaho.platform.api.repository.datasource.IDatasourceMgmtService; import org.pentaho.platform.api.repository.datasource.NonExistingDatasourceException; import org.pentaho.platform.api.repository2.unified.IUnifiedRepository; import org.pentaho.platform.api.repository2.unified.RepositoryFile; import org.pentaho.platform.engine.core.system.PentahoSessionHolder; import org.pentaho.platform.engine.core.system.PentahoSystem; import org.pentaho.platform.engine.core.system.SystemSettings; import org.pentaho.platform.engine.core.system.boot.PlatformInitializationException; import org.pentaho.platform.engine.services.connection.datasource.dbcp.JndiDatasourceService; import org.pentaho.platform.engine.services.solution.SolutionEngine; import org.pentaho.platform.plugin.action.mondrian.catalog.IMondrianCatalogService; import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper; import org.pentaho.platform.plugin.action.mondrian.mapper.MondrianOneToOneUserRoleListMapper; import org.pentaho.platform.plugin.services.connections.mondrian.MDXConnection; import org.pentaho.platform.plugin.services.connections.mondrian.MDXOlap4jConnection; import org.pentaho.platform.plugin.services.connections.sql.SQLConnection; import org.pentaho.platform.plugin.services.importer.MetadataImportHandler; import org.pentaho.platform.plugin.services.importer.MondrianImportHandler; import org.pentaho.platform.plugin.services.importer.PlatformImportException; import org.pentaho.platform.plugin.services.importer.RepositoryFileImportBundle; import org.pentaho.platform.plugin.services.importer.mimeType.MimeType; import org.pentaho.platform.plugin.services.metadata.IPentahoMetadataDomainRepositoryExporter; import org.pentaho.platform.plugin.services.metadata.IPentahoMetadataDomainRepositoryImporter; import org.pentaho.platform.plugin.services.metadata.PentahoMetadataDomainRepository; import org.pentaho.platform.plugin.services.pluginmgr.PluginClassLoader; import org.pentaho.platform.plugin.services.pluginmgr.PluginResourceLoader; import org.pentaho.platform.repository2.unified.RepositoryUtils; import org.pentaho.platform.repository2.unified.fs.FileSystemBackedUnifiedRepository; import org.pentaho.test.platform.engine.core.MicroPlatform; import org.pentaho.test.platform.engine.security.MockSecurityHelper; import org.springframework.dao.DataAccessException; import org.springframework.security.GrantedAuthority; import org.springframework.security.GrantedAuthorityImpl; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.userdetails.User; import org.springframework.security.userdetails.UserDetails; import org.springframework.security.userdetails.UserDetailsService; import org.springframework.security.userdetails.UsernameNotFoundException; public class DatasourceResourceTest { private static MicroPlatform mp; @BeforeClass public static void setUp() throws Exception { System.setProperty( "org.osjava.sj.root", "test-res/solution1/system/simple-jndi" ); //$NON-NLS-1$ //$NON-NLS-2$ mp = new MicroPlatform( "test-res/solution1" ); IAuthorizationPolicy mockAuthorizationPolicy = mock( IAuthorizationPolicy.class ); when( mockAuthorizationPolicy.isAllowed( anyString() ) ).thenReturn( true ); IUserRoleListService mockUserRoleListService = mock( IUserRoleListService.class ); mp.define( ISolutionEngine.class, SolutionEngine.class, IPentahoDefinableObjectFactory.Scope.GLOBAL ); mp.define( IUnifiedRepository.class, TestFileSystemBackedUnifiedRepository.class, IPentahoDefinableObjectFactory.Scope.GLOBAL ); mp.define( IMondrianCatalogService.class, MondrianCatalogHelper.class, IPentahoDefinableObjectFactory.Scope.GLOBAL ); mp.define( "connection-SQL", SQLConnection.class ); mp.define( "connection-MDX", MDXConnection.class ); mp.define( "connection-MDXOlap4j", MDXOlap4jConnection.class ); mp.define( IDBDatasourceService.class, JndiDatasourceService.class, IPentahoDefinableObjectFactory.Scope.GLOBAL ); mp.define( MDXConnection.MDX_CONNECTION_MAPPER_KEY, MondrianOneToOneUserRoleListMapper.class, IPentahoDefinableObjectFactory.Scope.GLOBAL ); mp.define( IDatasourceMgmtService.class, MockDatasourceMgmtService.class ); mp.define( IClientRepositoryPathsStrategy.class, MockClientRepositoryPathsStrategy.class ); mp.define( ISecurityHelper.class, MockSecurityHelper.class ); mp.define( UserDetailsService.class, MockUserDetailService.class ); mp.define( "singleTenantAdminUserName", "admin" ); mp.defineInstance( IMetadataDomainRepository.class, createMetadataDomainRepository() ); mp.defineInstance( IAuthorizationPolicy.class, mockAuthorizationPolicy ); mp.defineInstance( IPluginResourceLoader.class, new PluginResourceLoader() { protected PluginClassLoader getOverrideClassloader() { return new PluginClassLoader( new File( ".", "test-res/solution1/system/simple-jndi" ), this ); } } ); mp.defineInstance( IUserRoleListService.class, mockUserRoleListService ); mp.setSettingsProvider( new SystemSettings() ); mp.start(); PentahoSessionHolder.setStrategyName( PentahoSessionHolder.MODE_GLOBAL ); SecurityContextHolder.setStrategyName( SecurityContextHolder.MODE_GLOBAL ); } @Before @After public void clearDSWData() { File repoData = new File( "test-res/dsw/etc" ); if ( repoData.exists() && repoData.isDirectory() ) { clearDir( repoData ); } } private void clearDir( File dir ) { if ( dir.isDirectory() ) { for ( File file : dir.listFiles() ) { if ( file.isDirectory() ) { clearDir( file ); } else { file.delete(); } } } } @Test public void DummyTest() throws Exception { } @Test public void testMondrianImportExport() throws Exception { final String domainName = "SalesData"; List<MimeType> mimeTypeList = new ArrayList<MimeType>(); mimeTypeList.add( new MimeType( "Mondrian", "mondrian.xml" ) ); System.setProperty( "org.osjava.sj.root", "test-res/solution1/system/simple-jndi" ); //$NON-NLS-1$ //$NON-NLS-2$ File mondrian = new File( "test-res/dsw/testData/SalesData.mondrian.xml" ); RepositoryFile repoMondrianFile = new RepositoryFile.Builder( mondrian.getName() ).folder( false ).hidden( false ) .build(); RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder() .file( repoMondrianFile ).charSet( "UTF-8" ).input( new FileInputStream( mondrian ) ).mime( "mondrian.xml" ) .withParam( "parameters", "Datasource=Pentaho;overwrite=true" ).withParam( "domain-id", "SalesData" ).build() ; MondrianImportHandler mondrianImportHandler = new MondrianImportHandler( mimeTypeList, PentahoSystem.get( IMondrianCatalogService.class ) ); mondrianImportHandler.importFile( bundle1 ); try { KettleEnvironment.init(); Props.init( Props.TYPE_PROPERTIES_EMPTY ); } catch ( Exception e ) { // may already be initialized by another test } Domain domain = generateModel(); ModelerWorkspace model = new ModelerWorkspace( new GwtModelerWorkspaceHelper() ); model.setModelName( "ORDERS" ); model.setDomain( domain ); model.getWorkspaceHelper().populateDomain( model ); new ModelerService().serializeModels( domain, domainName ); final Response salesData = new DatasourceResource().doGetDSWFilesAsDownload( domainName + ".xmi" ); Assert.assertEquals( salesData.getStatus(), Response.Status.OK.getStatusCode() ); Assert.assertNotNull( salesData.getMetadata() ); Assert.assertNotNull( salesData.getMetadata().getFirst( "Content-Disposition" ) ); Assert.assertEquals( salesData.getMetadata().getFirst( "Content-Disposition" ).getClass(), String.class ); Assert.assertTrue( ( (String) salesData.getMetadata().getFirst( "Content-Disposition" ) ).endsWith( domainName + ".zip\"" ) ); File file = File.createTempFile( domainName, ".zip" ); final FileOutputStream fileOutputStream = new FileOutputStream( file ); ( (StreamingOutput) salesData.getEntity() ).write( fileOutputStream ); fileOutputStream.close(); final ZipFile zipFile = new ZipFile( file ); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while ( entries.hasMoreElements() ) { final ZipEntry zipEntry = entries.nextElement(); Assert.assertTrue( zipEntry.getName().equals( domainName + ".xmi" ) || zipEntry.getName().equals( domainName + ".mondrian.xml" ) ); } zipFile.close(); file.delete(); } @Test public void testMetadataImportExport() throws PlatformInitializationException, IOException, PlatformImportException { List<MimeType> mimeTypeList = new ArrayList<MimeType>(); mimeTypeList.add( new MimeType("Metadata", ".xmi") ); File metadata = new File( "test-res/dsw/testData/metadata.xmi" ); RepositoryFile repoMetadataFile = new RepositoryFile.Builder( metadata.getName() ).folder( false ).hidden( false ) .build(); MetadataImportHandler metadataImportHandler = new MetadataImportHandler( mimeTypeList, (IPentahoMetadataDomainRepositoryImporter) PentahoSystem.get( IMetadataDomainRepository.class ) ); RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder() .file( repoMetadataFile ).charSet( "UTF-8" ).input( new FileInputStream( metadata ) ).mime( ".xmi" ).withParam( "domain-id", "SalesData" ).build() ; metadataImportHandler.importFile( bundle1 ); final Response salesData = new DatasourceResource().doGetDSWFilesAsDownload( "SalesData" ); Assert.assertEquals( salesData.getStatus(), Response.Status.OK.getStatusCode() ); Assert.assertNotNull( salesData.getMetadata() ); Assert.assertNotNull( salesData.getMetadata().getFirst( "Content-Disposition" ) ); Assert.assertEquals( salesData.getMetadata().getFirst( "Content-Disposition" ).getClass(), String.class ); Assert.assertTrue( ( (String) salesData.getMetadata().getFirst( "Content-Disposition" ) ).endsWith( ".xmi\"" ) ); } private static PentahoMetadataDomainRepository createMetadataDomainRepository() throws Exception { IUnifiedRepository repository = new FileSystemBackedUnifiedRepository( "test-res/dsw" ); mp.defineInstance( IUnifiedRepository.class, repository ); Assert.assertNotNull( new RepositoryUtils( repository ).getFolder( "/etc/metadata", true, true, null ) ); Assert.assertNotNull( new RepositoryUtils( repository ).getFolder( "/etc/mondrian", true, true, null ) ); PentahoMetadataDomainRepository pentahoMetadataDomainRepository = new PentahoMetadataDomainRepository( repository ); return pentahoMetadataDomainRepository; } private Domain generateModel() { Domain domain = null; try { DatabaseMeta database = new DatabaseMeta(); database.setDatabaseType( "Hypersonic" ); //$NON-NLS-1$ database.setAccessType( DatabaseMeta.TYPE_ACCESS_JNDI ); database.setDBName( "SampleData" ); //$NON-NLS-1$ database.setName( "SampleData" ); //$NON-NLS-1$ System.out.println( database.testConnection() ); TableModelerSource source = new TableModelerSource( database, "ORDERS", null ); //$NON-NLS-1$ domain = source.generateDomain(); List<OlapDimension> olapDimensions = new ArrayList<OlapDimension>(); OlapDimension dimension = new OlapDimension(); dimension.setName( "test" ); //$NON-NLS-1$ dimension.setTimeDimension( false ); olapDimensions.add( dimension ); domain.getLogicalModels().get( 1 ).setProperty( "olap_dimensions", olapDimensions ); //$NON-NLS-1$ } catch ( Exception e ) { e.printStackTrace(); } return domain; } public static class MockDatasourceMgmtService implements IDatasourceMgmtService { @Override public void init( IPentahoSession arg0 ) { } @Override public String createDatasource( IDatabaseConnection arg0 ) throws DuplicateDatasourceException, DatasourceMgmtServiceException { return null; } @Override public void deleteDatasourceById( String arg0 ) throws NonExistingDatasourceException, DatasourceMgmtServiceException { } @Override public void deleteDatasourceByName( String arg0 ) throws NonExistingDatasourceException, DatasourceMgmtServiceException { } @Override public IDatabaseConnection getDatasourceById( String arg0 ) throws DatasourceMgmtServiceException { return null; } @Override public IDatabaseConnection getDatasourceByName( String arg0 ) throws DatasourceMgmtServiceException { return null; } @Override public List<String> getDatasourceIds() throws DatasourceMgmtServiceException { return null; } @Override public List<IDatabaseConnection> getDatasources() throws DatasourceMgmtServiceException { return null; } @Override public String updateDatasourceById( String arg0, IDatabaseConnection arg1 ) throws NonExistingDatasourceException, DatasourceMgmtServiceException { return null; } @Override public String updateDatasourceByName( String arg0, IDatabaseConnection arg1 ) throws NonExistingDatasourceException, DatasourceMgmtServiceException { return null; } } public static class MockUserDetailService implements UserDetailsService { @Override public UserDetails loadUserByUsername( String name ) throws UsernameNotFoundException, DataAccessException { GrantedAuthority[] auths = new GrantedAuthority[2]; auths[0] = new GrantedAuthorityImpl( "Authenticated" ); auths[1] = new GrantedAuthorityImpl( "Administrator" ); UserDetails user = new User( name, "password", true, true, true, true, auths ); return user; } } public static class TestFileSystemBackedUnifiedRepository extends FileSystemBackedUnifiedRepository { public TestFileSystemBackedUnifiedRepository() { super( "bin/test-solutions/solution" ); } } public static class MockClientRepositoryPathsStrategy implements IClientRepositoryPathsStrategy { @Override public String getEtcFolderName() { return null; } @Override public String getEtcFolderPath() { return null; } @Override public String getHomeFolderName() { return null; } @Override public String getHomeFolderPath() { return null; } @Override public String getPublicFolderName() { return null; } @Override public String getPublicFolderPath() { return null; } @Override public String getRootFolderPath() { return null; } @Override public String getUserHomeFolderName( String arg0 ) { return null; } @Override public String getUserHomeFolderPath( String arg0 ) { return null; } } }
package gov.nih.nci.camod.webapp.util; import gov.nih.nci.camod.Constants; import javax.servlet.http.HttpServletRequest; public class SidebarUtil extends gov.nih.nci.camod.webapp.action.BaseAction { public String findSubMenu( HttpServletRequest request, String jspName ) { System.out.println("<sidebar.jsp> String jspName=" + jspName ); if( jspName.equals("searchSimple.jsp") || jspName.equals("searchHelp.jsp") || jspName.equals("searchAdvanced.jsp") || jspName.equals("searchDrugScreening.jsp") || jspName.equals("searchTableOfContents.jsp") || jspName.equals("searchResultsDrugScreen.jsp") || jspName.equals("searchResults.jsp")) { return "subSearchMenu.jsp"; } else if ( jspName.equals("viewModelCharacteristics.jsp") || jspName.equals("viewSpontaneousMutation.jsp") || jspName.equals("viewTransplantXenograft.jsp") || jspName.equals("viewGenomicSegment.jsp") || jspName.equals("viewTargetedModification.jsp") || jspName.equals("viewInducedMutation.jsp") || jspName.equals("viewEngineeredTransgene.jsp") || jspName.equals("viewGeneticDescription.jsp") || jspName.equals("viewInvivoDetails.jsp") || jspName.equals("viewPublications.jsp") || jspName.equals("viewCarcinogenicInterventions.jsp") || jspName.equals("viewHistopathology.jsp") || jspName.equals("viewTherapeuticApproaches.jsp") || jspName.equals("viewCellLines.jsp") || jspName.equals("viewImages.jsp") || jspName.equals("viewMicroarrays.jsp") ){ String theSubMenu = "subViewModelMenu.jsp"; // For special cases when we don't have an animal model if (request.getSession().getAttribute(Constants.ANIMALMODEL) == null) { theSubMenu = "subSearchMenu.jsp"; } return theSubMenu; } else if ( jspName.equals("adminRoles.jsp") || jspName.equals("helpAdmin.jsp") || jspName.equals("adminModelsAssignment.jsp") || jspName.equals("adminCommentsAssignment.jsp") || jspName.equals("adminRolesAssignment.jsp") || jspName.equals("adminEditUserRoles.jsp") || jspName.equals("adminEditUser.jsp") || jspName.equals("adminUserManagement.jsp") || jspName.equals("helpDesk.jsp") ) { return "subAdminMenu.jsp"; } else if ( jspName.equals("submitOverview.jsp") || jspName.equals("submitAssocExpression.jsp") || jspName.equals("submitAssocMetastasis.jsp") || jspName.equals("submitSpontaneousMutation.jsp") || jspName.equals("submitClinicalMarkers.jsp") || jspName.equals("submitGeneDelivery.jsp") || jspName.equals("submitModelCharacteristics.jsp") || jspName.equals("submitEngineeredTransgene.jsp") || jspName.equals("submitGenomicSegment.jsp") || jspName.equals("submitTargetedModification.jsp") || jspName.equals("submitInducedMutation.jsp") || jspName.equals("submitChemicalDrug.jsp") || jspName.equals("submitEnvironmentalFactors.jsp") || jspName.equals("submitNutritionalFactors.jsp") || jspName.equals("submitGrowthFactors.jsp") || jspName.equals("submitHormone.jsp") || jspName.equals("submitRadiation.jsp") || jspName.equals("submitViralTreatment.jsp")|| jspName.equals("submitTransplantXenograft.jsp") || jspName.equals("submitSurgeryOther.jsp") || jspName.equals("submitPublications.jsp") || jspName.equals("submitHistopathology.jsp")|| jspName.equals("submitCellLines.jsp") || jspName.equals("submitTherapy.jsp") || jspName.equals("submitImages.jsp") || jspName.equals("submitMicroarrayData.jsp") || jspName.equals("submitJacksonLab.jsp") || jspName.equals("submitMMHCCRepo.jsp") || jspName.equals("submitInvestigator.jsp") || jspName.equals("submitIMSR.jsp") ) { return "subSubmitMenu.jsp"; } else if ( jspName.equals("submitModels.jsp") || jspName.equals("submitNewModel.jsp") ) { return "subEmptyMenu.jsp"; } else { return "subEmptyMenu.jsp"; } } }
package info.tregmine.commands; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.bukkit.World; import com.maxmind.geoip.Location; import static org.bukkit.ChatColor.*; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.database.ConnectionPool; import info.tregmine.database.DBPlayerDAO; public class QuitMessageCommand extends AbstractCommand { public QuitMessageCommand(Tregmine tregmine) { super(tregmine, "quitmessage"); } private String argsToMessage(String[] args) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" "); buf.append(args[i]); } return buf.toString(); } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (args.length == 0) { return getownmsg(player); } if (args[0].matches("player") && args[1].matches("get")) { return getelsemsg(player, args); } else if (args[0].matches("player") && args[1].matches("set")) { return setelsemsg(player, args); } else if (args[0].matches("help")) { return help(player, args); } else { return setownmsg(player, args); } } private boolean help(TregminePlayer player, String[] args) { if (player.isAdmin()){ player.sendMessage(DARK_GRAY + " player.sendMessage(GRAY + "Get your Quit Message: " + GREEN + "/quitmessage"); player.sendMessage(GRAY + "Set your Quit Message: " + GREEN + "/quitmessage <message>"); player.sendMessage(GRAY + "Get another player's Quit Message: "); player.sendMessage(GREEN + "/quitmessage player get <player>"); player.sendMessage(GRAY + "Set another player's Quit Message: "); player.sendMessage(GREEN + "/quitmessage player set <player> <message>"); player.sendMessage(DARK_GRAY + " } else if (player.isGuardian()){ player.sendMessage(DARK_GRAY + " player.sendMessage(GRAY + "Get your Quit Message: " + GREEN + "/quitmessage"); player.sendMessage(GRAY + "Set your Quit Message: " + GREEN + "/quitmessage <message>"); player.sendMessage(GRAY + "Get another player's Quit Message: "); player.sendMessage(GREEN + "/quitmessage player get <player>"); player.sendMessage(DARK_GRAY + " } else if (player.isDonator()|| player.isBuilder()){ player.sendMessage(DARK_GRAY + " player.sendMessage(GRAY + "Get your Quit Message: " + GREEN + "/quitmessage"); player.sendMessage(GRAY + "Set your Quit Message: " + GREEN + "/quitmessage <message>"); player.sendMessage(DARK_GRAY + " } else{ player.sendMessage(DARK_GRAY + " player.sendMessage(RED + "Sorry, Quit Messages are only for players who"); player.sendMessage(RED + "donate to keep the server running."); player.sendMessage(DARK_GRAY + " } return true; } private boolean setownmsg(TregminePlayer player, String[] args) { if(!player.isDonator()&&!player.isAdmin()&&!player.isBuilder()&&!player.isGuardian()){ return true; } String message = null; message = argsToMessage(args); player.setQuitMessage(message); player.sendMessage(YELLOW + "Your quit message has been set to:"); player.sendMessage(YELLOW + message); Connection conn = null; try { conn = ConnectionPool.getConnection(); DBPlayerDAO playerDAO = new DBPlayerDAO(conn); playerDAO.updatePlayerInfo(player); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } return true; } private boolean setelsemsg(TregminePlayer player, String[] args) { if (!player.isAdmin()) { return true; } if (args.length == 3 ) { player.sendMessage(RED + "Correct Usage: /quitmessage player set <player> <message>"); return true; } String pattern = args[2]; List<TregminePlayer> candidates = tregmine.matchPlayer(pattern); if (candidates.size() != 1) { return true; } TregminePlayer victim = candidates.get(0); if (victim == null) { return true; } if (victim.isOp()) { player.sendMessage(RED + "Thou shall not mess with the Gods!"); World world = player.getWorld(); org.bukkit.Location location = player.getLocation(); world.strikeLightning(location); return true; } StringBuilder newQuitMessage = new StringBuilder(); for (int i = 3; i < args.length; i++) { newQuitMessage.append(args[i] + " "); } String quitmsgString = newQuitMessage.toString(); quitmsgString.trim(); victim.setQuitMessage(quitmsgString); player.sendMessage(victim.getChatName() + "'s" + YELLOW + " quit message has been set to:"); player.sendMessage(YELLOW + quitmsgString); Connection conn = null; try { conn = ConnectionPool.getConnection(); DBPlayerDAO playerDAO = new DBPlayerDAO(conn); playerDAO.updatePlayerInfo(player); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } return true; } private boolean getelsemsg(TregminePlayer player, String[] args) { if (!player.isAdmin() && !player.isGuardian()) { return true; } if (args.length > 3 ) { player.sendMessage(RED + "Correct Usage: /quitmessage player get <player>"); return true; } String pattern = args[2]; List<TregminePlayer> candidates = tregmine.matchPlayer(pattern); if (candidates.size() != 1) { return true; } TregminePlayer victim = candidates.get(0); if (victim == null) { return true; } String victimName = victim.getChatName(); player.sendMessage(victimName + "'s " + YELLOW + "current Quit Message is:"); player.sendMessage(YELLOW + victim.getQuitMessage()); return true; } private boolean getownmsg(TregminePlayer player) { if(!player.isDonator()&&!player.isAdmin()&&!player.isBuilder()&&!player.isGuardian()){ return true; } player.sendMessage(YELLOW + "Your current Quit Message is:"); player.sendMessage(YELLOW + player.getQuitMessage()); return true; } }
package uk.bl.scope; import java.io.File; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.util.List; import models.LookupEntry; import models.Target; import play.Logger; import uk.bl.Const; import uk.bl.api.Utils; import uk.bl.exception.WhoisException; import uk.bl.wa.whois.JRubyWhois; import uk.bl.wa.whois.WhoisResult; import com.avaje.ebean.Ebean; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; public class Scope { public static final String UK_DOMAIN = ".uk"; public static final String GEO_IP_SERVICE = "GeoLite2-City.mmdb"; public static final String UK_COUNTRY_CODE = "GB"; public static final String HTTP = "http: public static final String HTTPS = "https: public static final String WWW = "www."; public static final String END_STR = "/"; /** * This method queries geo IP from database * @param ip - The host IP * @return true if in UK domain */ public static boolean queryDb(String ip) { boolean res = false; // A File object pointing to your GeoIP2 or GeoLite2 database File database = new File(GEO_IP_SERVICE); try { // This creates the DatabaseReader object, which should be reused across // lookups. DatabaseReader reader = new DatabaseReader.Builder(database).build(); // Find city by given IP CityResponse response = reader.city(InetAddress.getByName(ip)); Logger.info(response.getCountry().getIsoCode()); Logger.info(response.getCountry().getName()); // Check country code in city response if (response.getCountry().getIsoCode().equals(UK_COUNTRY_CODE)) { res = true; } } catch (Exception e) { Logger.warn("GeoIP error. " + e); } return res; } /** * This method normalizes passed URL that it is appropriate for IP calculation. * @param url The passed URL * @return normalized URL */ public static String normalizeUrl(String url) { String res = url; if (res != null && res.length() > 0) { if (!res.contains(WWW)) { res = WWW + res; } if (!res.contains(HTTP)) { if (!res.contains(HTTPS)) { res = HTTP + res; } } if (!res.endsWith(END_STR)) { res = res + END_STR; } } Logger.info("normalized URL: " + res); return res; } /** * This method comprises rule engine for checking if a given URL is in scope. * @return true if in scope * @throws WhoisException */ public static boolean check(String url, String nidUrl) throws WhoisException { boolean res = false; Logger.info("check url: " + url + ", nid: " + nidUrl); url = normalizeUrl(url); /** * Check if given URL is already in project database in a table LookupEntry. * If this is in return associated value, otherwise process lookup using expert rules. */ boolean inProjectDb = false; if (url != null && url.length() > 0) { List<LookupEntry> lookupEntryCount = LookupEntry.filterByName(url); if (lookupEntryCount.size() > 0) { inProjectDb = true; res = LookupEntry.getValueByUrl(url); Logger.info("lookup entry for '" + url + "' is in database with value: " + res); } } if (!inProjectDb) { /** * Rule 1: check manual scope settings because they have more severity. If one of the fields: * * Rule 1.1: "field_uk_domain" * Rule 1.2: "field_uk_postal_address" * Rule 1.3: "field_via_correspondence" * Rule 1.4: "field_professional_judgement" * * is true - checking result is positive. * * Rule 1.5: if the field "field_no_ld_criteria_met" is true - checking result is negative * */ // read Target fields with manual entries and match to the given NID URL (Rules 1.1 - 1.5) if (nidUrl != null && nidUrl.length() > 0) { if (!res) { res = Target.checkManualScope(nidUrl); } } if (!res && nidUrl != null && nidUrl.length() > 0) { res = Target.checkLicense(nidUrl); } // Rule 3.1: check domain name if (!res && url != null && url.length() > 0) { if (url.contains(UK_DOMAIN)) { res = true; } } // Rule 3.2: check geo IP if (!res && url != null && url.length() > 0) { res = checkGeoIp(url); } // Rule 3.3: check whois lookup service if (!res && url != null && url.length() > 0) { res = checkWhois(url); } // store in project DB storeInProjectDb(url, res); } Logger.info("lookup entry for '" + url + "' is in database with value: " + res); return res; } /** * This method extracts host from the given URL and checks geo IP using geo IP database. * @param url * @return true if in UK domain */ public static boolean checkGeoIp(String url) { boolean res = false; String ip = getIpFromUrl(url); res = queryDb(ip); return res; } /** * This method extracts domain name from the given URL and checks country or country code * in response using whois lookup service. * @param url * @return true if in UK domain * @throws WhoisException */ public static boolean checkWhois(String url) throws WhoisException { boolean res = false; try { JRubyWhois whoIs = new JRubyWhois(); Logger.info("checkWhois: " + whoIs + " " + url); WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl(url)); Logger.info("whoIsRes: " + whoIsRes); // WhoisResult whoIsRes = whoIs.lookup(getDomainFromUrl("marksandspencer.com")); res = whoIsRes.isUKRegistrant(); Logger.info("isUKRegistrant?: " + res); } catch (Exception e) { Logger.info("whois lookup message: " + e.getMessage()); throw new WhoisException(e); } Logger.info("whois res: " + res); return res; } /** * This method saves result of scope lookup for given URL if it is * not yet in a project database. * @param url The search URL * @param res The evaluated result after checking by expert rules */ public static void storeInProjectDb(String url, boolean res) { LookupEntry lookupEntry = new LookupEntry(); lookupEntry.id = Utils.createId(); lookupEntry.url = Const.ACT_URL + lookupEntry.id; lookupEntry.name = url; lookupEntry.value = res; Logger.info("Save lookup entry " + lookupEntry.toString()); Ebean.save(lookupEntry); } /** * This method converts URL to IP address. * @param url * @return IP address as a string */ public static String getIpFromUrl(String url) { String ip = ""; InetAddress address; try { address = InetAddress.getByName(new URL(url).getHost()); ip = address.getHostAddress(); } catch (UnknownHostException e) { Logger.info("ip calculation unknown host error for url=" + url + ". " + e.getMessage()); } catch (MalformedURLException e) { Logger.info("ip calculation error for url=" + url + ". " + e.getMessage()); } return ip; } /** * This method extracts domain name from the given URL. * @param url * @return */ public static String getDomainFromUrl(String url) { String domain = ""; try { // Logger.info("get host: " + new URL(url).getHost()); domain = new URL(url).getHost().replace(WWW, ""); Logger.info("whois lookup for domain: " + domain); } catch (Exception e) { Logger.info("domain calculation error for url=" + url + ". " + e.getMessage()); domain = url; } return domain; } }
package utilities; import java.sql.Timestamp; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; public class General { public static boolean validateEmail(String email) { try { String regex = "/^((([a-z]|\\d|[! email.matches(regex); return true; } catch (Exception e) { return false; } } public static boolean validateName(String name) { try { String regex = "/^[0-9a-zA-Z]{6,20}$/"; name.matches(regex); return true; } catch (Exception e) { return false; } } public static boolean validatePassword(String password) { try { String regex = "/^[0-9a-zA-Z]{6,20}$/"; password.matches(regex); return true; } catch (Exception e) { return false; } } public static Timestamp now() { return new java.sql.Timestamp(localCalendar().getTimeInMillis()); } public static Calendar localCalendar() { return new GregorianCalendar(TimeZone.getTimeZone("GMT+8")); // should match mysql setting `/etc/my.cnf` } }
package io.spine.tools.validate.field; import io.spine.code.proto.FieldDeclaration; import io.spine.tools.validate.code.Expression; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.tools.validate.code.Expression.formatted; import static java.util.Optional.empty; public final class FieldValidatorFactories { private final Expression messageAccess; public FieldValidatorFactories(Expression messageAccess) { this.messageAccess = checkNotNull(messageAccess); } public FieldValidatorFactory forField(FieldDeclaration field) { if (!field.isCollection()) { return forScalarField(field); } else { return onViolation -> empty(); } } private FieldValidatorFactory forScalarField(FieldDeclaration field) { Expression fieldAccess = formatted("%s.get%s()", messageAccess, field.name().toCamelCase()); switch (field.javaType()) { case STRING: return new StringFieldValidatorFactory(field, fieldAccess); case INT: case LONG: case FLOAT: case DOUBLE: return new NumberFieldValidatorFactory(field, fieldAccess); case BOOLEAN: case BYTE_STRING: case ENUM: case MESSAGE: default: return onViolation -> empty(); } } }
package org.mwc.cmap.TimeController.views; import java.awt.event.ActionEvent; import java.beans.*; import java.text.*; import java.util.*; import junit.framework.TestCase; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.jface.action.*; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.*; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.part.ViewPart; import org.mwc.cmap.TimeController.TimeControllerPlugin; import org.mwc.cmap.TimeController.controls.DTGBiSlider; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.DataTypes.Temporal.*; import org.mwc.cmap.core.ui_support.PartMonitor; import org.mwc.debrief.core.editors.PlotEditor; import org.mwc.debrief.core.editors.painters.*; import MWC.GUI.Layers; import MWC.GUI.Properties.DateFormatPropertyEditor; import MWC.GenericData.*; import MWC.Utilities.Timer.TimerListener; /** * View performing time management: show current time, allow control of time, * allow selection of time periods */ public class TimeController extends ViewPart implements ISelectionProvider, TimerListener { private PartMonitor _myPartMonitor; /** * the automatic timer we are using */ private MWC.Utilities.Timer.Timer _theTimer; /** * the editor the user is currently working with (assigned alongside the * time-provider object) */ protected IEditorPart _currentEditor; /** * listen out for new times */ final private PropertyChangeListener _temporalListener = new NewTimeListener(); /** * the temporal dataset controlling the narrative entry currently displayed */ private TimeProvider _myTemporalDataset; /** * the "write" interface for the plot which tracks the narrative, where * avaialable */ private ControllableTime _controllableTime; /** * the "write" interface for indicating a selected time period */ private ControllablePeriod _controllablePeriod; /** * label showing the current time */ private Label _timeLabel; /** * the set of layers we control through the range selector */ private Layers _myLayers; /** * the parent object for the time controller. It is at this level that we * enable/disable the controls */ private Composite _wholePanel; /** * the people listening to us */ private Vector _selectionListeners; /** * and the preferences for time control */ private TimeControlProperties _myStepperProperties; /** * module to look after the limits of the slider */ SliderRangeManagement _slideManager = null; /** * the action which stores the current DTG as a bookmark */ private Action _setAsBookmarkAction; /** * when the user clicks on us, we set our properties as a selection. Remember * the set of properties */ private StructuredSelection _propsAsSelection = null; /** * our fancy time range selector */ private DTGBiSlider _dtgRangeSlider; /** * whether the user wants to trim to time period after bislider change */ private Action _filterToSelectionAction; /** * the slider control - remember it because we're always changing the limits, * etc */ private Scale _tNowSlider; /** * the play button, obviously. */ private Button _playButton; private PropertyChangeListener _myDateFormatListener = null; /** * name of property storing slider step size, used for saving state */ private final String SLIDER_STEP_SIZE = "SLIDER_STEP_SIZE"; /** make the forward button visible at a class level so that we can * fire it in testing */ private Button _forwardButton; /** * This is a callback that will allow us to create the viewer and initialize * it. */ public void createPartControl(Composite parent) { // also sort out the slider conversion bits. We do it at the start, because // callbacks // created during initialisation may need to use/reset it _slideManager = new SliderRangeManagement() { public void setMinVal(int min) { _tNowSlider.setMinimum(min); } public void setMaxVal(int max) { _tNowSlider.setMaximum(max); } public void setTickSize(int small, int large, int drag) { _tNowSlider.setIncrement(small); _tNowSlider.setPageIncrement(large); } public void setEnabled(boolean val) { _tNowSlider.setEnabled(val); } }; // and fill in the interface buildInterface(parent); // of course though, we start off with the buttons not enabled _wholePanel.setEnabled(false); // and start listing for any part action setupListeners(); // ok we're all ready now. just try and see if the current part is valid _myPartMonitor.fireActivePart(getSite().getWorkbenchWindow().getActivePage()); // say that we're a selection provider getSite().setSelectionProvider(this); /** * the timer-related settings */ _theTimer = new MWC.Utilities.Timer.Timer(); _theTimer.stop(); _theTimer.setDelay(1000); _theTimer.addTimerListener(this); } /** * ok - put in our bits * * @param parent */ private void buildInterface(Composite parent) { // ok, draw our wonderful GUI. _wholePanel = new Composite(parent, SWT.BORDER); GridLayout onTop = new GridLayout(); onTop.horizontalSpacing = 0; onTop.verticalSpacing = 0; onTop.marginHeight = 0; onTop.marginWidth = 0; _wholePanel.setLayout(onTop); // stick in the long list of VCR buttons createVCRbuttons(); _timeLabel = new Label(_wholePanel, SWT.NONE); GridData labelGrid = new GridData(GridData.FILL_HORIZONTAL); _timeLabel.setLayoutData(labelGrid); _timeLabel.setAlignment(SWT.CENTER); _timeLabel.setText(" // _timeLabel.setFont(new Font(Display.getDefault(), "OCR A Extended", 16, // SWT.NONE)); _timeLabel.setFont(new Font(Display.getDefault(), "Arial", 16, SWT.NONE)); _timeLabel.setForeground(new Color(Display.getDefault(), 33, 255, 22)); _timeLabel.setBackground(new Color(Display.getDefault(), 0, 0, 0)); // next create the time slider holder _tNowSlider = new Scale(_wholePanel, SWT.NONE); GridData sliderGrid = new GridData(GridData.FILL_HORIZONTAL); _tNowSlider.setLayoutData(sliderGrid); _tNowSlider.setMinimum(0); _tNowSlider.setMaximum(100); _tNowSlider.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { if (!_alreadyProcessingChange) { _alreadyProcessingChange = true; int index = _tNowSlider.getSelection(); HiResDate newDTG = _slideManager.fromSliderUnits(index, _dtgRangeSlider .getStepSize()); fireNewTime(newDTG); _alreadyProcessingChange = false; } } public void widgetDefaultSelected(SelectionEvent e) { } }); _tNowSlider.addListener(SWT.MouseWheel, new WheelMovedEvent()); _dtgRangeSlider = new DTGBiSlider(_wholePanel) { public void rangeChanged(TimePeriod period) { super.rangeChanged(period); selectPeriod(period); } }; if (_defaultSliderResolution != null) _dtgRangeSlider.setStepSize(_defaultSliderResolution.intValue()); // hmm, do we have a default step size for the slider? GridData biGrid = new GridData(GridData.FILL_BOTH); _dtgRangeSlider.getControl().setLayoutData(biGrid); } private void createVCRbuttons() { // first create the button holder Composite _btnPanel = new Composite(_wholePanel, SWT.NONE); GridData btnGrid = new GridData(GridData.FILL_HORIZONTAL); _btnPanel.setLayoutData(btnGrid); FillLayout btnFiller = new FillLayout(SWT.HORIZONTAL); btnFiller.marginHeight = 0; _btnPanel.setLayout(btnFiller); Button eBwd = new Button(_btnPanel, SWT.NONE); eBwd.addSelectionListener(new TimeButtonSelectionListener(false, null)); eBwd.setImage(TimeControllerPlugin.getImage("icons/media_beginning.png")); // eBwd.setImage(TimeControllerPlugin.getImage("icons/control_start_blue.png")); Button lBwd = new Button(_btnPanel, SWT.NONE); lBwd.setText("<<"); lBwd.setImage(TimeControllerPlugin.getImage("icons/media_rewind.png")); lBwd.addSelectionListener(new TimeButtonSelectionListener(false, new Boolean(true))); Button sBwd = new Button(_btnPanel, SWT.NONE); sBwd.setText("<"); sBwd.setImage(TimeControllerPlugin.getImage("icons/media_back.png")); sBwd.addSelectionListener(new TimeButtonSelectionListener(false, new Boolean(false))); _playButton = new Button(_btnPanel, SWT.TOGGLE | SWT.NONE); _playButton.setImage(TimeControllerPlugin.getImage("icons/media_play.png")); _playButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { boolean playing = _playButton.getSelection(); ImageDescriptor thisD; if (playing) { thisD = TimeControllerPlugin.getImageDescriptor("icons/media_pause.png"); startPlaying(); } else { thisD = TimeControllerPlugin.getImageDescriptor("icons/media_play.png"); stopPlaying(); } _playButton.setImage(thisD.createImage()); } }); _forwardButton = new Button(_btnPanel, SWT.NONE); _forwardButton.setImage(TimeControllerPlugin.getImage("icons/media_forward.png")); _forwardButton.addSelectionListener(new TimeButtonSelectionListener(true, new Boolean(false))); Button lFwd = new Button(_btnPanel, SWT.NONE); lFwd.setImage(TimeControllerPlugin.getImage("icons/media_fast_forward.png")); lFwd.addSelectionListener(new TimeButtonSelectionListener(true, new Boolean(true))); Button eFwd = new Button(_btnPanel, SWT.NONE); eFwd.setImage(TimeControllerPlugin.getImage("icons/media_end.png")); eFwd.addSelectionListener(new TimeButtonSelectionListener(true, null)); } boolean _alreadyProcessingChange = false; /** * user has selected a time period, indicate it to the controllable * * @param period */ protected void selectPeriod(final TimePeriod period) { if (_controllablePeriod != null) { // updating the text items has to be done in the UI thread. make it so Display.getDefault().asyncExec(new Runnable() { public void run() { _controllablePeriod.setPeriod(period); // are we set to filter? if (_filterToSelectionAction.isChecked()) { _controllablePeriod .performOperation(ControllablePeriod.FILTER_TO_TIME_PERIOD); // and trim down the range of our slider manager // hey, what's the current dtg? HiResDate currentDTG = _slideManager.fromSliderUnits(_tNowSlider .getSelection(), _dtgRangeSlider.getStepSize()); // update the range of the slider _slideManager.resetRange(period.getStartDTG(), period.getEndDTG()); // hey - remember the updated time range (largely so that we can // restore from file later on) _myStepperProperties.setSliderStartTime(period.getStartDTG()); _myStepperProperties.setSliderEndTime(period.getEndDTG()); // do we need to move the slider back into a valid point? // hmm, was it too late? HiResDate trimmedDTG = null; if (currentDTG.greaterThan(period.getEndDTG())) { trimmedDTG = period.getEndDTG(); } else if (currentDTG.lessThan(period.getStartDTG())) { trimmedDTG = period.getStartDTG(); } else { if (!_alreadyProcessingChange) _tNowSlider.setSelection(_slideManager.toSliderUnits(currentDTG)); } // did we have to move them? if (trimmedDTG != null) { fireNewTime(trimmedDTG); } } } }); } } protected void stopPlaying() { _theTimer.stop(); } /** * ok, start auto-stepping forward through the serial */ protected void startPlaying() { // hey - set a practical minimum step size, 1/4 second is a fair start point final long delayToUse = Math.max(_myStepperProperties.getAutoInterval().getMillis(), 250); // ok - make sure the time has the right time _theTimer.setDelay(delayToUse); _theTimer.start(); } public void onTime(ActionEvent event) { // temporarily remove ourselves, to prevent being called twice _theTimer.removeTimerListener(this); // catch any exceptions raised here, it doesn't really // matter if we miss a time step try { // pass the step operation on to our parent processClick(Boolean.FALSE, true); } catch (Exception e) { CorePlugin.logError(Status.ERROR, "Error on auto-time stepping", e); } // register ourselves as a time again _theTimer.addTimerListener(this); } private final class NewTimeListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent event) { // see if it's the time or the period which // has changed if (event.getPropertyName().equals(TimeProvider.TIME_CHANGED_PROPERTY_NAME)) { // ok, use the new time HiResDate newDTG = (HiResDate) event.getNewValue(); timeUpdated(newDTG); } else if (event.getPropertyName().equals(TimeProvider.PERIOD_CHANGED_PROPERTY_NAME)) { TimePeriod newPeriod = (TimePeriod) event.getNewValue(); _slideManager.resetRange(newPeriod.getStartDTG(), newPeriod.getEndDTG()); } // also double-check if it's time to enable our interface checkTimeEnabled(); } } private void processClick(Boolean large, boolean fwd) { // check that we have a current time (on initialisation some plots may not // contain data) HiResDate tNow = _myTemporalDataset.getTime(); if (tNow != null) { // yup, time is there. work with it baby long micros = tNow.getMicros(); // right, special case for when user wants to go straight to the end - in // which // case there is a zero in the scale if (large == null) { // right, fwd or bwd if (fwd) micros = _myTemporalDataset.getPeriod().getEndDTG().getMicros(); else micros = _myTemporalDataset.getPeriod().getStartDTG().getMicros(); } else { long size; // normal processing.. if (large.booleanValue()) { // do large step size = (long) _myStepperProperties.getLargeStep().getValueIn( Duration.MICROSECONDS); } else { // and the small size step size = (long) _myStepperProperties.getSmallStep().getValueIn( Duration.MICROSECONDS); } // right, either move forwards or backwards. if (fwd) micros += size; else micros -= size; } HiResDate newDTG = new HiResDate(0, micros); // find the extent of the current dataset // TimePeriod timeP = _myTemporalDataset.getPeriod(); TimePeriod timeP = new TimePeriod.BaseTimePeriod(_myStepperProperties .getSliderStartTime(), _myStepperProperties.getSliderEndTime()); // do we represent a valid time? if (timeP.contains(newDTG)) { // yes, fire the new DTG fireNewTime(newDTG); } } } private boolean _firingNewTime = false; /** * any default size to use for the slider threshold (read in as part of the * 'init' operation before we actually create the slider) */ private Integer _defaultSliderResolution; private void fireNewTime(HiResDate dtg) { if (!_firingNewTime) { _firingNewTime = true; _controllableTime.setTime(this, dtg, true); _firingNewTime = false; } } private void setupListeners() { // try to add ourselves to listen out for page changes // getSite().getWorkbenchWindow().getPartService().addPartListener(this); _myPartMonitor = new PartMonitor(getSite().getWorkbenchWindow().getPartService()); _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { if (_myTemporalDataset != part) { // ok, stop listening to the old one if (_myTemporalDataset != null) { // right, we were looking at something, and now we're not. // stop playing (if we were) if (_theTimer.isRunning()) { // un-depress the play button _playButton.setSelection(false); // and tell the button's listeners (which will stop the timer // and update the image) _playButton.notifyListeners(SWT.Selection, new Event()); } // stop listening to that dataset _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); } // implementation here. _myTemporalDataset = (TimeProvider) part; // and start listening to the new one _myTemporalDataset.addListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); // also configure for the current time HiResDate newDTG = _myTemporalDataset.getTime(); timeUpdated(newDTG); // and initialise the current time TimePeriod timeRange = _myTemporalDataset.getPeriod(); if (timeRange != null) { // don't update the slider here, take it's value from the // TimeControlPreferences _slideManager.resetRange(timeRange.getStartDTG(), timeRange.getEndDTG()); // and our range selector - first the outer ranges _dtgRangeSlider.updateOuterRanges(timeRange); // and now the slider positions _dtgRangeSlider.updateSelectedRanges(timeRange.getStartDTG(), timeRange .getEndDTG()); } checkTimeEnabled(); // hmm, do we want to store this part? _currentEditor = (IEditorPart) parentPart; } } }); _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // was it our one? if (_myTemporalDataset == part) { // ok, stop listening to this object (just in case we were, // anyway). _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); _myTemporalDataset = null; } // and sort out whether we should be active or not. checkTimeEnabled(); } }); // _myPartMonitor.addPartListener(TimeProvider.class, PartMonitor.CLOSED, // new PartMonitor.ICallback() // public void eventTriggered(String type, Object part, IWorkbenchPart // parentPart) // // are we still listening? // if (_myTemporalDataset != null) // _myTemporalDataset.removeListener(_temporalListener, // TimeProvider.TIME_CHANGED_PROPERTY_NAME); // _myTemporalDataset = null; // checkTimeEnabled(); _myPartMonitor.addPartListener(Layers.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // implementation here. Layers newLayers = (Layers) part; if (newLayers != _myLayers) { _myLayers = newLayers; } } }); _myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { if (part == _myLayers) _myLayers = null; } }); _myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // implementation here. ControllableTime ct = (ControllableTime) part; _controllableTime = ct; checkTimeEnabled(); } }); _myPartMonitor.addPartListener(ControllableTime.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { if (part == _controllableTime) { _controllableTime = null; checkTimeEnabled(); } } }); _myPartMonitor.addPartListener(ControllablePeriod.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // implementation here. ControllablePeriod ct = (ControllablePeriod) part; _controllablePeriod = ct; checkTimeEnabled(); } }); _myPartMonitor.addPartListener(ControllablePeriod.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { if (part == _controllablePeriod) { _controllablePeriod = null; checkTimeEnabled(); } } }); _myPartMonitor.addPartListener(LayerPainterManager.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // ok, insert the painter mode actions, together with our standard // ones populateDropDownList((LayerPainterManager) part); } }); _myPartMonitor.addPartListener(LayerPainterManager.class, PartMonitor.CLOSED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // _painterSelector.getCombo().setEnabled(false); // _myLayerPainterManager = null; } }); _myPartMonitor.addPartListener(TimeControlPreferences.class, PartMonitor.ACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { // just check we're not already managing this plot if (part != _myStepperProperties) { // ok, ignore the old one, if we have one if (_myStepperProperties != null) { _myStepperProperties.removePropertyChangeListener(_myDateFormatListener); _myStepperProperties = null; } _myStepperProperties = (TimeControlProperties) part; if (_myDateFormatListener == null) _myDateFormatListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { // right, see if the user is changing the DTG format if (evt.getPropertyName().equals(TimeControlProperties.DTG_FORMAT_ID)) { // ok, refresh the DTG String newVal = getFormattedDate(_myTemporalDataset.getTime()); _timeLabel.setText(newVal); // hmm, also set the bi-slider to repaint so we get fresh // labels _dtgRangeSlider.update(); } else if (evt.getPropertyName().equals( TimeControlProperties.STEP_INTERVAL_ID)) { // hey, if we're stepping, we'd better change the size of // the time step if (_theTimer.isRunning()) { Duration theDelay = (Duration) evt.getNewValue(); _theTimer.setDelay((long) theDelay .getValueIn(Duration.MILLISECONDS)); } } } }; // also, listen out for changes in the DTG formatter _myStepperProperties.addPropertyChangeListener(_myDateFormatListener); // and update the slider ranges // do we have start/stop times? HiResDate startDTG = _myStepperProperties.getSliderStartTime(); if ((startDTG != null) && (_myTemporalDataset != null)) { // cool - update the slider to our data settings // aaah, first check that the time period isn't greater than our // data period TimePeriod dataPeriod = _myTemporalDataset.getPeriod(); HiResDate startTime, endTime; startTime = _myStepperProperties.getSliderStartTime(); endTime = _myStepperProperties.getSliderEndTime(); // trim slider start time if (startTime.lessThan(dataPeriod.getStartDTG())) startTime = dataPeriod.getStartDTG(); else if (startTime.greaterThan(dataPeriod.getEndDTG())) startTime = dataPeriod.getEndDTG(); // trim slider end time if (endTime.lessThan(dataPeriod.getStartDTG())) endTime = dataPeriod.getStartDTG(); else if (endTime.greaterThan(dataPeriod.getEndDTG())) endTime = dataPeriod.getEndDTG(); _slideManager.resetRange(startTime, endTime); // right, trim the DTG to the current slider settings HiResDate tNow = _myTemporalDataset.getTime(); HiResDate tNew = null; if (tNow != null) { TimePeriod sliderPeriod = new TimePeriod.BaseTimePeriod( _myStepperProperties.getSliderStartTime(), _myStepperProperties .getSliderEndTime()); if (!sliderPeriod.contains(tNow)) { if (tNow.lessThan(_myStepperProperties.getSliderStartTime())) tNew = _myStepperProperties.getSliderStartTime(); else tNew = _myStepperProperties.getSliderEndTime(); } if (tNew != null) _controllableTime.setTime(this, tNew, false); } // and set the time again - the slider has probably forgotten timeUpdated(_myTemporalDataset.getTime()); } else { // we don't have an existing period - reset it from the data // provided // do we have a dataset even? if (_myTemporalDataset != null) { TimePeriod period = _myTemporalDataset.getPeriod(); if (period != null) _slideManager.resetRange(period.getStartDTG(), period.getEndDTG()); } } } } }); _myPartMonitor.addPartListener(TimeControlPreferences.class, PartMonitor.DEACTIVATED, new PartMonitor.ICallback() { public void eventTriggered(String type, Object part, IWorkbenchPart parentPart) { } }); } /** * convenience method to make the panel enabled if we have a time controller * and a valid time */ private void checkTimeEnabled() { boolean enable = false; if (_myTemporalDataset != null) { if ((_controllableTime != null) && (_myTemporalDataset.getTime() != null)) enable = true; } final boolean finalEnabled = enable; Display.getDefault().asyncExec(new Runnable() { public void run() { if (!_wholePanel.isDisposed()) { // aaah, if we're clearing the panel, set the text to "pending" if (_myTemporalDataset == null) { _timeLabel.setText(" } _wholePanel.setEnabled(finalEnabled); } } }); } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#dispose() */ public void dispose() { super.dispose(); // and stop listening for part activity _myPartMonitor.dispose(getSite().getWorkbenchWindow().getPartService()); // also stop listening for time events if (_myTemporalDataset != null) { _myTemporalDataset.removeListener(_temporalListener, TimeProvider.TIME_CHANGED_PROPERTY_NAME); } } /** * Passing the focus request to the viewer's control. */ public void editMeInProperties() { // do we have any data? if (_myStepperProperties != null) { // get the editable thingy if (_propsAsSelection == null) _propsAsSelection = new StructuredSelection(_myStepperProperties); if (_selectionListeners != null) { SelectionChangedEvent sEvent = new SelectionChangedEvent(this, _propsAsSelection); for (Iterator stepper = _selectionListeners.iterator(); stepper.hasNext();) { ISelectionChangedListener thisL = (ISelectionChangedListener) stepper.next(); if (thisL != null) { thisL.selectionChanged(sEvent); } } } _propsAsSelection = null; } else { System.out.println("we haven't got any properties yet"); } } // temporal data management /** * the data we are looking at has updated. If we're set to follow that time, * update ourselves */ private void timeUpdated(final HiResDate newDTG) { if (newDTG != null) { if (!_timeLabel.isDisposed()) { // updating the text items has to be done in the UI thread. make it so // note - we use 'syncExec'. When we were using asyncExec, we would have // a back-log // of events waiting to fire. Runnable nextEvent = new Runnable() { public void run() { // display the correct time. String newVal = getFormattedDate(newDTG); _timeLabel.setText(newVal); if (!_alreadyProcessingChange) { // there's a (slim) chance that the temp dataset has already been // cleared, or // hasn't been caught yet. just check we still know about it if (_myTemporalDataset != null) { TimePeriod dataPeriod = _myTemporalDataset.getPeriod(); if (dataPeriod != null) { int newIndex = _slideManager.toSliderUnits(newDTG); // did we find a valid time? if (newIndex != -1) { // yes, go for it. _tNowSlider.setSelection(newIndex); } } } } } }; Display.getDefault().syncExec(nextEvent); } } else { System.out.println("null DTG received by time controller"); } } private String getFormattedDate(HiResDate newDTG) { String newVal = "n/a"; // hmm, we may have heard about the new date before hearing about the // plot's stepper properties. check they arrived if (_myStepperProperties != null) { String dateFormat = _myStepperProperties.getDTGFormat(); // store.getString(PreferenceConstants.P_STRING); try { newVal = toStringHiRes(newDTG, dateFormat); } catch (IllegalArgumentException e) { System.err.println("Invalid date format in preferences"); } } return newVal; } private static SimpleDateFormat _myFormat = null; private static String _myFormatString = null; public static String toStringHiRes(HiResDate time, String pattern) throws IllegalArgumentException { // so, have a look at the data long micros = time.getMicros(); // long wholeSeconds = micros / 1000000; StringBuffer res = new StringBuffer(); java.util.Date theTime = new java.util.Date(micros / 1000); // do we already know about a date format? if(_myFormatString != null) { // right, see if it's what we're after if(_myFormatString != pattern) { // nope, it's not what we're after. ditch gash _myFormatString = null; _myFormat = null; } } // so, we either don't have a format yet, or we did have, and now we want to forget it... if(_myFormat == null) { _myFormatString = pattern; _myFormat = new SimpleDateFormat(pattern); _myFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } res.append(_myFormat.format(theTime)); DecimalFormat microsFormat = new DecimalFormat("000000"); DecimalFormat millisFormat = new DecimalFormat("000"); // do we have micros? if (micros % 1000 > 0) { // yes res.append("."); res.append(microsFormat.format(micros % 1000000)); } else { // do we have millis? if (micros % 1000000 > 0) { // yes, convert the value to millis long millis = micros = (micros % 1000000) / 1000; res.append("."); res.append(millisFormat.format(millis)); } else { // just use the normal output } } return res.toString(); } public static class TestTimeController extends TestCase { private int _min, _max, _smallTick, _largeTick, _dragSize; private boolean _enabled; public void testSliderScales() { SliderRangeManagement range = new SliderRangeManagement() { public void setMinVal(int min) { _min = min; } public void setMaxVal(int max) { _max = max; } public void setTickSize(int small, int large, int drag) { _smallTick = small; _largeTick = large; _dragSize = drag; } public void setEnabled(boolean val) { _enabled = val; } }; // initialise our testing values _min = _max = _smallTick = _largeTick = -1; _enabled = false; HiResDate starter = new HiResDate(0, 100); HiResDate ender = new HiResDate(0, 200); range.resetRange(starter, ender); assertEquals("min val set", 0, _min); assertEquals("max val set", 100, _max); assertEquals("sml tick set", 10000, _smallTick); assertEquals("drag size set", 500, _dragSize); assertEquals("large tick set", 100000, _largeTick); assertTrue("slider should be enabled", _enabled); // ok, see how the transfer goes HiResDate newToSlider = new HiResDate(0, 130); int res = range.toSliderUnits(newToSlider); assertEquals("correct to slider units", 30, res); // and backwards newToSlider = range.fromSliderUnits(res, 1000); assertEquals("correct from slider units", 130, newToSlider.getMicros()); // right, now back to millis Calendar cal = new GregorianCalendar(); cal.set(2005, 3, 3, 12, 1, 1); Date starterD = cal.getTime(); cal.set(2005, 3, 12, 12, 1, 1); Date enderD = cal.getTime(); starter = new HiResDate(starterD.getTime()); ender = new HiResDate(enderD.getTime()); range.resetRange(starter, ender); long diff = (enderD.getTime() - starterD.getTime()) / 1000; assertEquals("correct range in secs", diff, _max); assertEquals("sml tick set", 60, _smallTick); assertEquals("large tick set", 600, _largeTick); } } private class WheelMovedEvent implements Listener { public void handleEvent(Event event) { // find out what keys are pressed int keys = event.stateMask; // is is the control button? if ((keys & SWT.CTRL) != 0) { final double zoomFactor; // decide if we're going in or out if(event.count > 0) zoomFactor = 0.9; else zoomFactor = 1.1; // and request the zoom doZoom(zoomFactor); } else { // right, we're not zooming, we must be time-stepping int count = event.count; boolean fwd; Boolean large = new Boolean(false); if ((keys & SWT.SHIFT) != 0) large = new Boolean(true); if (count < 0) fwd = true; else fwd = false; processClick(large, fwd); } } } public void addSelectionChangedListener(ISelectionChangedListener listener) { if (_selectionListeners == null) _selectionListeners = new Vector(0, 1); // see if we don't already contain it.. if (!_selectionListeners.contains(listener)) _selectionListeners.add(listener); } /** zoom the plot (in response to a control-mouse drag) * * @param zoomFactor */ public void doZoom(double zoomFactor) { // ok, get the plot, and do some zooming if(_currentEditor instanceof PlotEditor) { PlotEditor plot = (PlotEditor) _currentEditor; plot.getChart().getCanvas().getProjection().zoom(zoomFactor); plot.getChart().update(); } } public ISelection getSelection() { return null; } /** * accessor to the slider (used for testing the view) * * @return the slider control */ public DTGBiSlider getPeriodSlider() { return _dtgRangeSlider; } public Scale getTimeSlider() { return _tNowSlider; } public void removeSelectionChangedListener(ISelectionChangedListener listener) { _selectionListeners.remove(listener); } public void setSelection(ISelection selection) { } /** * ok - put in the stepper mode buttons - and any others we think of. */ private void populateDropDownList(final LayerPainterManager myLayerPainterManager) { // clear the list final IMenuManager menuManager = getViewSite().getActionBars().getMenuManager(); final IToolBarManager toolManager = getViewSite().getActionBars().getToolBarManager(); // ok, remove the existing items menuManager.removeAll(); toolManager.removeAll(); // ok, what are the painters we know about TemporalLayerPainter[] list = myLayerPainterManager.getList(); // add the items for (int i = 0; i < list.length; i++) { // ok, next painter final TemporalLayerPainter painter = list[i]; // create an action for it Action thisOne = new Action(painter.toString(), Action.AS_RADIO_BUTTON) { public void runWithEvent(Event event) { myLayerPainterManager.setCurrentPainter(painter); } }; String descPath = "icons/" + painter.toString().toLowerCase() + ".gif"; thisOne.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin .getImageDescriptor(descPath)); // hmm, and see if this is our current painter if (painter.getName().equals(myLayerPainterManager.getCurrentPainter().getName())) { thisOne.setChecked(true); } // and store it on both menus menuManager.add(thisOne); toolManager.add(thisOne); } // ok, let's have a separator menuManager.add(new Separator()); toolManager.add(new Separator()); // add the list of DTG formats for the DTG slider addDateFormats(menuManager); // add the list of DTG formats for the DTG slider addBiSliderResolution(menuManager); // now the add-bookmark item _setAsBookmarkAction = new Action("Add DTG as bookmark", Action.AS_PUSH_BUTTON) { public void runWithEvent(Event event) { addMarker(); } }; _setAsBookmarkAction.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin .getImageDescriptor("icons/bkmrk_nav.gif")); _setAsBookmarkAction.setToolTipText("Add this DTG to the list of bookmarks"); menuManager.add(_setAsBookmarkAction); // let user indicate whether we should be filtering to window _filterToSelectionAction = new Action("Filter to time", Action.AS_CHECK_BOX) { }; _filterToSelectionAction.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin .getImageDescriptor("icons/filter_to_period.gif")); _filterToSelectionAction.setToolTipText("Filter plot data to selected time period"); menuManager.add(_filterToSelectionAction); toolManager.add(_filterToSelectionAction); // // and the // Action expandTimeSliders = new Action("Expand slider to full period", // Action.AS_PUSH_BUTTON) // public void runWithEvent(Event event) // expandTimeSliderRangeToFull(); // expandTimeSliders.setImageDescriptor(org.mwc.debrief.core.CorePlugin // .getImageDescriptor("icons/expand_time_period.gif")); // expandTimeSliders.setToolTipText("Expand time-slider to full period"); // menuManager.add(expandTimeSliders); // toolManager.add(expandTimeSliders); // and a properties editor Action toolboxProperties = new Action("Properties...", Action.AS_PUSH_BUTTON) { public void runWithEvent(Event event) { editMeInProperties(); } }; toolboxProperties.setToolTipText("Edit Time Controller properties"); toolboxProperties.setImageDescriptor(org.mwc.debrief.core.DebriefPlugin .getImageDescriptor("icons/properties.gif")); menuManager.add(new Separator()); menuManager.add(toolboxProperties); // ok - get the action bars to re-populate themselves, otherwise we don't // see our changes getViewSite().getActionBars().updateActionBars(); } /** * @param menuManager */ private void addDateFormats(final IMenuManager menuManager) { // ok, second menu for the DTG formats MenuManager formatMenu = new MenuManager("DTG Format"); // and store it menuManager.add(formatMenu); // and now the date formats String[] formats = DateFormatPropertyEditor.getTagList(); for (int i = 0; i < formats.length; i++) { final String thisFormat = formats[i]; // the properties manager is expecting the integer index of the new // format, not the string value. // so store it as an integer index final Integer thisIndex = new Integer(i); // and create a new action to represent the change Action newFormat = new Action(thisFormat, Action.AS_RADIO_BUTTON) { public void run() { super.run(); _myStepperProperties.setPropertyValue(TimeControlProperties.DTG_FORMAT_ID, thisIndex); // todo: we need to tell the plot that it's changed - fake this by // firing a quick formatting change _myLayers.fireReformatted(null); } }; formatMenu.add(newFormat); } } /** * @param menuManager */ private void addBiSliderResolution(final IMenuManager menuManager) { // ok, second menu for the DTG formats MenuManager formatMenu = new MenuManager("Time slider increment"); // and store it menuManager.add(formatMenu); // and now the date formats Object[][] stepSizes = { { "1 sec", new Long(1000) }, { "1 min", new Long(60 * 1000) }, { "5 min", new Long(5 * 60 * 1000) }, { "15 min", new Long(15 * 60 * 1000) }, { "1 hour", new Long(60 * 60 * 1000) }, }; for (int i = 0; i < stepSizes.length; i++) { final String sizeLabel = (String) stepSizes[i][0]; final Long thisSize = (Long) stepSizes[i][1]; // and create a new action to represent the change Action newFormat = new Action(sizeLabel, Action.AS_RADIO_BUTTON) { public void run() { super.run(); _dtgRangeSlider.setStepSize(thisSize.longValue()); // ok, update the ranges of the slider _dtgRangeSlider.updateOuterRanges(_myTemporalDataset.getPeriod()); } }; formatMenu.add(newFormat); } } protected void expandTimeSliderRangeToFull() { TimePeriod period = _myTemporalDataset.getPeriod(); _slideManager.resetRange(period.getStartDTG(), period.getEndDTG()); } protected void addMarker() { try { // right, do we have an editor with a file? IEditorInput input = _currentEditor.getEditorInput(); if (input instanceof IFileEditorInput) { // aaah, and is there a file present? IFileEditorInput ife = (IFileEditorInput) input; IResource file = ife.getFile(); String currentText = _timeLabel.getText(); long tNow = _myTemporalDataset.getTime().getMicros(); if (file != null) { // yup, get the description InputDialog inputD = new InputDialog(getViewSite().getShell(), "Add bookmark at this DTG", "Enter description of this bookmark", currentText, null); inputD.open(); String content = inputD.getValue(); if (content != null) { IMarker marker = file.createMarker(IMarker.BOOKMARK); Map attributes = new HashMap(4); attributes.put(IMarker.MESSAGE, content); attributes.put(IMarker.LOCATION, currentText); attributes.put(IMarker.LINE_NUMBER, "" + tNow); attributes.put(IMarker.USER_EDITABLE, Boolean.FALSE); marker.setAttributes(attributes); } } } } catch (CoreException e) { e.printStackTrace(); } } /** * convenience class to help us manage the fwd/bwd step buttons * * @author Ian.Mayo */ private class TimeButtonSelectionListener implements SelectionListener { private boolean _fwd; private Boolean _large; public TimeButtonSelectionListener(boolean fwd, Boolean large) { _fwd = fwd; _large = large; } public void widgetSelected(SelectionEvent e) { processClick(_large, _fwd); } public void widgetDefaultSelected(SelectionEvent e) { } } // AND PROPERTY EDITORS FOR THE public void setFocus() { // ok - put the cursor on the time sldier _tNowSlider.setFocus(); } /** * @param memento */ public void saveState(IMemento memento) { super.saveState(memento); // // ok, store me bits // start off with the time step memento.putInteger(SLIDER_STEP_SIZE, (int) _dtgRangeSlider.getStepSize()); // first the } /** * @param site * @param memento * @throws PartInitException */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); if (memento != null) { // try the slider step size Integer stepSize = memento.getInteger(SLIDER_STEP_SIZE); if (stepSize != null) { _defaultSliderResolution = stepSize; } } } /** * provide the currently selected period * * @return */ public TimePeriod getPeriod() { return getPeriodSlider().getPeriod(); } /** provide some support for external testing */ public void doTests() { // check we have some data TestCase.assertNotNull("check we have time to control",_controllableTime); TestCase.assertNotNull("check we have time provider",_myTemporalDataset); TestCase.assertNotNull("check we have period to control",_controllablePeriod); HiResDate tDemanded = new HiResDate(0, 818748000000000L); // note - time equates to: 120600:00 // ok, try stepping forward. get the current time HiResDate tNow = _myTemporalDataset.getTime(); // step forward one Event ev = new Event(); _forwardButton.notifyListeners(SWT.Selection, ev); // find the new time HiResDate tNew = _myTemporalDataset.getTime(); TestCase.assertNotSame("time has changed", "" + tNew.getMicros(), "" + tNow.getMicros()); // ok, go back to the demanded time (in case we loaded the plot with a different saved time) _controllableTime.setTime(new Integer(111), tDemanded, true); // have a look at the date String timeStr = _timeLabel.getText(); // check it's what we're expecting TestCase.assertEquals("time is correct", timeStr, "120600:00"); } }
package org.wildfly.extension.undertow.deployment; import io.undertow.Handlers; import io.undertow.jsp.JspFileHandler; import io.undertow.jsp.JspServletBuilder; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.resource.CachingResourceManager; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.servlet.api.ClassIntrospecter; import io.undertow.servlet.api.ConfidentialPortManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ErrorPage; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.HttpMethodSecurityInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.InstanceHandle; import io.undertow.servlet.api.ListenerInfo; import io.undertow.servlet.api.LoginConfig; import io.undertow.servlet.api.MimeMapping; import io.undertow.servlet.api.SecurityConstraint; import io.undertow.servlet.api.ServletContainerInitializerInfo; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.ServletSecurityInfo; import io.undertow.servlet.api.ServletSessionConfig; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.api.ThreadSetupAction; import io.undertow.servlet.api.WebResourceCollection; import io.undertow.servlet.handlers.DefaultServlet; import io.undertow.servlet.handlers.ServletPathMatches; import io.undertow.servlet.util.ImmediateInstanceFactory; import io.undertow.websockets.jsr.WebSocketDeploymentInfo; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.jasper.servlet.JspServlet; import org.jboss.annotation.javaee.Icon; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.version.Version; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.modules.Module; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.jboss.security.CacheableManager; import org.jboss.security.audit.AuditManager; import org.jboss.security.auth.login.JASPIAuthenticationInfo; import org.jboss.security.authorization.config.AuthorizationModuleEntry; import org.jboss.security.authorization.modules.JACCAuthorizationModule; import org.jboss.security.config.ApplicationPolicy; import org.jboss.security.config.AuthorizationInfo; import org.jboss.security.config.SecurityConfiguration; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.JSPConfig; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.SessionCookieConfig; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.security.AuditNotificationReceiver; import org.wildfly.extension.undertow.security.JAASIdentityManagerImpl; import org.wildfly.extension.undertow.security.JbossAuthorizationManager; import org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor; import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; import org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction; import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; import org.wildfly.extension.undertow.security.jaspi.JASPIAuthenticationMechanism; import org.wildfly.extension.undertow.security.jaspi.JASPICSecurityContextFactory; import org.wildfly.extension.undertow.session.CodecSessionConfigWrapper; import org.wildfly.extension.undertow.session.SharedSessionManagerConfig; import org.xnio.IoUtils; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import org.jboss.security.AuthenticationManager; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.AUTHENTICATE; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.DENY; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; import org.jboss.security.authentication.JBossCachedAuthenticationManager; /** * Service that builds up the undertow metadata. * * @author Stuart Douglas */ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> { public static final ServiceName SERVICE_NAME = ServiceName.of("UndertowDeploymentInfoService"); private static final String TEMP_DIR = "jboss.server.temp.dir"; public static final String DEFAULT_SERVLET_NAME = "default"; public static final String OLD_URI_PREFIX = "http://java.sun.com"; public static final String NEW_URI_PREFIX = "http://xmlns.jcp.org"; public static final String UNDERTOW = "undertow"; private DeploymentInfo deploymentInfo; private final JBossWebMetaData mergedMetaData; private final String deploymentName; private final TldsMetaData tldsMetaData; private final List<TldMetaData> sharedTlds; private final Module module; private final ScisMetaData scisMetaData; private final VirtualFile deploymentRoot; private final String jaccContextId; private final String securityDomain; private final List<ServletContextAttribute> attributes; private final String contextPath; private final List<SetupAction> setupActions; private final Set<VirtualFile> overlays; private final List<ExpressionFactoryWrapper> expressionFactoryWrappers; private final List<PredicatedHandler> predicatedHandlers; private final List<HandlerWrapper> initialHandlerChainWrappers; private final List<HandlerWrapper> innerHandlerChainWrappers; private final List<HandlerWrapper> outerHandlerChainWrappers; private final List<ThreadSetupAction> threadSetupActions; private final List<ServletExtension> servletExtensions; private final SharedSessionManagerConfig sharedSessionManagerConfig; private final boolean explodedDeployment; private final InjectedValue<UndertowService> undertowService = new InjectedValue<>(); private final InjectedValue<SessionManagerFactory> sessionManagerFactory = new InjectedValue<>(); private final InjectedValue<SessionIdentifierCodec> sessionIdentifierCodec = new InjectedValue<>(); private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>(); private final InjectedValue<ServletContainerService> container = new InjectedValue<>(); private final InjectedValue<PathManager> pathManagerInjector = new InjectedValue<PathManager>(); private final InjectedValue<ComponentRegistry> componentRegistryInjectedValue = new InjectedValue<>(); private final InjectedValue<Host> host = new InjectedValue<>(); private final InjectedValue<ControlPoint> controlPointInjectedValue = new InjectedValue<>(); private final Map<String, InjectedValue<Executor>> executorsByName = new HashMap<String, InjectedValue<Executor>>(); private final String topLevelDeploymentName; private final WebSocketDeploymentInfo webSocketDeploymentInfo; private UndertowDeploymentInfoService(final JBossWebMetaData mergedMetaData, final String deploymentName, final TldsMetaData tldsMetaData, final List<TldMetaData> sharedTlds, final Module module, final ScisMetaData scisMetaData, final VirtualFile deploymentRoot, final String jaccContextId, final String securityDomain, final List<ServletContextAttribute> attributes, final String contextPath, final List<SetupAction> setupActions, final Set<VirtualFile> overlays, final List<ExpressionFactoryWrapper> expressionFactoryWrappers, List<PredicatedHandler> predicatedHandlers, List<HandlerWrapper> initialHandlerChainWrappers, List<HandlerWrapper> innerHandlerChainWrappers, List<HandlerWrapper> outerHandlerChainWrappers, List<ThreadSetupAction> threadSetupActions, boolean explodedDeployment, List<ServletExtension> servletExtensions, SharedSessionManagerConfig sharedSessionManagerConfig, String topLevelDeploymentName, WebSocketDeploymentInfo webSocketDeploymentInfo) { this.mergedMetaData = mergedMetaData; this.deploymentName = deploymentName; this.tldsMetaData = tldsMetaData; this.sharedTlds = sharedTlds; this.module = module; this.scisMetaData = scisMetaData; this.deploymentRoot = deploymentRoot; this.jaccContextId = jaccContextId; this.securityDomain = securityDomain; this.attributes = attributes; this.contextPath = contextPath; this.setupActions = setupActions; this.overlays = overlays; this.expressionFactoryWrappers = expressionFactoryWrappers; this.predicatedHandlers = predicatedHandlers; this.initialHandlerChainWrappers = initialHandlerChainWrappers; this.innerHandlerChainWrappers = innerHandlerChainWrappers; this.outerHandlerChainWrappers = outerHandlerChainWrappers; this.threadSetupActions = threadSetupActions; this.explodedDeployment = explodedDeployment; this.servletExtensions = servletExtensions; this.sharedSessionManagerConfig = sharedSessionManagerConfig; this.topLevelDeploymentName = topLevelDeploymentName; this.webSocketDeploymentInfo = webSocketDeploymentInfo; } @Override public synchronized void start(final StartContext startContext) throws StartException { ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); DeploymentInfo deploymentInfo = createServletConfig(); handleDistributable(deploymentInfo); handleIdentityManager(deploymentInfo); handleJASPIMechanism(deploymentInfo); handleJACCAuthorization (deploymentInfo); handleAdditionalAuthenticationMechanisms(deploymentInfo); handleSecurityCache(deploymentInfo, mergedMetaData); if(mergedMetaData.isUseJBossAuthorization()) { deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager())); } SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig(); if(sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) { sessionConfig = sharedSessionManagerConfig.getSessionConfig(); } ServletSessionConfig config = null; //default session config SessionCookieConfig defaultSessionConfig = container.getValue().getSessionCookieConfig(); if (defaultSessionConfig != null) { config = new ServletSessionConfig(); if (defaultSessionConfig.getName() != null) { config.setName(defaultSessionConfig.getName()); } if (defaultSessionConfig.getDomain() != null) { config.setDomain(defaultSessionConfig.getDomain()); } if (defaultSessionConfig.getHttpOnly() != null) { config.setHttpOnly(defaultSessionConfig.getHttpOnly()); } if (defaultSessionConfig.getSecure() != null) { config.setSecure(defaultSessionConfig.getSecure()); } if (defaultSessionConfig.getMaxAge() != null) { config.setMaxAge(defaultSessionConfig.getMaxAge()); } if (defaultSessionConfig.getComment() != null) { config.setComment(defaultSessionConfig.getComment()); } } boolean sessionTimeoutSet = false; if (sessionConfig != null) { if (sessionConfig.getSessionTimeoutSet()) { deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60); sessionTimeoutSet = true; } CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig(); if (config == null) { config = new ServletSessionConfig(); } if (cookieConfig != null) { if (cookieConfig.getName() != null) { config.setName(cookieConfig.getName()); } if (cookieConfig.getDomain() != null) { config.setDomain(cookieConfig.getDomain()); } if (cookieConfig.getComment() != null) { config.setComment(cookieConfig.getComment()); } config.setSecure(cookieConfig.getSecure()); config.setPath(cookieConfig.getPath()); config.setMaxAge(cookieConfig.getMaxAge()); config.setHttpOnly(cookieConfig.getHttpOnly()); } List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes(); if (modes != null && !modes.isEmpty()) { final Set<SessionTrackingMode> trackingModes = new HashSet<>(); for (SessionTrackingModeType mode : modes) { switch (mode) { case COOKIE: trackingModes.add(SessionTrackingMode.COOKIE); break; case SSL: trackingModes.add(SessionTrackingMode.SSL); break; case URL: trackingModes.add(SessionTrackingMode.URL); break; } } config.setSessionTrackingModes(trackingModes); } } if(!sessionTimeoutSet) { deploymentInfo.setDefaultSessionTimeout(container.getValue().getDefaultSessionTimeout() * 60); } if (config != null) { deploymentInfo.setServletSessionConfig(config); } for (final SetupAction action : setupActions) { deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action)); } if (initialHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) { deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper); } } if (innerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) { deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper); } } if (outerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) { deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper); } } if (threadSetupActions != null) { for (ThreadSetupAction threadSetupAction : threadSetupActions) { deploymentInfo.addThreadSetupAction(threadSetupAction); } } deploymentInfo.setServerName("WildFly " + Version.AS_VERSION); if (undertowService.getValue().isStatisticsEnabled()) { deploymentInfo.setMetricsCollector(new UndertowMetricsCollector()); } ControlPoint controlPoint = controlPointInjectedValue.getOptionalValue(); if (controlPoint != null) { deploymentInfo.addInitialHandlerChainWrapper(GlobalRequestControllerHandler.wrapper(controlPoint)); } this.deploymentInfo = deploymentInfo; } finally { Thread.currentThread().setContextClassLoader(oldTccl); } } private void handleSecurityCache(DeploymentInfo deploymentInfo, JBossWebMetaData mergedMetaData) { AuthenticationManager manager = securityDomainContextValue.getValue().getAuthenticationManager(); if(manager instanceof CacheableManager) { deploymentInfo.addNotificationReceiver(new CacheInvalidationNotificationReceiver((CacheableManager<?, java.security.Principal>) manager)); if(mergedMetaData.isFlushOnSessionInvalidation()) { CacheInvalidationSessionListener listener = new CacheInvalidationSessionListener((CacheableManager<?, java.security.Principal>) manager); deploymentInfo.addListener(Servlets.listener(CacheInvalidationSessionListener.class, new ImmediateInstanceFactory<EventListener>(listener))); } } } @Override public synchronized void stop(final StopContext stopContext) { IoUtils.safeClose(this.deploymentInfo.getResourceManager()); AuthenticationManager authManager = securityDomainContextValue.getValue().getAuthenticationManager(); if (authManager != null && authManager instanceof JBossCachedAuthenticationManager) { ((JBossCachedAuthenticationManager)authManager).releaseModuleEntries(module.getClassLoader()); } this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; } @Override public synchronized DeploymentInfo getValue() throws IllegalStateException, IllegalArgumentException { return deploymentInfo; } /** * <p>Adds to the deployment the {@link JASPIAuthenticationMechanism}, if necessary. The handler will be added if the security domain * is configured with JASPI authentication.</p> * * @param deploymentInfo */ private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) { ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) { String authMethod = null; LoginConfig loginConfig = deploymentInfo.getLoginConfig(); if (loginConfig != null && loginConfig.getAuthMethods().size() > 0) authMethod = loginConfig.getAuthMethods().get(0).getName(); deploymentInfo.setJaspiAuthenticationMechanism(new JASPIAuthenticationMechanism(this.securityDomain, authMethod)); deploymentInfo.setSecurityContextFactory(new JASPICSecurityContextFactory(this.securityDomain)); } } /** * <p> * Sets the {@link JACCAuthorizationManager} in the specified {@link DeploymentInfo} if the webapp security domain * has defined a JACC authorization module. * </p> * * @param deploymentInfo the {@link DeploymentInfo} instance. */ private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) { // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null) { AuthorizationInfo authzInfo = applicationPolicy.getAuthorizationInfo(); if (authzInfo != null) { for (AuthorizationModuleEntry entry : authzInfo.getModuleEntries()) { if (JACCAuthorizationModule.class.getName().equals(entry.getPolicyModuleName())) { deploymentInfo.setAuthorizationManager(new JACCAuthorizationManager()); break; } } } } } private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo) { for (Map.Entry<String, AuthenticationMechanism> am : host.getValue().getAdditionalAuthenticationMechanisms().entrySet()) { deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } private void handleIdentityManager(final DeploymentInfo deploymentInfo) { SecurityDomainContext sdc = securityDomainContextValue.getValue(); deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc)); AuditManager auditManager = sdc.getAuditManager(); if (auditManager != null && !mergedMetaData.isDisableAudit()) { deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager)); } deploymentInfo.setConfidentialPortManager(getConfidentialPortManager()); } private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @Override public int getConfidentialPort(HttpServerExchange exchange) { int port = exchange.getConnection().getLocalAddress(InetSocketAddress.class).getPort(); if (port<0){ UndertowLogger.ROOT_LOGGER.debugf("Confidential port not defined for port %s", port); } return host.getValue().getServer().getValue().lookupSecurePort(port); } }; } private void handleDistributable(final DeploymentInfo deploymentInfo) { SessionManagerFactory managerFactory = this.sessionManagerFactory.getOptionalValue(); if (managerFactory != null) { deploymentInfo.setSessionManagerFactory(managerFactory); } SessionIdentifierCodec codec = this.sessionIdentifierCodec.getOptionalValue(); if (codec != null) { deploymentInfo.setSessionConfigWrapper(new CodecSessionConfigWrapper(codec)); } } /* This is to address WFLY-1894 but should probably be moved to some other place. */ private String resolveContextPath() { if (deploymentName.equals(host.getValue().getDefaultWebModule())) { return "/"; } else { return contextPath; } } private DeploymentInfo createServletConfig() throws StartException { final ComponentRegistry componentRegistry = componentRegistryInjectedValue.getValue(); try { if (!mergedMetaData.isMetadataComplete()) { mergedMetaData.resolveAnnotations(); } final DeploymentInfo d = new DeploymentInfo(); d.setContextPath(resolveContextPath()); if (mergedMetaData.getDescriptionGroup() != null) { d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); } d.setDeploymentName(deploymentName); d.setHostName(host.getValue().getName()); final ServletContainerService servletContainer = container.getValue(); try { //TODO: make the caching limits configurable ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment); resourceManager = new CachingResourceManager(100, 10 * 1024 * 1024, servletContainer.getBufferCache(), resourceManager, explodedDeployment ? 2000 : -1); d.setResourceManager(resourceManager); } catch (IOException e) { throw new StartException(e); } File tempFile = new File(pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath(), deploymentName); tempFile.mkdirs(); d.setTempDir(tempFile); d.setClassLoader(module.getClassLoader()); final String servletVersion = mergedMetaData.getServletVersion(); if (servletVersion != null) { d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + "")); d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + "")); } else { d.setMajorVersion(3); d.setMinorVersion(1); } //in most cases flush just hurts performance for no good reason d.setIgnoreFlush(servletContainer.isIgnoreFlush()); //controls initialization of filters on start of application d.setEagerFilterInit(servletContainer.isEagerFilterInit()); d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers()); d.setServletStackTraces(servletContainer.getStackTraces()); d.setDisableCachingForSecuredPages(servletContainer.isDisableCachingForSecuredPages()); if (servletContainer.getSessionPersistenceManager() != null) { d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager()); } //for 2.2 apps we do not require a leading / in path mappings boolean is22OrOlder; if (d.getMajorVersion() == 1) { is22OrOlder = true; } else if (d.getMajorVersion() == 2) { is22OrOlder = d.getMinorVersion() < 3; } else { is22OrOlder = false; } JSPConfig jspConfig = servletContainer.getJspConfig(); final Set<String> seenMappings = new HashSet<>(); HashMap<String, TagLibraryInfo> tldInfo = createTldsInfo(tldsMetaData, sharedTlds); //default JSP servlet final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null; if (jspServlet != null) { //this would be null if jsp support is disabled HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData); JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new WebInjectionContainer(module.getClassLoader(), componentRegistryInjectedValue.getValue()))); if (mergedMetaData.getJspConfig() != null) { d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values())); } d.addServlet(jspServlet); final Set<String> jspPropertyGroupMappings = propertyGroups.keySet(); for (final String mapping : jspPropertyGroupMappings) { jspServlet.addMapping(mapping); } seenMappings.addAll(jspPropertyGroupMappings); //setup JSP expression factory wrapper if (!expressionFactoryWrappers.isEmpty()) { d.addListener(new ListenerInfo(JspInitializationListener.class)); d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers); } } d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry)); final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>(); if (mergedMetaData.getExecutorName() != null) { d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).getValue()); } if (servletExtensions != null) { for (ServletExtension extension : servletExtensions) { d.addServletExtension(extension); } } if (mergedMetaData.getServletMappings() != null) { for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) { List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName()); if (list == null) { servletMappings.put(mapping.getServletName(), list = new ArrayList<>()); } list.add(mapping); } } if (jspServlet != null) { jspServlet.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(null)); // we need to clear the file attribute if it is set (WFLY-4106) List<ServletMappingMetaData> list = servletMappings.get(jspServlet.getName()); if(list != null && ! list.isEmpty()) { for (final ServletMappingMetaData mapping : list) { for(String urlPattern : mapping.getUrlPatterns()) { jspServlet.addMapping(urlPattern); } seenMappings.addAll(mapping.getUrlPatterns()); } } } final List<JBossServletMetaData> servlets = new ArrayList<JBossServletMetaData>(); for (JBossServletMetaData servlet : mergedMetaData.getServlets()) { servlets.add(servlet); } for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) { final ServletInfo s; if (servlet.getJspFile() != null) { s = new ServletInfo(servlet.getName(), JspServlet.class); s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile())); } else { if (servlet.getServletClass() == null) { if(DEFAULT_SERVLET_NAME.equals(servlet.getName())) { s = new ServletInfo(servlet.getName(), DefaultServlet.class); } else { throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName()); } } else { Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass); if (creator != null) { InstanceFactory<Servlet> factory = createInstanceFactory(creator); s = new ServletInfo(servlet.getName(), servletClass, factory); } else { s = new ServletInfo(servlet.getName(), servletClass); } } } s.setAsyncSupported(servlet.isAsyncSupported()) .setJspFile(servlet.getJspFile()) .setEnabled(servlet.isEnabled()); if (servlet.getRunAs() != null) { s.setRunAs(servlet.getRunAs().getRoleName()); } if (servlet.getLoadOnStartupSet()) {//todo why not cleanup api and just use int everywhere s.setLoadOnStartup(servlet.getLoadOnStartupInt()); } if (servlet.getExecutorName() != null) { s.setExecutor(executorsByName.get(servlet.getExecutorName()).getValue()); } handleServletMappings(is22OrOlder, seenMappings, servletMappings, s); if (servlet.getInitParam() != null) { for (ParamValueMetaData initParam : servlet.getInitParam()) { if (!s.getInitParams().containsKey(initParam.getParamName())) { s.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } if (servlet.getServletSecurity() != null) { ServletSecurityInfo securityInfo = new ServletSecurityInfo(); s.setServletSecurityInfo(securityInfo); securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())) .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed()); if (servlet.getServletSecurity().getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) { securityInfo.addHttpMethodSecurityInfo( new HttpMethodSecurityInfo() .setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())) .addRolesAllowed(method.getRolesAllowed()) .setMethod(method.getMethod())); } } } if (servlet.getSecurityRoleRefs() != null) { for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) { s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink()); } } if (servlet.getMultipartConfig() != null) { MultipartConfigMetaData mp = servlet.getMultipartConfig(); s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold())); } d.addServlet(s); } //we explicitly add the default servlet, to allow it to be mapped if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) { ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class); handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet); d.addServlet(defaultServlet); } if (mergedMetaData.getFilters() != null) { for (final FilterMetaData filter : mergedMetaData.getFilters()) { Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass); FilterInfo f; if (creator != null) { InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator); f = new FilterInfo(filter.getName(), filterClass, instanceFactory); } else { f = new FilterInfo(filter.getName(), filterClass); } f.setAsyncSupported(filter.isAsyncSupported()); d.addFilter(f); if (filter.getInitParam() != null) { for (ParamValueMetaData initParam : filter.getInitParam()) { f.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } } if (mergedMetaData.getFilterMappings() != null) { for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) { if (mapping.getUrlPatterns() != null) { for (String url : mapping.getUrlPatterns()) { if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) { url = "/" + url; } if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST); } } } if (mapping.getServletNames() != null) { for (String servletName : mapping.getServletNames()) { if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST); } } } } } if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) { for (final ServletContainerInitializer sci : scisMetaData.getScis()) { final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci); d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci))); } } if (mergedMetaData.getListeners() != null) { for (ListenerMetaData listener : mergedMetaData.getListeners()) { addListener(module.getClassLoader(), componentRegistry, d, listener); } } if (mergedMetaData.getContextParams() != null) { for (ParamValueMetaData param : mergedMetaData.getContextParams()) { d.addInitParameter(param.getParamName(), param.getParamValue()); } } if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) { List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles(); for (String file : welcomeFiles) { if (file.startsWith("/")) { d.addWelcomePages(file.substring(1)); } else { d.addWelcomePages(file); } } } else { d.addWelcomePages("index.html", "index.htm", "index.jsp"); } if (mergedMetaData.getErrorPages() != null) { for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) { final ErrorPage errorPage; if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType())); } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode())); } else { errorPage = new ErrorPage(page.getLocation()); } d.addErrorPages(errorPage); } } if (mergedMetaData.getMimeMappings() != null) { for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) { d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType())); } } d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null); Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames(); if (mergedMetaData.getSecurityConstraints() != null) { for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) { SecurityConstraint securityConstraint = new SecurityConstraint() .setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee())); List<String> roleNames = constraint.getRoleNames(); if (constraint.getAuthConstraint() == null) { // no auth constraint means we permit the empty roles securityConstraint.setEmptyRoleSemantic(PERMIT); } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) { // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable // authentication only mode. // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow. securityConstraint.setEmptyRoleSemantic(AUTHENTICATE); } else { securityConstraint.addRolesAllowed(roleNames); } if (constraint.getResourceCollections() != null) { for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) { securityConstraint.addWebResourceCollection(new WebResourceCollection() .addHttpMethods(resourceCollection.getHttpMethods()) .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()) .addUrlPatterns(resourceCollection.getUrlPatterns())); } } d.addSecurityConstraint(securityConstraint); } } final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig(); if (loginConfig != null) { List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod()); if (loginConfig.getFormLoginConfig() != null) { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage())); } else { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName())); } for (AuthMethodConfig method : authMethod) { d.getLoginConfig().addLastAuthMethod(method); } } d.addSecurityRoles(mergedMetaData.getSecurityRoleNames()); Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap(); d.addThreadSetupAction(new SecurityContextThreadSetupAction(securityDomain, securityDomainContextValue.getValue(), principalVersusRolesMap)); d.addInnerHandlerChainWrapper(SecurityContextAssociationHandler.wrapper(mergedMetaData.getRunAsIdentity())); d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); d.addLifecycleInterceptor(new RunAsLifecycleInterceptor(mergedMetaData.getRunAsIdentity())); if (principalVersusRolesMap != null) { for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) { d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue()); } } // Setup an deployer configured ServletContext attributes if(attributes != null) { for (ServletContextAttribute attribute : attributes) { d.addServletContextAttribute(attribute.getName(), attribute.getValue()); } } //now setup websockets if they are enabled if(servletContainer.isWebsocketsEnabled() && webSocketDeploymentInfo != null) { webSocketDeploymentInfo.setBuffers(servletContainer.getWebsocketsBufferPool().getValue()); webSocketDeploymentInfo.setWorker(servletContainer.getWebsocketsWorker().getValue()); webSocketDeploymentInfo.setDispatchToWorkerThread(servletContainer.isDispatchWebsocketInvocationToWorker()); d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo); } if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) { for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) { d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding()); } } if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) { d.addInitialHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { if (predicatedHandlers.size() == 1) { PredicatedHandler ph = predicatedHandlers.get(0); return Handlers.predicate(ph.getPredicate(), ph.getHandler().wrap(handler), handler); } else { return Handlers.predicates(predicatedHandlers, handler); } } }); } if (mergedMetaData.getDefaultEncoding() != null) { d.setDefaultEncoding(mergedMetaData.getDefaultEncoding()); } else if (servletContainer.getDefaultEncoding() != null) { d.setDefaultEncoding(servletContainer.getDefaultEncoding()); } return d; } catch (ClassNotFoundException e) { throw new StartException(e); } } private void handleServletMappings(boolean is22OrOlder, Set<String> seenMappings, Map<String, List<ServletMappingMetaData>> servletMappings, ServletInfo s) { List<ServletMappingMetaData> mappings = servletMappings.get(s.getName()); if (mappings != null) { for (ServletMappingMetaData mapping : mappings) { for (String pattern : mapping.getUrlPatterns()) { if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) { pattern = "/" + pattern; } if (!seenMappings.contains(pattern)) { s.addMapping(pattern); seenMappings.add(pattern); } } } } } /** * Convert the authentication method name from the format specified in the web.xml to the format used by * {@link javax.servlet.http.HttpServletRequest}. * <p/> * If the auth method is not recognised then it is returned as-is. * * @return The converted auth method. * @throws NullPointerException if no configuredMethod is supplied. */ private static List<AuthMethodConfig> authMethod(String configuredMethod) { if (configuredMethod == null) { return Collections.singletonList(new AuthMethodConfig(HttpServletRequest.BASIC_AUTH)); } return AuthMethodParser.parse(configuredMethod, Collections.singletonMap("CLIENT-CERT", HttpServletRequest.CLIENT_CERT_AUTH)); } private static io.undertow.servlet.api.TransportGuaranteeType transportGuaranteeType(final TransportGuaranteeType type) { if (type == null) { return io.undertow.servlet.api.TransportGuaranteeType.NONE; } switch (type) { case CONFIDENTIAL: return io.undertow.servlet.api.TransportGuaranteeType.CONFIDENTIAL; case INTEGRAL: return io.undertow.servlet.api.TransportGuaranteeType.INTEGRAL; case NONE: return io.undertow.servlet.api.TransportGuaranteeType.NONE; } throw new RuntimeException("UNREACHABLE"); } private static HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) { final HashMap<String, JspPropertyGroup> result = new HashMap<>(); // JSP Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // JSP Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.jasper.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); for (String pattern : jspPropertyGroup.getUrlPatterns()) { // Split off the groups to individual mappings result.put(pattern, jspPropertyGroup); } } } } //it looks like jasper needs these in order of least specified to most specific final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>(); final ArrayList<String> paths = new ArrayList<>(result.keySet()); Collections.sort(paths, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.length() - o2.length(); } }); for (String path : paths) { ret.put(path, result.get(path)); } return ret; } private static HashMap<String, TagLibraryInfo> createTldsInfo(final TldsMetaData tldsMetaData, List<TldMetaData> sharedTlds) throws ClassNotFoundException { final HashMap<String, TagLibraryInfo> ret = new HashMap<>(); if (tldsMetaData != null) { if (tldsMetaData.getTlds() != null) { for (Map.Entry<String, TldMetaData> tld : tldsMetaData.getTlds().entrySet()) { createTldInfo(tld.getKey(), tld.getValue(), ret); } } if (sharedTlds != null) { for (TldMetaData metaData : sharedTlds) { createTldInfo(null, metaData, ret); } } } //we also register them under the new namespaces for (String k : new HashSet<>(ret.keySet())) { if (k != null) { if (k.startsWith(OLD_URI_PREFIX)) { String newUri = k.replace(OLD_URI_PREFIX, NEW_URI_PREFIX); ret.put(newUri, ret.get(k)); } } } return ret; } private static TagLibraryInfo createTldInfo(final String location, final TldMetaData tldMetaData, final HashMap<String, TagLibraryInfo> ret) throws ClassNotFoundException { String relativeLocation = location; String jarPath = null; if (relativeLocation != null && relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) { tagLibraryInfo.setJspversion(tldMetaData.getVersion()); } else { tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); } tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) { tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); } tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) { tagVariableInfo.setScope(variableMetaData.getScope().toString()); } tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } ret.put(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } if (jarPath.equals("META-INF/taglib.tld")) { ret.put(relativeLocation, tagLibraryInfo); } } return tagLibraryInfo; } private static void addListener(final ClassLoader classLoader, final ComponentRegistry components, final DeploymentInfo d, final ListenerMetaData listener) throws ClassNotFoundException { ListenerInfo l; final Class<? extends EventListener> listenerClass = (Class<? extends EventListener>) classLoader.loadClass(listener.getListenerClass()); ManagedReferenceFactory creator = components.createInstanceFactory(listenerClass); if (creator != null) { InstanceFactory<EventListener> factory = createInstanceFactory(creator); l = new ListenerInfo(listenerClass, factory); } else { l = new ListenerInfo(listenerClass); } d.addListener(l); } private static <T> InstanceFactory<T> createInstanceFactory(final ManagedReferenceFactory creator) { return new InstanceFactory<T>() { @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference instance = creator.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) instance.getInstance(); } @Override public void release() { instance.release(); } }; } }; } public void addInjectedExecutor(final String name, final InjectedValue<Executor> injected) { executorsByName.put(name, injected); } public InjectedValue<ServletContainerService> getContainer() { return container; } public InjectedValue<SecurityDomainContext> getSecurityDomainContextValue() { return securityDomainContextValue; } public Injector<SessionManagerFactory> getSessionManagerFactoryInjector() { return this.sessionManagerFactory; } public Injector<SessionIdentifierCodec> getSessionIdentifierCodecInjector() { return this.sessionIdentifierCodec; } public InjectedValue<UndertowService> getUndertowService() { return undertowService; } public InjectedValue<PathManager> getPathManagerInjector() { return pathManagerInjector; } public InjectedValue<ControlPoint> getControlPointInjectedValue() { return controlPointInjectedValue; } public InjectedValue<ComponentRegistry> getComponentRegistryInjectedValue() { return componentRegistryInjectedValue; } public InjectedValue<Host> getHost() { return host; } private static class ComponentClassIntrospector implements ClassIntrospecter { private final ComponentRegistry componentRegistry; public ComponentClassIntrospector(final ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } @Override public <T> InstanceFactory<T> createInstanceFactory(final Class<T> clazz) throws NoSuchMethodException { final ManagedReferenceFactory component = componentRegistry.createInstanceFactory(clazz); return new ManagedReferenceInstanceFactory<>(component); } } private static class ManagedReferenceInstanceFactory<T> implements InstanceFactory<T> { private final ManagedReferenceFactory component; public ManagedReferenceInstanceFactory(final ManagedReferenceFactory component) { this.component = component; } @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference reference = component.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) reference.getInstance(); } @Override public void release() { reference.release(); } }; } } public static Builder builder() { return new Builder(); } public static class Builder { private String topLevelDeploymentName; private JBossWebMetaData mergedMetaData; private String deploymentName; private TldsMetaData tldsMetaData; private List<TldMetaData> sharedTlds; private Module module; private ScisMetaData scisMetaData; private VirtualFile deploymentRoot; private String jaccContextId; private List<ServletContextAttribute> attributes; private String contextPath; private String securityDomain; private List<SetupAction> setupActions; private Set<VirtualFile> overlays; private List<ExpressionFactoryWrapper> expressionFactoryWrappers; private List<PredicatedHandler> predicatedHandlers; private List<HandlerWrapper> initialHandlerChainWrappers; private List<HandlerWrapper> innerHandlerChainWrappers; private List<HandlerWrapper> outerHandlerChainWrappers; private List<ThreadSetupAction> threadSetupActions; private List<ServletExtension> servletExtensions; private SharedSessionManagerConfig sharedSessionManagerConfig; private boolean explodedDeployment; private WebSocketDeploymentInfo webSocketDeploymentInfo; Builder setMergedMetaData(final JBossWebMetaData mergedMetaData) { this.mergedMetaData = mergedMetaData; return this; } public Builder setDeploymentName(final String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder setTldsMetaData(final TldsMetaData tldsMetaData) { this.tldsMetaData = tldsMetaData; return this; } public Builder setSharedTlds(final List<TldMetaData> sharedTlds) { this.sharedTlds = sharedTlds; return this; } public Builder setModule(final Module module) { this.module = module; return this; } public Builder setScisMetaData(final ScisMetaData scisMetaData) { this.scisMetaData = scisMetaData; return this; } public Builder setDeploymentRoot(final VirtualFile deploymentRoot) { this.deploymentRoot = deploymentRoot; return this; } public Builder setJaccContextId(final String jaccContextId) { this.jaccContextId = jaccContextId; return this; } public Builder setAttributes(final List<ServletContextAttribute> attributes) { this.attributes = attributes; return this; } public Builder setContextPath(final String contextPath) { this.contextPath = contextPath; return this; } public Builder setSetupActions(final List<SetupAction> setupActions) { this.setupActions = setupActions; return this; } public Builder setSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder setOverlays(final Set<VirtualFile> overlays) { this.overlays = overlays; return this; } public Builder setExpressionFactoryWrappers(final List<ExpressionFactoryWrapper> expressionFactoryWrappers) { this.expressionFactoryWrappers = expressionFactoryWrappers; return this; } public Builder setPredicatedHandlers(List<PredicatedHandler> predicatedHandlers) { this.predicatedHandlers = predicatedHandlers; return this; } public Builder setInitialHandlerChainWrappers(List<HandlerWrapper> initialHandlerChainWrappers) { this.initialHandlerChainWrappers = initialHandlerChainWrappers; return this; } public Builder setInnerHandlerChainWrappers(List<HandlerWrapper> innerHandlerChainWrappers) { this.innerHandlerChainWrappers = innerHandlerChainWrappers; return this; } public Builder setOuterHandlerChainWrappers(List<HandlerWrapper> outerHandlerChainWrappers) { this.outerHandlerChainWrappers = outerHandlerChainWrappers; return this; } public Builder setThreadSetupActions(List<ThreadSetupAction> threadSetupActions) { this.threadSetupActions = threadSetupActions; return this; } public Builder setExplodedDeployment(boolean explodedDeployment) { this.explodedDeployment = explodedDeployment; return this; } public List<ServletExtension> getServletExtensions() { return servletExtensions; } public Builder setServletExtensions(List<ServletExtension> servletExtensions) { this.servletExtensions = servletExtensions; return this; } public Builder setSharedSessionManagerConfig(SharedSessionManagerConfig sharedSessionManagerConfig) { this.sharedSessionManagerConfig = sharedSessionManagerConfig; return this; } public Builder setTopLevelDeploymentName(String topLevelDeploymentName) { this.topLevelDeploymentName = topLevelDeploymentName; return this; } public Builder setWebSocketDeploymentInfo(WebSocketDeploymentInfo webSocketDeploymentInfo) { this.webSocketDeploymentInfo = webSocketDeploymentInfo; return this; } public UndertowDeploymentInfoService createUndertowDeploymentInfoService() { return new UndertowDeploymentInfoService(mergedMetaData, deploymentName, tldsMetaData, sharedTlds, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, threadSetupActions, explodedDeployment, servletExtensions, sharedSessionManagerConfig, topLevelDeploymentName, webSocketDeploymentInfo); } } private static class UndertowThreadSetupAction implements ThreadSetupAction { private final Handle handle; private final SetupAction action; public UndertowThreadSetupAction(SetupAction action) { this.action = action; handle = new Handle() { @Override public void tearDown() { UndertowThreadSetupAction.this.action.teardown(Collections.<String, Object>emptyMap()); } }; } @Override public Handle setup(final HttpServerExchange exchange) { action.setup(Collections.<String, Object>emptyMap()); return handle; } } }
package net.i2p.time; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; public class NtpMessage { public byte leapIndicator = 0; /** * This value indicates the NTP/SNTP version number. The version number * is 3 for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI). * If necessary to distinguish between IPv4, IPv6 and OSI, the * encapsulating context must be inspected. */ public byte version = 3; public byte mode = 0; public short stratum = 0; /** * This value indicates the maximum interval between successive messages, * in seconds to the nearest power of two. The values that can appear in * this field presently range from 4 (16 s) to 14 (16284 s); however, most * applications use only the sub-range 6 (64 s) to 10 (1024 s). */ public byte pollInterval = 0; /** * This value indicates the precision of the local clock, in seconds to * the nearest power of two. The values that normally appear in this field * range from -6 for mains-frequency clocks to -20 for microsecond clocks * found in some workstations. */ public byte precision = 0; /** * This value indicates the total roundtrip delay to the primary reference * source, in seconds. Note that this variable can take on both positive * and negative values, depending on the relative time and frequency * offsets. The values that normally appear in this field range from * negative values of a few milliseconds to positive values of several * hundred milliseconds. */ public double rootDelay = 0; /** * This value indicates the nominal error relative to the primary reference * source, in seconds. The values that normally appear in this field * range from 0 to several hundred milliseconds. */ public double rootDispersion = 0; public byte[] referenceIdentifier = {0, 0, 0, 0}; /** * This is the time at which the local clock was last set or corrected, in * seconds since 00:00 1-Jan-1900. */ public double referenceTimestamp = 0; /** * This is the time at which the request departed the client for the * server, in seconds since 00:00 1-Jan-1900. */ public double originateTimestamp = 0; /** * This is the time at which the request arrived at the server, in seconds * since 00:00 1-Jan-1900. */ public double receiveTimestamp = 0; /** * This is the time at which the reply departed the server for the client, * in seconds since 00:00 1-Jan-1900. */ public double transmitTimestamp = 0; /** * Constructs a new NtpMessage from an array of bytes. */ public NtpMessage(byte[] array) { // See the packet format diagram in RFC 2030 for details leapIndicator = (byte) ((array[0] >> 6) & 0x3); version = (byte) ((array[0] >> 3) & 0x7); mode = (byte) (array[0] & 0x7); stratum = unsignedByteToShort(array[1]); pollInterval = array[2]; precision = array[3]; rootDelay = (array[4] * 256.0) + unsignedByteToShort(array[5]) + (unsignedByteToShort(array[6]) / 256.0) + (unsignedByteToShort(array[7]) / 65536.0); rootDispersion = (unsignedByteToShort(array[8]) * 256.0) + unsignedByteToShort(array[9]) + (unsignedByteToShort(array[10]) / 256.0) + (unsignedByteToShort(array[11]) / 65536.0); referenceIdentifier[0] = array[12]; referenceIdentifier[1] = array[13]; referenceIdentifier[2] = array[14]; referenceIdentifier[3] = array[15]; referenceTimestamp = decodeTimestamp(array, 16); originateTimestamp = decodeTimestamp(array, 24); receiveTimestamp = decodeTimestamp(array, 32); transmitTimestamp = decodeTimestamp(array, 40); } /** * Constructs a new NtpMessage in client -> server mode, and sets the * transmit timestamp to the current time. */ public NtpMessage() { // Note that all the other member variables are already set with // appropriate default values. this.mode = 3; this.transmitTimestamp = (System.currentTimeMillis()/1000.0) + 2208988800.0; } /** * This method constructs the data bytes of a raw NTP packet. */ public byte[] toByteArray() { // All bytes are automatically set to 0 byte[] p = new byte[48]; p[0] = (byte) (leapIndicator << 6 | version << 3 | mode); p[1] = (byte) stratum; p[2] = (byte) pollInterval; p[3] = (byte) precision; // root delay is a signed 16.16-bit FP, in Java an int is 32-bits int l = (int) (rootDelay * 65536.0); p[4] = (byte) ((l >> 24) & 0xFF); p[5] = (byte) ((l >> 16) & 0xFF); p[6] = (byte) ((l >> 8) & 0xFF); p[7] = (byte) (l & 0xFF); // root dispersion is an unsigned 16.16-bit FP, in Java there are no // unsigned primitive types, so we use a long which is 64-bits long ul = (long) (rootDispersion * 65536.0); p[8] = (byte) ((ul >> 24) & 0xFF); p[9] = (byte) ((ul >> 16) & 0xFF); p[10] = (byte) ((ul >> 8) & 0xFF); p[11] = (byte) (ul & 0xFF); p[12] = referenceIdentifier[0]; p[13] = referenceIdentifier[1]; p[14] = referenceIdentifier[2]; p[15] = referenceIdentifier[3]; encodeTimestamp(p, 16, referenceTimestamp); encodeTimestamp(p, 24, originateTimestamp); encodeTimestamp(p, 32, receiveTimestamp); encodeTimestamp(p, 40, transmitTimestamp); return p; } /** * Returns a string representation of a NtpMessage */ public String toString() { String precisionStr = new DecimalFormat("0.#E0").format(Math.pow(2, precision)); return "Leap indicator: " + leapIndicator + "\n" + "Version: " + version + "\n" + "Mode: " + mode + "\n" + "Stratum: " + stratum + "\n" + "Poll: " + pollInterval + "\n" + "Precision: " + precision + " (" + precisionStr + " seconds)\n" + "Root delay: " + new DecimalFormat("0.00").format(rootDelay*1000) + " ms\n" + "Root dispersion: " + new DecimalFormat("0.00").format(rootDispersion*1000) + " ms\n" + "Reference identifier: " + referenceIdentifierToString(referenceIdentifier, stratum, version) + "\n" + "Reference timestamp: " + timestampToString(referenceTimestamp) + "\n" + "Originate timestamp: " + timestampToString(originateTimestamp) + "\n" + "Receive timestamp: " + timestampToString(receiveTimestamp) + "\n" + "Transmit timestamp: " + timestampToString(transmitTimestamp); } /** * Converts an unsigned byte to a short. By default, Java assumes that * a byte is signed. */ public static short unsignedByteToShort(byte b) { if((b & 0x80)==0x80) return (short) (128 + (b & 0x7f)); else return (short) b; } /** * Will read 8 bytes of a message beginning at <code>pointer</code> * and return it as a double, according to the NTP 64-bit timestamp * format. */ public static double decodeTimestamp(byte[] array, int pointer) { double r = 0.0; for(int i=0; i<8; i++) { r += unsignedByteToShort(array[pointer+i]) * Math.pow(2, (3-i)*8); } return r; } /** * Encodes a timestamp in the specified position in the message */ public static void encodeTimestamp(byte[] array, int pointer, double timestamp) { // Converts a double into a 64-bit fixed point for(int i=0; i<8; i++) { // 2^24, 2^16, 2^8, .. 2^-32 double base = Math.pow(2, (3-i)*8); // Capture byte value array[pointer+i] = (byte) (timestamp / base); // Subtract captured value from remaining total timestamp = timestamp - (double) (unsignedByteToShort(array[pointer+i]) * base); } // From RFC 2030: It is advisable to fill the non-significant // low order bits of the timestamp with a random, unbiased // bitstring, both to avoid systematic roundoff errors and as // a means of loop detection and replay detection. array[7+pointer] = (byte) (Math.random()*255.0); } /** * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a * formatted date/time string. */ public static String timestampToString(double timestamp) { if(timestamp==0) return "0"; // timestamp is relative to 1900, utc is used by Java and is relative // to 1970 double utc = timestamp - (2208988800.0); // milliseconds long ms = (long) (utc * 1000.0); // date/time String date = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date(ms)); // fraction double fraction = timestamp - ((long) timestamp); String fractionSting = new DecimalFormat(".000000").format(fraction); return date + fractionSting; } /** * Returns a string representation of a reference identifier according * to the rules set out in RFC 2030. */ public static String referenceIdentifierToString(byte[] ref, short stratum, byte version) { // From the RFC 2030: // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified) // or stratum-1 (primary) servers, this is a four-character ASCII // string, left justified and zero padded to 32 bits. if(stratum==0 || stratum==1) { return new String(ref); } // In NTP Version 3 secondary servers, this is the 32-bit IPv4 // address of the reference source. else if(version==3) { return unsignedByteToShort(ref[0]) + "." + unsignedByteToShort(ref[1]) + "." + unsignedByteToShort(ref[2]) + "." + unsignedByteToShort(ref[3]); } // In NTP Version 4 secondary servers, this is the low order 32 bits // of the latest transmit timestamp of the reference source. else if(version==4) { return "" + ((unsignedByteToShort(ref[0]) / 256.0) + (unsignedByteToShort(ref[1]) / 65536.0) + (unsignedByteToShort(ref[2]) / 16777216.0) + (unsignedByteToShort(ref[3]) / 4294967296.0)); } return ""; } }
package net.kencochrane.raven.logback; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.ThrowableProxy; import ch.qos.logback.core.BasicStatusManager; import ch.qos.logback.core.Context; import ch.qos.logback.core.status.OnConsoleStatusListener; import net.kencochrane.raven.Raven; import net.kencochrane.raven.event.Event; import net.kencochrane.raven.event.EventBuilder; import net.kencochrane.raven.event.interfaces.ExceptionInterface; import net.kencochrane.raven.event.interfaces.MessageInterface; import net.kencochrane.raven.event.interfaces.StackTraceInterface; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.slf4j.MDC; import org.slf4j.Marker; import org.slf4j.MarkerFactory; import org.slf4j.helpers.MessageFormatter; import java.util.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class SentryAppenderTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private Raven mockRaven; private SentryAppender sentryAppender; @Before public void setUp() throws Exception { sentryAppender = new SentryAppender(mockRaven); setMockContextOnAppender(sentryAppender); } @After public void tearDown() throws Exception { Raven.RAVEN_THREAD.remove(); } private void setMockContextOnAppender(SentryAppender sentryAppender) { Context mockContext = mock(Context.class); sentryAppender.setContext(mockContext); BasicStatusManager statusManager = new BasicStatusManager(); OnConsoleStatusListener listener = new OnConsoleStatusListener(); listener.start(); statusManager.add(listener); when(mockContext.getStatusManager()).thenReturn(statusManager); } @Test public void testSimpleMessageLogging() throws Exception { String message = UUID.randomUUID().toString(); String loggerName = UUID.randomUUID().toString(); String threadName = UUID.randomUUID().toString(); Date date = new Date(1373883196416L); ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); Event event; ILoggingEvent loggingEvent = newLoggingEvent(loggerName, null, Level.INFO, message, null, null, null, threadName, null, date.getTime()); sentryAppender.append(loggingEvent); verify(mockRaven).runBuilderHelpers(any(EventBuilder.class)); verify(mockRaven).sendEvent(eventCaptor.capture()); event = eventCaptor.getValue(); assertThat(event.getMessage(), is(message)); assertThat(event.getLogger(), is(loggerName)); assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName)); assertThat(event.getTimestamp(), is(date)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testLogLevelConversions() throws Exception { assertLevelConverted(Event.Level.DEBUG, Level.TRACE); assertLevelConverted(Event.Level.DEBUG, Level.DEBUG); assertLevelConverted(Event.Level.INFO, Level.INFO); assertLevelConverted(Event.Level.WARNING, Level.WARN); assertLevelConverted(Event.Level.ERROR, Level.ERROR); } private void assertLevelConverted(Event.Level expectedLevel, Level level) { ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, null, level, null, null, null)); verify(mockRaven).sendEvent(eventCaptor.capture()); assertThat(eventCaptor.getValue().getLevel(), is(expectedLevel)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); reset(mockRaven); } @Test public void testExceptionLogging() throws Exception { Exception exception = new Exception(); ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, null, Level.ERROR, null, null, exception)); verify(mockRaven).sendEvent(eventCaptor.capture()); ExceptionInterface exceptionInterface = (ExceptionInterface) eventCaptor.getValue().getSentryInterfaces() .get(ExceptionInterface.EXCEPTION_INTERFACE); Throwable capturedException = exceptionInterface.getThrowable(); assertThat(capturedException.getMessage(), is(exception.getMessage())); assertThat(capturedException.getStackTrace(), is(exception.getStackTrace())); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testLogParametrisedMessage() throws Exception { String messagePattern = "Formatted message {} {} {}"; Object[] parameters = {"first parameter", new Object[0], null}; ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, messagePattern, parameters, null)); verify(mockRaven).sendEvent(eventCaptor.capture()); MessageInterface messageInterface = (MessageInterface) eventCaptor.getValue().getSentryInterfaces() .get(MessageInterface.MESSAGE_INTERFACE); assertThat(eventCaptor.getValue().getMessage(), is("Formatted message first parameter [] null")); assertThat(messageInterface.getMessage(), is(messagePattern)); assertThat(messageInterface.getParameters(), is(Arrays.asList(parameters[0].toString(), parameters[1].toString(), null))); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testMarkerAddedToTag() throws Exception { String markerName = UUID.randomUUID().toString(); ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, MarkerFactory.getMarker(markerName), Level.INFO, null, null, null)); verify(mockRaven).sendEvent(eventCaptor.capture()); assertThat(eventCaptor.getValue().getTags(), Matchers.<String, Object>hasEntry(SentryAppender.LOGBACK_MARKER, markerName)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testMdcAddedToExtra() throws Exception { String extraKey = UUID.randomUUID().toString(); String extraValue = UUID.randomUUID().toString(); ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); MDC.put(extraKey, extraValue); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, null, null, null, Collections.singletonMap(extraKey, extraValue), null, null, 0)); verify(mockRaven).sendEvent(eventCaptor.capture()); assertThat(eventCaptor.getValue().getExtra(), Matchers.<String, Object>hasEntry(extraKey, extraValue)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testSourceUsedAsStacktrace() throws Exception { StackTraceElement[] location = {new StackTraceElement(UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), 42)}; ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, null, null, null, null, null, location, 0)); verify(mockRaven).sendEvent(eventCaptor.capture()); StackTraceInterface stackTraceInterface = (StackTraceInterface) eventCaptor.getValue().getSentryInterfaces() .get(StackTraceInterface.STACKTRACE_INTERFACE); assertThat(stackTraceInterface.getStackTrace(), is(location)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testCulpritWithSource() throws Exception { StackTraceElement[] location = {new StackTraceElement("a", "b", "c", 42), new StackTraceElement("d", "e", "f", 69)}; ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, null, null, null, null, null, location, 0)); verify(mockRaven).sendEvent(eventCaptor.capture()); assertThat(eventCaptor.getValue().getCulprit(), is("a.b(c:42)")); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testCulpritWithoutSource() throws Exception { String loggerName = UUID.randomUUID().toString(); ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class); sentryAppender.append(newLoggingEvent(loggerName, null, Level.INFO, null, null, null)); verify(mockRaven).sendEvent(eventCaptor.capture()); assertThat(eventCaptor.getValue().getCulprit(), is(loggerName)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testClose() throws Exception { sentryAppender.stop(); verify(mockRaven.getConnection(), never()).close(); sentryAppender = new SentryAppender(mockRaven, true); setMockContextOnAppender(sentryAppender); sentryAppender.stop(); verify(mockRaven.getConnection()).close(); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testAppendFailIfCurrentThreadSpawnedByRaven(){ Raven.RAVEN_THREAD.set(true); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, null, null, null)); verify(mockRaven, never()).sendEvent(any(Event.class)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(0)); } @Test public void testRavenFailureDoesNotPropagate(){ doThrow(new UnsupportedOperationException()).when(mockRaven).sendEvent(any(Event.class)); sentryAppender.append(newLoggingEvent(null, null, Level.INFO, null, null, null)); assertThat(sentryAppender.getContext().getStatusManager().getCount(), is(1)); } private ILoggingEvent newLoggingEvent(String loggerName, Marker marker, Level level, String message, Object[] argumentArray, Throwable t) { return newLoggingEvent(loggerName, marker, level, message, argumentArray, t, null, null, null, System.currentTimeMillis()); } private ILoggingEvent newLoggingEvent(String loggerName, Marker marker, Level level, String message, Object[] argumentArray, Throwable throwable, Map<String, String> mdcPropertyMap, String threadName, StackTraceElement[] callerData, long timestamp) { ILoggingEvent iLoggingEvent = mock(ILoggingEvent.class); when(iLoggingEvent.getThreadName()).thenReturn(threadName); when(iLoggingEvent.getLevel()).thenReturn(level); when(iLoggingEvent.getMessage()).thenReturn(message); when(iLoggingEvent.getArgumentArray()).thenReturn(argumentArray); when(iLoggingEvent.getFormattedMessage()).thenReturn( argumentArray != null ? MessageFormatter.arrayFormat(message, argumentArray).getMessage() : message); when(iLoggingEvent.getLoggerName()).thenReturn(loggerName); when(iLoggingEvent.getThrowableProxy()).thenReturn(throwable != null ? new ThrowableProxy(throwable) : null); when(iLoggingEvent.getCallerData()).thenReturn(callerData != null ? callerData : new StackTraceElement[0]); when(iLoggingEvent.hasCallerData()).thenReturn(callerData != null && callerData.length > 0); when(iLoggingEvent.getMarker()).thenReturn(marker); when(iLoggingEvent.getMDCPropertyMap()) .thenReturn(mdcPropertyMap != null ? mdcPropertyMap : Collections.<String, String>emptyMap()); when(iLoggingEvent.getTimeStamp()).thenReturn(timestamp); return iLoggingEvent; } }
package net.sandius.rembulan.compiler.gen.block; import net.sandius.rembulan.compiler.gen.PrototypeContext; import net.sandius.rembulan.compiler.gen.SlotState; import net.sandius.rembulan.core.ControlThrowable; import net.sandius.rembulan.core.Dispatch; import net.sandius.rembulan.core.LuaState; import net.sandius.rembulan.core.ObjectSink; import net.sandius.rembulan.core.ResumeInfo; import net.sandius.rembulan.core.Table; import net.sandius.rembulan.core.TableFactory; import net.sandius.rembulan.core.Upvalue; import net.sandius.rembulan.util.Check; import net.sandius.rembulan.util.asm.ASMUtils; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Emit { public final int REGISTER_OFFSET = 3; public final int LV_STATE = 0; public final int LV_OBJECTSINK = 1; public final int LV_RESUME = 2; private final PrototypeContext context; private final MethodVisitor visitor; private final Map<Object, Label> labels; private final ArrayList<Label> resumptionPoints; public Emit(PrototypeContext context, MethodVisitor visitor) { this.context = Check.notNull(context); this.visitor = Check.notNull(visitor); this.labels = new HashMap<>(); this.resumptionPoints = new ArrayList<>(); } protected Label _l(Object key) { Label l = labels.get(key); if (l != null) { return l; } else { Label nl = new Label(); labels.put(key, nl); return nl; } } protected String thisClassName() { return context.className(); } public void _note(String text) { System.out.println("// " + text); } public void _dup() { visitor.visitInsn(Opcodes.DUP); } public void _swap() { visitor.visitInsn(Opcodes.SWAP); } public void _push_null() { visitor.visitInsn(Opcodes.ACONST_NULL); } public void _push_int(int i) { switch (i) { case -1: visitor.visitInsn(Opcodes.ICONST_M1); break; case 0: visitor.visitInsn(Opcodes.ICONST_0); break; case 1: visitor.visitInsn(Opcodes.ICONST_1); break; case 2: visitor.visitInsn(Opcodes.ICONST_2); break; case 3: visitor.visitInsn(Opcodes.ICONST_3); break; case 4: visitor.visitInsn(Opcodes.ICONST_4); break; case 5: visitor.visitInsn(Opcodes.ICONST_5); break; default: visitor.visitLdcInsn(i); break; } } private void _push_long(long l) { if (l == 0L) visitor.visitInsn(Opcodes.LCONST_0); else if (l == 1L) visitor.visitInsn(Opcodes.LCONST_1); else visitor.visitLdcInsn(l); } public void _push_double(double d) { if (d == 0.0) visitor.visitInsn(Opcodes.DCONST_0); else if (d == 1.0) visitor.visitInsn(Opcodes.DCONST_1); else visitor.visitLdcInsn(d); } public void _load_k(int idx, Class castTo) { Object k = context.getConst(idx); if (k == null) { _push_null(); } else if (k instanceof Boolean) { _push_int((Boolean) k ? 1 : 0); _invokeStatic(Boolean.class, "valueOf", Type.getMethodType(Type.getType(Boolean.class), Type.BOOLEAN_TYPE)); } else if (k instanceof Double || k instanceof Float) { _push_double(((Number) k).doubleValue()); _invokeStatic(Double.class, "valueOf", Type.getMethodType(Type.getType(Double.class), Type.DOUBLE_TYPE)); } else if (k instanceof Number) { _push_long(((Number) k).longValue()); _invokeStatic(Long.class, "valueOf", Type.getMethodType(Type.getType(Long.class), Type.LONG_TYPE)); } else if (k instanceof String) { visitor.visitLdcInsn((String) k); } else { _note("load const #" + idx + " of type " + PrototypeContext.constantType(k)); } if (castTo != null) { if (!castTo.isAssignableFrom(k.getClass())) { _checkCast(castTo); } } } public void _load_k(int idx) { _load_k(idx, null); } public void _load_reg_value(int idx) { visitor.visitVarInsn(Opcodes.ALOAD, REGISTER_OFFSET + idx); } public void _load_reg(int idx, SlotState slots, Class castTo) { Check.notNull(slots); Check.nonNegative(idx); if (slots.isCaptured(idx)) { _get_downvalue(idx); _get_upvalue_value(); } else { _load_reg_value(idx); } Class clazz = Object.class; if (castTo != null) { if (!castTo.isAssignableFrom(clazz)) { _checkCast(castTo); } } } public void _load_reg(int idx, SlotState slots) { _load_reg(idx, slots, null); } public void _get_downvalue(int idx) { visitor.visitVarInsn(Opcodes.ALOAD, REGISTER_OFFSET + idx); _checkCast(Upvalue.class); } public void _load_reg_or_const(int rk, SlotState slots, Class castTo) { Check.notNull(slots); if (rk < 0) { // it's a constant _load_k(-rk - 1, castTo); } else { _load_reg(rk, slots, castTo); } } public void _load_reg_or_const(int rk, SlotState slots) { _load_reg_or_const(rk, slots, null); } private void _store_reg_value(int r) { visitor.visitVarInsn(Opcodes.ASTORE, REGISTER_OFFSET + r); } public void _store(int r, SlotState slots) { Check.notNull(slots); if (slots.isCaptured(r)) { _get_downvalue(r); _swap(); _set_upvalue_value(); } else { _store_reg_value(r); } } @Deprecated public String _className(String cn) { return cn.replace('.', '/'); } @Deprecated public String _classDesc(String cn) { return "L" + _className(cn) + ";"; } @Deprecated public String _classDesc(Class clazz) { if (clazz.isPrimitive()) { if (clazz.equals(void.class)) return "V"; else if (clazz.equals(byte.class)) return "B"; else if (clazz.equals(boolean.class)) return "Z"; else if (clazz.equals(char.class)) return "C"; else if (clazz.equals(double.class)) return "D"; else if (clazz.equals(float.class)) return "F"; else if (clazz.equals(int.class)) return "I"; else if (clazz.equals(long.class)) return "J"; else if (clazz.equals(short.class)) return "S"; else throw new IllegalArgumentException(); } else { if (clazz.isArray()) { return _className(clazz.getName()); } else { return "L" + _className(clazz.getName()) + ";"; } } } public void _invokeStatic(Class clazz, String methodName, Type methodSignature) { visitor.visitMethodInsn( Opcodes.INVOKESTATIC, Type.getInternalName(clazz), methodName, methodSignature.getDescriptor(), false ); } public void _invokeVirtual(Class clazz, String methodName, Type methodSignature) { visitor.visitMethodInsn( Opcodes.INVOKEVIRTUAL, Type.getInternalName(clazz), methodName, methodSignature.getDescriptor(), false ); } public void _invokeInterface(Class clazz, String methodName, Type methodSignature) { visitor.visitMethodInsn( Opcodes.INVOKEINTERFACE, Type.getInternalName(clazz), methodName, methodSignature.getDescriptor(), true ); } public void _invokeSpecial(String className, String methodName, Type methodSignature) { visitor.visitMethodInsn( Opcodes.INVOKESPECIAL, _className(className), methodName, methodSignature.getDescriptor(), false ); } // public void _invokeSpecial(Class clazz, String methodName, String methodSignature) { // _invokeSpecial(clazz.getName(), methodName, methodSignature); public String _methodSignature(Class returnType, Class... parameters) { StringBuilder bld = new StringBuilder(); bld.append("("); for (Class p : parameters) { bld.append(_classDesc(p)); } bld.append(")"); bld.append(_classDesc(returnType)); return bld.toString(); } public void _dispatchCall(String methodName, Type signature) { _invokeStatic(Dispatch.class, methodName, signature); } public void _dispatch_binop(String name, Class clazz) { Type t = Type.getType(clazz); _invokeStatic(Dispatch.class, name, Type.getMethodType(t, t, t)); } public void _dispatch_generic_mt_2(String name) { _invokeStatic( Dispatch.class, name, Type.getMethodType( Type.VOID_TYPE, Type.getType(LuaState.class), Type.getType(ObjectSink.class), Type.getType(Object.class), Type.getType(Object.class) ) ); } public void _dispatch_index() { _dispatch_generic_mt_2("index"); } public void _checkCast(Class clazz) { visitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(clazz)); } public void _loadState() { visitor.visitVarInsn(Opcodes.ALOAD, LV_STATE); } public void _loadObjectSink() { visitor.visitVarInsn(Opcodes.ALOAD, LV_OBJECTSINK); } public void _retrieve_1() { _invokeVirtual(ObjectSink.class, "_1", Type.getMethodType(Type.getType(Object.class))); } public void _save_pc(Object o) { Label rl = _l(o); int idx = resumptionPoints.size(); resumptionPoints.add(rl); _push_int(idx); visitor.visitVarInsn(Opcodes.ISTORE, LV_RESUME); } public void _resumptionPoint(Object label) { _label_here(label); } private Label lswitch; private Label lbegin; private Label lerror; private Label lend; public void _begin() { lswitch = new Label(); visitor.visitJumpInsn(Opcodes.GOTO, lswitch); lbegin = new Label(); lerror = new Label(); resumptionPoints.add(lbegin); visitor.visitLabel(lbegin); _frame_same(); } public void _end() { lend = new Label(); visitor.visitLabel(lend); if (isResumable()) { _error_state(); } _dispatch_table(); if (isResumable()) { _resumption_handler(lbegin, lend); } } protected void _error_state() { visitor.visitLabel(lerror); _new(IllegalStateException.class); _dup(); _ctor(IllegalStateException.class); visitor.visitInsn(Opcodes.ATHROW); } protected boolean isResumable() { return resumptionPoints.size() > 1; } protected void _dispatch_table() { visitor.visitLabel(lswitch); _frame_same(); if (isResumable()) { Label[] labels = resumptionPoints.toArray(new Label[0]); visitor.visitVarInsn(Opcodes.ILOAD, LV_RESUME); visitor.visitTableSwitchInsn(0, resumptionPoints.size() - 1, lerror, labels); } else { // only entry point here visitor.visitJumpInsn(Opcodes.GOTO, resumptionPoints.get(0)); } } protected int numOfRegisters() { return context.prototype().getMaximumStackSize(); } protected void _make_saved_state() { _new(ResumeInfo.SavedState.class); _dup(); // resumption point visitor.visitVarInsn(Opcodes.ILOAD, LV_RESUME); // registers int numRegs = numOfRegisters(); _push_int(numRegs); visitor.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class)); for (int i = 0; i < numRegs; i++) { _dup(); _push_int(i); _load_reg_value(i); visitor.visitInsn(Opcodes.AASTORE); } _ctor(Type.getType(ResumeInfo.SavedState.class), Type.INT_TYPE, ASMUtils.arrayTypeFor(Object.class)); } protected void _resumption_handler(Label begin, Label end) { Label handler = new Label(); visitor.visitLabel(handler); visitor.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] { Type.getInternalName(ControlThrowable.class) }); _new(ResumeInfo.class); _dup(); _make_saved_state(); _ctor(ResumeInfo.class, Object.class); // FIXME _invokeVirtual(ControlThrowable.class, "push", Type.getMethodType(Type.VOID_TYPE, Type.getType(ResumeInfo.class))); // rethrow visitor.visitInsn(Opcodes.ATHROW); visitor.visitTryCatchBlock(begin, end, handler, Type.getInternalName(ControlThrowable.class)); } public String _upvalue_field_name(int idx) { String n = context.upvalueName(idx); if (n != null) { return n; // FIXME: make sure it's a valid name, & that it's unique! } else { return "uv_" + idx; } } public void _get_upvalue_ref(int idx) { visitor.visitFieldInsn( Opcodes.GETFIELD, _className(thisClassName()), _upvalue_field_name(idx), Type.getDescriptor(Upvalue.class)); } public void _get_upvalue_value() { _invokeVirtual(Upvalue.class, "get", Type.getMethodType(Type.getType(Object.class))); } public void _set_upvalue_value() { _invokeVirtual(Upvalue.class, "set", Type.getMethodType(Type.VOID_TYPE, Type.getType(Object.class))); } public void _return() { visitor.visitInsn(Opcodes.RETURN); } public void _new(String className) { visitor.visitTypeInsn(Opcodes.NEW, _className(className)); } public void _new(Class clazz) { _new(clazz.getName()); } public void _ctor(Type clazz, Type... args) { _invokeSpecial(clazz.getInternalName(), "<init>", Type.getMethodType(Type.VOID_TYPE, args)); } public void _ctor(String className, Class... args) { Type[] argTypes = new Type[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = Type.getType(args[i]); } _ctor(Type.getType(_classDesc(className)), argTypes); } public void _ctor(Class clazz, Class... args) { _ctor(clazz.getName(), args); } public void _capture(int idx) { _new(Upvalue.class); _dup(); _load_reg_value(idx); _ctor(Upvalue.class, Object.class); _store_reg_value(idx); } public void _uncapture(int idx) { _load_reg_value(idx); _get_upvalue_value(); _store_reg_value(idx); } private void _frame_same() { visitor.visitFrame(Opcodes.F_SAME, 0, null, 0, null); } public void _label_here(Object identity) { Label l = _l(identity); visitor.visitLabel(l); _frame_same(); } public void _goto(Object l) { visitor.visitJumpInsn(Opcodes.GOTO, _l(l)); } public void _next_insn(Target t) { _goto(t); // if (t.inSize() < 2) { // // can be inlined, TODO: check this again // _note("goto ignored: " + t.toString()); // else { // _goto(t); } public void _new_table(int array, int hash) { _loadState(); _invokeVirtual(LuaState.class, "tableFactory", Type.getMethodType(Type.getType(TableFactory.class))); _push_int(array); _push_int(hash); _invokeVirtual(TableFactory.class, "newTable", Type.getMethodType(Type.getType(Table.class), Type.INT_TYPE, Type.INT_TYPE)); } public void _if_null(Object target) { visitor.visitJumpInsn(Opcodes.IFNULL, _l(target)); } public void _if_nonnull(Object target) { visitor.visitJumpInsn(Opcodes.IFNONNULL, _l(target)); } public void _tailcall_0() { _invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE)); } public void _tailcall_1() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o)); } public void _tailcall_2() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o, o)); } public void _tailcall_3() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "tailCall", Type.getMethodType(Type.VOID_TYPE, o, o, o)); } public void _setret_0() { _invokeInterface(ObjectSink.class, "reset", Type.getMethodType(Type.VOID_TYPE)); } public void _setret_1() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o)); } public void _setret_2() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o, o)); } public void _setret_3() { Type o = Type.getType(Object.class); _invokeInterface(ObjectSink.class, "setTo", Type.getMethodType(Type.VOID_TYPE, o, o)); } public void _line_here(int line) { Label l = _l(new Object()); visitor.visitLabel(l); visitor.visitLineNumber(line, l); } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.jme.tools; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.text.DecimalFormat; import java.util.HashMap; import java.util.logging.Level; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JSlider; import javax.swing.KeyStroke; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import com.jme.bounding.BoundingBox; import com.jme.bounding.BoundingVolume; import com.jme.image.Texture; import com.jme.light.DirectionalLight; import com.jme.math.FastMath; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.Controller; import com.jme.scene.Line; import com.jme.scene.Node; import com.jme.scene.Spatial; import com.jme.scene.state.LightState; import com.jme.scene.state.MaterialState; import com.jme.scene.state.TextureState; import com.jme.scene.state.WireframeState; import com.jme.scene.state.ZBufferState; import com.jme.system.JmeException; import com.jme.util.LoggingSystem; import com.jme.util.TextureKey; import com.jme.util.TextureManager; import com.jme.util.export.binary.BinaryImporter; import com.jme.util.geom.Debugger; import com.jmex.effects.particles.ParticleGeometry; import com.samskivert.swing.GroupLayout; import com.samskivert.swing.Spacer; import com.samskivert.util.Config; import com.samskivert.util.ObjectUtil; import com.samskivert.util.StringUtil; import com.threerings.resource.ResourceManager; import com.threerings.util.MessageBundle; import com.threerings.util.MessageManager; import com.threerings.jme.JmeCanvasApp; import com.threerings.jme.Log; import com.threerings.jme.camera.CameraHandler; import com.threerings.jme.model.Model; import com.threerings.jme.model.TextureProvider; import com.threerings.jme.util.SpatialVisitor; /** * A simple viewer application that allows users to examine models and their * animations by loading them from their uncompiled <code>.properties</code> / * <code>.mxml</code> representations or their compiled <code>.dat</code> * representations. */ public class ModelViewer extends JmeCanvasApp { public static void main (String[] args) { // write standard output and error to a log file if (System.getProperty("no_log_redir") == null) { String dlog = "viewer.log"; try { PrintStream logOut = new PrintStream( new FileOutputStream(dlog), true); System.setOut(logOut); System.setErr(logOut); } catch (IOException ioe) { Log.warning("Failed to open debug log [path=" + dlog + ", error=" + ioe + "]."); } } LoggingSystem.getLoggingSystem().setLevel(Level.WARNING); new ModelViewer(args.length > 0 ? args[0] : null); } /** * Creates and initializes an instance of the model viewer application. * * @param path the path of the model to view, or <code>null</code> for * none */ public ModelViewer (String path) { super(1024, 768); _rsrcmgr = new ResourceManager("rsrc"); _msg = new MessageManager("rsrc.i18n").getBundle("jme.viewer"); _path = path; JPopupMenu.setDefaultLightWeightPopupEnabled(false); _frame = new JFrame(_msg.get("m.title")); _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menu = new JMenuBar(); _frame.setJMenuBar(menu); JMenu file = new JMenu(_msg.get("m.file_menu")); file.setMnemonic(KeyEvent.VK_F); menu.add(file); Action load = new AbstractAction(_msg.get("m.file_load")) { public void actionPerformed (ActionEvent e) { showLoadDialog(); } }; load.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_L); load.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.CTRL_MASK)); file.add(load); Action importAction = new AbstractAction(_msg.get("m.file_import")) { public void actionPerformed (ActionEvent e) { showImportDialog(); } }; importAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_I); importAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK)); file.add(importAction); file.addSeparator(); Action quit = new AbstractAction(_msg.get("m.file_quit")) { public void actionPerformed (ActionEvent e) { System.exit(0); } }; quit.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_Q); quit.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK)); file.add(quit); JMenu view = new JMenu(_msg.get("m.view_menu")); view.setMnemonic(KeyEvent.VK_V); menu.add(view); Action wireframe = new AbstractAction(_msg.get("m.view_wireframe")) { public void actionPerformed (ActionEvent e) { _wfstate.setEnabled(!_wfstate.isEnabled()); } }; wireframe.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_W); wireframe.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK)); view.add(new JCheckBoxMenuItem(wireframe)); view.addSeparator(); _pivots = new JCheckBoxMenuItem(_msg.get("m.view_pivots")); _pivots.setMnemonic(KeyEvent.VK_P); _pivots.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK)); view.add(_pivots); _bounds = new JCheckBoxMenuItem(_msg.get("m.view_bounds")); _bounds.setMnemonic(KeyEvent.VK_B); _bounds.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK)); view.add(_bounds); _normals = new JCheckBoxMenuItem(_msg.get("m.view_normals")); _normals.setMnemonic(KeyEvent.VK_N); _normals.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK)); view.add(_normals); view.addSeparator(); Action campos = new AbstractAction(_msg.get("m.view_campos")) { public void actionPerformed (ActionEvent e) { _campos.setVisible(!_campos.isVisible()); } }; campos.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A); campos.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK)); view.add(new JCheckBoxMenuItem(campos)); view.addSeparator(); _vmenu = new JMenu(_msg.get("m.model_variant")); view.add(_vmenu); JMenu amode = new JMenu(_msg.get("m.animation_mode")); final JRadioButtonMenuItem flipbook = new JRadioButtonMenuItem(_msg.get("m.mode_flipbook")), morph = new JRadioButtonMenuItem(_msg.get("m.mode_morph")), skin = new JRadioButtonMenuItem(_msg.get("m.mode_skin")); ButtonGroup mgroup = new ButtonGroup() { public void setSelected (ButtonModel model, boolean b) { super.setSelected(model, b); if (b) { if (flipbook.isSelected()) { _animMode = Model.AnimationMode.FLIPBOOK; } else if (morph.isSelected()) { _animMode = Model.AnimationMode.MORPH; } else { _animMode = Model.AnimationMode.SKIN; } if (_loaded != null) { loadModel(_loaded); // reload } } } }; mgroup.add(flipbook); mgroup.add(morph); mgroup.add(skin); mgroup.setSelected(skin.getModel(), true); amode.add(skin); amode.add(morph); amode.add(flipbook); view.add(amode); view.addSeparator(); Action rlight = new AbstractAction(_msg.get("m.view_light")) { public void actionPerformed (ActionEvent e) { if (_rldialog == null) { _rldialog = new RotateLightDialog(); _rldialog.pack(); } _rldialog.setVisible(true); } }; rlight.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_R); rlight.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_MASK)); view.add(new JMenuItem(rlight)); Action rcamera = new AbstractAction(_msg.get("m.view_recenter")) { public void actionPerformed (ActionEvent e) { ((OrbitCameraHandler)_camhand).recenter(); updateCameraPosition(); } }; rcamera.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C); rcamera.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_MASK)); view.add(new JMenuItem(rcamera)); _frame.getContentPane().add(getCanvas(), BorderLayout.CENTER); JPanel bpanel = new JPanel(new BorderLayout()); _frame.getContentPane().add(bpanel, BorderLayout.SOUTH); _animctrls = new JPanel(); _animctrls.setBorder(BorderFactory.createEtchedBorder()); bpanel.add(_animctrls, BorderLayout.NORTH); _animctrls.add(new JLabel(_msg.get("m.anim_select"))); _animctrls.add(_animbox = new JComboBox()); _animctrls.add(new JButton( new AbstractAction(_msg.get("m.anim_start")) { public void actionPerformed (ActionEvent e) { String anim = (String)_animbox.getSelectedItem(); if (_model.hasAnimation(anim)) { _model.startAnimation(anim); } else { // it's a sequence if (_model.getAnimation() != null) { _sequence = null; _model.stopAnimation(); } _sequence = StringUtil.parseStringArray( _model.getProperties().getProperty( anim + ".animations", "")); if (_sequence.length == 0) { _sequence = null; } else { _model.startAnimation(_sequence[_seqidx = 0]); } } } })); _animctrls.add(_animstop = new JButton( new AbstractAction(_msg.get("m.anim_stop")) { public void actionPerformed (ActionEvent e) { _model.stopAnimation(); } })); _animstop.setEnabled(false); _animctrls.add(new Spacer(50, 1)); _animctrls.add(new JLabel(_msg.get("m.anim_speed"))); _animctrls.add(_animspeed = new JSlider(-100, +100, 0)); _animspeed.setMajorTickSpacing(10); _animspeed.setSnapToTicks(true); _animspeed.setPaintTicks(true); _animspeed.addChangeListener(new ChangeListener() { public void stateChanged (ChangeEvent e) { updateAnimationSpeed(); } }); _animctrls.setVisible(false); JPanel spanel = new JPanel(new BorderLayout()); bpanel.add(spanel, BorderLayout.SOUTH); _status = new JLabel(" "); _status.setHorizontalAlignment(JLabel.LEFT); _status.setBorder(BorderFactory.createEtchedBorder()); spanel.add(_status, BorderLayout.CENTER); _campos = new JLabel(" "); _campos.setBorder(BorderFactory.createEtchedBorder()); _campos.setVisible(false); spanel.add(_campos, BorderLayout.EAST); _frame.pack(); _frame.setVisible(true); run(); } @Override // documentation inherited public boolean init () { if (!super.init()) { return false; } if (_path != null) { loadModel(new File(_path)); } return true; } @Override // documentation inherited protected void initDisplay () throws JmeException { super.initDisplay(); _ctx.getRenderer().setBackgroundColor(ColorRGBA.gray); _ctx.getRenderer().getQueue().setTwoPassTransparency(false); } @Override // documentation inherited protected void initInput () { super.initInput(); _camhand.setTiltLimits(-FastMath.HALF_PI, FastMath.HALF_PI); _camhand.setZoomLimits(1f, 500f); _camhand.tiltCamera(-FastMath.PI * 7.0f / 16.0f); updateCameraPosition(); MouseOrbiter orbiter = new MouseOrbiter(); _canvas.addMouseListener(orbiter); _canvas.addMouseMotionListener(orbiter); _canvas.addMouseWheelListener(orbiter); } /** * Updates the camera position label. */ protected void updateCameraPosition () { Camera cam = _camhand.getCamera(); Vector3f pos = cam.getLocation(), dir = cam.getDirection(), left = cam.getLeft(); float heading = -FastMath.atan2(dir.x, dir.y) * FastMath.RAD_TO_DEG, pitch = FastMath.asin(dir.z) * FastMath.RAD_TO_DEG; _campos.setText( "XYZ: " + CAMPOS_FORMAT.format(pos.x) + ", " + CAMPOS_FORMAT.format(pos.y) + ", " + CAMPOS_FORMAT.format(pos.z) + " HP: " + CAMPOS_FORMAT.format(heading) + ", " + CAMPOS_FORMAT.format(pitch)); } @Override // documentation inherited protected CameraHandler createCameraHandler (Camera camera) { return new OrbitCameraHandler(camera); } @Override // documentation inherited protected void initRoot () { super.initRoot(); // set default states MaterialState mstate = _ctx.getRenderer().createMaterialState(); mstate.getDiffuse().set(ColorRGBA.white); mstate.getAmbient().set(ColorRGBA.white); _ctx.getGeometry().setRenderState(mstate); _ctx.getGeometry().setRenderState( _wfstate = _ctx.getRenderer().createWireframeState()); _ctx.getGeometry().setNormalsMode(Spatial.NM_GL_NORMALIZE_PROVIDED); _wfstate.setEnabled(false); // create a grid on the XY plane to provide some reference Vector3f[] points = new Vector3f[GRID_SIZE*2 + GRID_SIZE*2]; float halfLength = (GRID_SIZE - 1) * GRID_SPACING / 2; int idx = 0; for (int xx = 0; xx < GRID_SIZE; xx++) { points[idx++] = new Vector3f( -halfLength + xx*GRID_SPACING, -halfLength, 0f); points[idx++] = new Vector3f( -halfLength + xx*GRID_SPACING, +halfLength, 0f); } for (int yy = 0; yy < GRID_SIZE; yy++) { points[idx++] = new Vector3f( -halfLength, -halfLength + yy*GRID_SPACING, 0f); points[idx++] = new Vector3f( +halfLength, -halfLength + yy*GRID_SPACING, 0f); } Line grid = new Line("grid", points, null, null, null); grid.getBatch(0).getDefaultColor().set(0.25f, 0.25f, 0.25f, 1f); grid.setLightCombineMode(LightState.OFF); grid.setModelBound(new BoundingBox()); grid.updateModelBound(); _ctx.getGeometry().attachChild(grid); grid.updateRenderState(); // attach a dummy node to draw debugging views _ctx.getGeometry().attachChild(new Node("debug") { public void onDraw (Renderer r) { if (_model == null) { return; } if (_pivots.getState()) { drawPivots(_model, r); } if (_bounds.getState()) { Debugger.drawBounds(_model, r); } if (_normals.getState()) { Debugger.drawNormals(_model, r, 5f, true); } } }); } /** * Draws the pivot axes of the given node and its children. */ protected void drawPivots (Spatial spatial, Renderer r) { if (_axes == null) { _axes = new Line("axes", new Vector3f[] { Vector3f.ZERO, Vector3f.UNIT_X, Vector3f.ZERO, Vector3f.UNIT_Y, Vector3f.ZERO, Vector3f.UNIT_Z }, null, new ColorRGBA[] { ColorRGBA.red, ColorRGBA.red, ColorRGBA.green, ColorRGBA.green, ColorRGBA.blue, ColorRGBA.blue }, null); _axes.setRenderQueueMode(Renderer.QUEUE_SKIP); _axes.setRenderState(r.createZBufferState()); LightState lstate = r.createLightState(); lstate.setEnabled(false); _axes.setRenderState(lstate); _axes.updateRenderState(); } _axes.getRenderState(ZBufferState.RS_ZBUFFER).apply(); _axes.getRenderState(LightState.RS_LIGHT).apply(); _axes.getWorldTranslation().set(spatial.getWorldTranslation()); _axes.getWorldRotation().set(spatial.getWorldRotation()); _axes.draw(r); if (spatial instanceof Node) { Node node = (Node)spatial; for (int ii = 0, nn = node.getQuantity(); ii < nn; ii++) { drawPivots(node.getChild(ii), r); } } } @Override // documentation inherited protected void initLighting () { _dlight = new DirectionalLight(); _dlight.setEnabled(true); _dlight.getDirection().set(-1f, 0f, -1f).normalizeLocal(); _dlight.getAmbient().set(0.25f, 0.25f, 0.25f, 1f); LightState lstate = _ctx.getRenderer().createLightState(); lstate.attach(_dlight); _ctx.getGeometry().setRenderState(lstate); _ctx.getGeometry().setLightCombineMode(LightState.REPLACE); } /** * Shows the load model dialog. */ protected void showLoadDialog () { if (_chooser == null) { _chooser = new JFileChooser(); _chooser.setDialogTitle(_msg.get("m.load_title")); _chooser.setFileFilter(new FileFilter() { public boolean accept (File file) { if (file.isDirectory()) { return true; } String path = file.toString().toLowerCase(); return path.endsWith(".properties") || path.endsWith(".dat"); } public String getDescription () { return _msg.get("m.load_filter"); } }); File dir = new File(_config.getValue("dir", ".")); if (dir.exists()) { _chooser.setCurrentDirectory(dir); } } if (_chooser.showOpenDialog(_frame) == JFileChooser.APPROVE_OPTION) { loadModel(_chooser.getSelectedFile()); } _config.setValue("dir", _chooser.getCurrentDirectory().toString()); } /** * Attempts to load a model from the specified location. */ protected void loadModel (File file) { String fpath = file.toString(); try { if (fpath.endsWith(".properties")) { compileModel(file); } else if (fpath.endsWith(".dat")) { loadCompiledModel(file); } else { throw new Exception(_msg.get("m.invalid_type")); } _status.setText(_msg.get("m.loaded_model", fpath)); _loaded = file; } catch (Exception e) { e.printStackTrace(); _status.setText(_msg.get("m.load_error", fpath, e)); } } /** * Attempts to compile and load a model. */ protected void compileModel (File file) throws Exception { _status.setText(_msg.get("m.compiling_model", file)); Model model = CompileModel.compile(file); if (model != null) { setModel(model, file); return; } // if compileModel returned null, the .dat file is up-to-date String fpath = file.toString(); int didx = fpath.lastIndexOf('.'); fpath = (didx == -1) ? fpath : fpath.substring(0, didx); loadCompiledModel(new File(fpath + ".dat")); } /** * Attempts to load a model that has already been compiled. */ protected void loadCompiledModel (File file) throws IOException { _status.setText(_msg.get("m.loading_model", file)); setModel(Model.readFromFile(file, false), file); } /** * Sets the model once it's been loaded. * * @param file the file from which the model was loaded */ protected void setModel (Model model, File file) { if (_model != null) { _ctx.getGeometry().detachChild(_model); } _ctx.getGeometry().attachChild(_model = _omodel = model); _model.setAnimationMode(_animMode); _model.lockStaticMeshes(_ctx.getRenderer(), true, true); // load the model's textures resolveModelTextures(file); // recenter the camera _model.updateGeometricState(0f, true); ((OrbitCameraHandler)_camhand).recenter(); updateCameraPosition(); // configure the variant menu _variant = null; _vmenu.removeAll(); ButtonGroup vgroup = new ButtonGroup() { public void setSelected (ButtonModel model, boolean b) { super.setSelected(model, b); String variant = model.getActionCommand(); if (b && !ObjectUtil.equals(variant, _variant)) { setVariant(model.getActionCommand()); } } }; JRadioButtonMenuItem def = new JRadioButtonMenuItem( _msg.get("m.variant_default")); def.setActionCommand(null); vgroup.add(def); _vmenu.add(def); for (String variant : _model.getVariantNames()) { JRadioButtonMenuItem vitem = new JRadioButtonMenuItem(variant); vitem.setActionCommand(variant); vgroup.add(vitem); _vmenu.add(vitem); } vgroup.setSelected(def.getModel(), true); // configure the animation panel String[] anims = _model.getAnimationNames(); if (anims.length == 0) { _animctrls.setVisible(false); return; } _model.addAnimationObserver(_animobs); _animctrls.setVisible(true); DefaultComboBoxModel abmodel = new DefaultComboBoxModel(anims); _animbox.setModel(abmodel); updateAnimationSpeed(); // if there are any sequences, add those as well String[] seqs = StringUtil.parseStringArray( _model.getProperties().getProperty("sequences", "")); for (String seq : seqs) { abmodel.addElement(seq); } } /** * Switches to the named variant. */ protected void setVariant (String variant) { _model.stopAnimation(); _ctx.getGeometry().detachChild(_model); _ctx.getGeometry().attachChild( _model = _omodel.createPrototype(variant)); _model.addAnimationObserver(_animobs); updateAnimationSpeed(); resolveModelTextures(_loaded); _variant = variant; } /** * Resolve the textures from the file's directory. */ protected void resolveModelTextures (File file) { final File dir = file.getParentFile(); _model.resolveTextures(new TextureProvider() { public TextureState getTexture (String name) { TextureState tstate = _tstates.get(name); if (tstate == null) { File file; if (name.startsWith("/")) { file = _rsrcmgr.getResourceFile(name.substring(1)); } else { file = new File(dir, name); } Texture tex = TextureManager.loadTexture(file.toString(), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR); if (tex == null) { Log.warning("Couldn't find texture [path=" + file + "]."); return null; } tex.setWrap(Texture.WM_WRAP_S_WRAP_T); tstate = _ctx.getRenderer().createTextureState(); tstate.setTexture(tex); _tstates.put(name, tstate); } return tstate; } protected HashMap<String, TextureState> _tstates = new HashMap<String, TextureState>(); }); _model.updateRenderState(); } /** * Shows the import particle system dialog. */ protected void showImportDialog () { if (_ichooser == null) { _ichooser = new JFileChooser(); _ichooser.setDialogTitle(_msg.get("m.import_title")); _ichooser.setFileFilter(new FileFilter() { public boolean accept (File file) { if (file.isDirectory()) { return true; } String path = file.toString().toLowerCase(); return path.endsWith(".jme"); } public String getDescription () { return _msg.get("m.import_filter"); } }); File dir = new File(_config.getValue("import_dir", ".")); if (dir.exists()) { _ichooser.setCurrentDirectory(dir); } } if (_ichooser.showOpenDialog(_frame) == JFileChooser.APPROVE_OPTION) { importFile(_ichooser.getSelectedFile()); } _config.setValue("import_dir", _ichooser.getCurrentDirectory().toString()); } /** * Attempts to import the specified file as a JME binary scene. */ protected void importFile (File file) { final File parent = file.getParentFile(); TextureKey.setLocationOverride(new TextureKey.LocationOverride() { public URL getLocation (String name) throws MalformedURLException { return new URL(parent.toURL(), name); } }); try { new ImportDialog(file, (Spatial)BinaryImporter.getInstance().load( file)).setVisible(true); } catch (Exception e) { e.printStackTrace(); _status.setText(_msg.get("m.load_error", file, e)); } TextureKey.setLocationOverride(null); } /** * Updates the model's animation speed based on the position of the * animation speed slider. */ protected void updateAnimationSpeed () { _model.setAnimationSpeed( FastMath.pow(2f, _animspeed.getValue() / 25f)); } /** The resource manager. */ protected ResourceManager _rsrcmgr; /** The translation bundle. */ protected MessageBundle _msg; /** The path of the initial model to load. */ protected String _path; /** The last model successfully loaded. */ protected File _loaded; /** The viewer frame. */ protected JFrame _frame; /** The variant menu. */ protected JMenu _vmenu; /** Debug view switches. */ protected JCheckBoxMenuItem _pivots, _bounds, _normals; /** The animation controls. */ protected JPanel _animctrls; /** The animation selector. */ protected JComboBox _animbox; /** The "stop animation" button. */ protected JButton _animstop; /** The animation speed slider. */ protected JSlider _animspeed; /** The status bar. */ protected JLabel _status; /** The camera position display. */ protected JLabel _campos; /** The model file chooser. */ protected JFileChooser _chooser; /** The import file chooser. */ protected JFileChooser _ichooser; /** The desired animation mode. */ protected Model.AnimationMode _animMode; /** The desired variant. */ protected String _variant; /** The light rotation dialog. */ protected RotateLightDialog _rldialog; /** The scene light. */ protected DirectionalLight _dlight; /** Used to toggle wireframe rendering. */ protected WireframeState _wfstate; /** The currently loaded model. */ protected Model _model; /** The original model (before switching to a variant). */ protected Model _omodel; /** Reused to draw pivot axes. */ protected Line _axes; /** The current animation sequence, if any. */ protected String[] _sequence; /** The current index in the animation sequence. */ protected int _seqidx; /** Enables and disables the stop button when animations start and stop. */ protected Model.AnimationObserver _animobs = new Model.AnimationObserver() { public boolean animationStarted (Model model, String name) { _animstop.setEnabled(true); return true; } public boolean animationCompleted (Model model, String name) { if (_sequence != null && ++_seqidx < _sequence.length) { _model.startAnimation(_sequence[_seqidx]); } else { _animstop.setEnabled(false); _sequence = null; } return true; } public boolean animationCancelled (Model model, String name) { if (_sequence != null && ++_seqidx < _sequence.length && _model.getAnimation(name).repeatType != Controller.RT_CLAMP) { _model.startAnimation(_sequence[_seqidx]); } else { _animstop.setEnabled(false); _sequence = null; } return true; } }; /** Allows users to manipulate an imported JME file. */ protected class ImportDialog extends JDialog implements ChangeListener { public ImportDialog (File file, Spatial spatial) { super(_frame, _msg.get("m.import", file), false); _spatial = spatial; // rotate from y-up to z-up and set initial scale _spatial.getLocalRotation().fromAngleNormalAxis(FastMath.HALF_PI, Vector3f.UNIT_X); _spatial.setLocalScale(0.025f); JPanel cpanel = GroupLayout.makeVBox(); getContentPane().add(cpanel, BorderLayout.CENTER); JPanel spanel = new JPanel(); spanel.add(new JLabel(_msg.get("m.scale"))); spanel.add(_scale = new JSlider(0, 1000, 250)); _scale.addChangeListener(this); cpanel.add(spanel); JPanel bpanel = new JPanel(); bpanel.add(new JButton(new AbstractAction( _msg.get("m.respawn_particles")) { public void actionPerformed (ActionEvent e) { _respawner.traverse(_spatial); } })); bpanel.add(new JButton(new AbstractAction(_msg.get("m.close")) { public void actionPerformed (ActionEvent e) { setVisible(false); } })); getContentPane().add(bpanel, BorderLayout.SOUTH); pack(); } // documentation inherited from interface ChangeListener public void stateChanged (ChangeEvent e) { _spatial.setLocalScale(_scale.getValue() * 0.0001f); } @Override // documentation inherited public void setVisible (boolean visible) { super.setVisible(visible); if (visible && _spatial.getParent() == null) { _ctx.getGeometry().attachChild(_spatial); _spatial.updateRenderState(); } else if (!visible && _spatial.getParent() != null) { _ctx.getGeometry().detachChild(_spatial); } } /** The imported scene. */ protected Spatial _spatial; /** The scale slider. */ protected JSlider _scale; } /** Allows users to move the directional light around. */ protected class RotateLightDialog extends JDialog implements ChangeListener { public RotateLightDialog () { super(_frame, _msg.get("m.rotate_light"), false); JPanel cpanel = GroupLayout.makeVBox(); getContentPane().add(cpanel, BorderLayout.CENTER); JPanel apanel = new JPanel(); apanel.add(new JLabel(_msg.get("m.azimuth"))); apanel.add(_azimuth = new JSlider(-180, +180, 0)); _azimuth.addChangeListener(this); cpanel.add(apanel); JPanel epanel = new JPanel(); epanel.add(new JLabel(_msg.get("m.elevation"))); epanel.add(_elevation = new JSlider(-90, +90, 45)); _elevation.addChangeListener(this); cpanel.add(epanel); JPanel bpanel = new JPanel(); bpanel.add(new JButton(new AbstractAction(_msg.get("m.close")) { public void actionPerformed (ActionEvent e) { setVisible(false); } })); getContentPane().add(bpanel, BorderLayout.SOUTH); } // documentation inherited from interface ChangeListener public void stateChanged (ChangeEvent e) { float az = _azimuth.getValue() * FastMath.DEG_TO_RAD, el = _elevation.getValue() * FastMath.DEG_TO_RAD; _dlight.getDirection().set( -FastMath.cos(az) * FastMath.cos(el), -FastMath.sin(az) * FastMath.cos(el), -FastMath.sin(el)); } /** Azimuth and elevation sliders. */ protected JSlider _azimuth, _elevation; } /** Moves the camera using mouse input. */ protected class MouseOrbiter extends MouseAdapter implements MouseMotionListener, MouseWheelListener { @Override // documentation inherited public void mousePressed (MouseEvent e) { _mloc.setLocation(e.getX(), e.getY()); } // documentation inherited from interface MouseMotionListener public void mouseMoved (MouseEvent e) { } // documentation inherited from interface MouseMotionListener public void mouseDragged (MouseEvent e) { int dx = e.getX() - _mloc.x, dy = e.getY() - _mloc.y; _mloc.setLocation(e.getX(), e.getY()); int mods = e.getModifiers(); if ((mods & MouseEvent.BUTTON1_MASK) != 0) { _camhand.tiltCamera(dy * FastMath.PI / 1000); _camhand.orbitCamera(-dx * FastMath.PI / 1000); } else if ((mods & MouseEvent.BUTTON2_MASK) != 0) { _camhand.zoomCamera(dy/8f); } else { _camhand.panCamera(-dx/8f, dy/8f); } updateCameraPosition(); } // documentation inherited from interface MouseWheelListener public void mouseWheelMoved (MouseWheelEvent e) { _camhand.zoomCamera(e.getWheelRotation() * 10f); updateCameraPosition(); } /** The last recorded position of the mouse cursor. */ protected Point _mloc = new Point(); } /** A camera handler that pans in directions orthogonal to the camera * direction. */ protected class OrbitCameraHandler extends CameraHandler { public OrbitCameraHandler (Camera camera) { super(camera); _gpoint = super.getGroundPoint(); } @Override // documentation inherited public void panCamera (float x, float y) { Vector3f offset = _camera.getLeft().mult(-x).addLocal( _camera.getUp().mult(y)); getGroundPoint().addLocal(offset); _camera.getLocation().addLocal(offset); _camera.onFrameChange(); } @Override // documentation inherited public Vector3f getGroundPoint () { return _gpoint; } /** * Resets the ground point to the center of the grid or, if there is * one, the center of the model. */ public void recenter () { Vector3f target = new Vector3f(); if (_model != null) { BoundingVolume bound = (BoundingVolume)_model.getWorldBound(); if (bound != null) { bound.getCenter(target); } } Vector3f offset = target.subtract(_gpoint); _camera.getLocation().addLocal(offset); _camera.onFrameChange(); _gpoint.set(target); } /** The point at which the camera is looking. */ protected Vector3f _gpoint; } /** The app configuration. */ protected static Config _config = new Config("com/threerings/jme/tools/ModelViewer"); /** Forces all particle systems to respawn. */ protected static SpatialVisitor<ParticleGeometry> _respawner = new SpatialVisitor<ParticleGeometry>(ParticleGeometry.class) { protected void visit (ParticleGeometry geom) { geom.forceRespawn(); } }; /** The number of lines on the grid in each direction. */ protected static final int GRID_SIZE = 32; /** The spacing between lines on the grid. */ protected static final float GRID_SPACING = 2.5f; /** The number formal used for the camera position. */ protected static final DecimalFormat CAMPOS_FORMAT = new DecimalFormat("+000.000;-000.000"); }
// $Id: DObject.java,v 1.71 2003/12/11 18:36:32 mdb Exp $ package com.threerings.presents.dobj; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import com.samskivert.util.ListUtil; import com.samskivert.util.StringUtil; import com.threerings.io.Streamable; import com.threerings.presents.Log; /** * The distributed object forms the foundation of the Presents system. All * information shared among users of the system is done via distributed * objects. A distributed object has a set of listeners. These listeners * have access to the object or a proxy of the object and therefore have * access to the data stored in the object's members at all times. * * <p> Additionally, an object as a set of subscribers. Subscribers manage * the lifespan of the object; while a subscriber is subscribed, the * listeners registered with an object will be notified of events. When * the subscriber unsubscribes, the object becomes non-live and the * listeners are no longer notified. <em>Note:</em> on the server, object * subscription is merely a formality as all objects remain live all the * time, so <em>do not</em> depend on event notifications ceasing when a * subscriber has relinquished its subscription. Always unregister all * listeners when they no longer need to hear from an object. * * <p> When there is any change to the the object's fields data, an event * is generated which is dispatched to all listeners of the object, * notifying them of that change and effecting that change to the copy of * the object maintained at each client. In this way, both a respository * of shared information and a mechanism for asynchronous notification are * made available as a fundamental application building blocks. * * <p> To define what information is shared, an application creates a * distributed object declaration which is much like a class declaration * except that it is transformed into a proper derived class of * <code>DObject</code> by a script. A declaration looks something like * this: * * <pre> * public dclass RoomObject * { * public String description; * public int[] occupants; * } * </pre> * * which is converted into an actual Java class that looks like this: * * <pre> * public class RoomObject extends DObject * { * public String getDescription () * { * // ... * } * * public void setDescription (String description) * { * // ... * } * * public int[] getOccupants () * { * // ... * } * * public void setOccupants (int[] occupants) * { * // ... * } * * public void setOccupantsAt (int index, int value) * { * // ... * } * } * </pre> * * These method calls on the actual distributed object will result in the * proper attribute change events being generated and dispatched. * * <p> Note that distributed object fields can be any of the following set * of primitive types: * * <code><pre> * boolean, byte, short, int, long, float, double * Boolean, Byte, Short, Integer, Long, Float, Double, String * boolean[], byte[], short[], int[], long[], float[], double[], String[] * </pre></code> * * Fields of type {@link Streamable} can also be used. */ public class DObject implements Streamable { public DObject () { _fields = (Field[])_ftable.get(getClass()); if (_fields == null) { _fields = getClass().getFields(); Arrays.sort(_fields, FIELD_COMP); _ftable.put(getClass(), _fields); } } /** * Returns the object id of this object. All objects in the system * have a unique object id. */ public int getOid () { return _oid; } /** * Returns the dobject manager under the auspices of which this object * operates. This could be <code>null</code> if the object is not * active. */ public DObjectManager getManager () { return _omgr; } /** * Don't call this function! Go through the distributed object manager * instead to ensure that everything is done on the proper thread. * This function can only safely be called directly when you know you * are operating on the omgr thread (you are in the middle of a call * to <code>objectAvailable</code> or to a listener callback). * * @see DObjectManager#subscribeToObject */ public void addSubscriber (Subscriber sub) { // only add the subscriber if they're not already there Object[] subs = ListUtil.testAndAdd(_subs, sub); if (subs != null) { // Log.info("Adding subscriber " + which() + ": " + sub + "."); _subs = subs; _scount++; } else { Log.warning("Refusing subscriber that's already in the list " + "[dobj=" + which() + ", subscriber=" + sub + "]"); Thread.dumpStack(); } } /** * Don't call this function! Go through the distributed object manager * instead to ensure that everything is done on the proper thread. * This function can only safely be called directly when you know you * are operating on the omgr thread (you are in the middle of a call * to <code>objectAvailable</code> or to a listener callback). * * @see DObjectManager#unsubscribeFromObject */ public void removeSubscriber (Subscriber sub) { if (ListUtil.clear(_subs, sub) != null) { // if we removed something, check to see if we just removed // the last subscriber from our list; we also want to be sure // that we're still active otherwise there's no need to notify // our objmgr because we don't have one if (--_scount == 0 && _omgr != null) { _omgr.removedLastSubscriber(this, _deathWish); } } } /** * Instructs this object to request to have a fork stuck in it when * its last subscriber is removed. */ public void setDestroyOnLastSubscriberRemoved (boolean deathWish) { _deathWish = deathWish; } /** * Adds an event listener to this object. The listener will be * notified when any events are dispatched on this object that match * their particular listener interface. * * <p> Note that the entity adding itself as a listener should have * obtained the object reference by subscribing to it or should be * acting on behalf of some other entity that subscribed to the * object, <em>and</em> that it must be sure to remove itself from the * listener list (via {@link #removeListener}) when it is done because * unsubscribing from the object (done by whatever entity subscribed * in the first place) is not guaranteed to result in the listeners * added through that subscription being automatically removed (in * most cases, they definitely will not be removed). * * @param listener the listener to be added. * * @see EventListener * @see AttributeChangeListener * @see SetListener * @see OidListListener */ public void addListener (ChangeListener listener) { // only add the listener if they're not already there Object[] els = ListUtil.testAndAdd(_listeners, listener); if (els != null) { _listeners = els; } else { Log.warning("Refusing repeat listener registration " + "[dobj=" + which() + ", list=" + listener + "]"); Thread.dumpStack(); } } /** * Removes an event listener from this object. The listener will no * longer be notified when events are dispatched on this object. * * @param listener the listener to be removed. */ public void removeListener (ChangeListener listener) { ListUtil.clear(_listeners, listener); } /** * Provides this object with an entity that can be used to validate * subscription requests and events before they are processed. The * access controller is handy for ensuring that clients are behaving * as expected and for preventing impermissible modifications or event * dispatches on a distributed object. */ public void setAccessController (AccessController controller) { _controller = controller; } /** * Returns a reference to the access controller in use by this object * or null if none has been configured. */ public AccessController getAccessController () { return _controller; } /** * At times, an entity on the server may need to ensure that events it * has queued up have made it through the event queue and are applied * to their respective objects before a service may safely be * undertaken again. To make this possible, it can acquire a lock on a * distributed object, generate the events in question and then * release the lock (via a call to <code>releaseLock</code>) which * will queue up a final event, the processing of which will release * the lock. Thus the lock will not be released until all of the * previously generated events have been processed. If the service is * invoked again before that lock is released, the associated call to * <code>acquireLock</code> will fail and the code can respond * accordingly. An object may have any number of outstanding locks as * long as they each have a unique name. * * @param name the name of the lock to acquire. * * @return true if the lock was acquired, false if the lock was not * acquired because it has not yet been released from a previous * acquisition. * * @see #releaseLock */ public boolean acquireLock (String name) { // check for the existence of the lock in the list and add it if // it's not already there Object[] list = ListUtil.testAndAddEqual(_locks, name); if (list == null) { // a null list means the object was already in the list return false; } else { // a non-null list means the object was added _locks = list; return true; } } /** * Queues up an event that when processed will release the lock of the * specified name. * * @see #acquireLock */ public void releaseLock (String name) { // queue up a release lock event postEvent(new ReleaseLockEvent(_oid, name)); } /** * Don't call this function! It is called by a remove lock event when * that event is processed and shouldn't be called at any other time. * If you mean to release a lock that was acquired with * <code>acquireLock</code> you should be using * <code>releaseLock</code>. * * @see #acquireLock * @see #releaseLock */ protected void clearLock (String name) { // clear the lock from the list if (ListUtil.clearEqual(_locks, name) == null) { // complain if we didn't find the lock Log.info("Unable to clear non-existent lock [lock=" + name + ", dobj=" + this + "]."); } } /** * Requests that this distributed object be destroyed. It does so by * queueing up an object destroyed event which the server will * validate and process. */ public void destroy () { postEvent(new ObjectDestroyedEvent(_oid)); } /** * Checks to ensure that the specified subscriber has access to this * object. This will be called before satisfying a subscription * request. If an {@link AccessController} has been specified for this * object, it will be used to determine whether or not to allow the * subscription request. If no controller is set, the subscription * will be allowed. * * @param sub the subscriber that will subscribe to this object. * * @return true if the subscriber has access to the object, false if * they do not. */ public boolean checkPermissions (Subscriber sub) { if (_controller != null) { return _controller.allowSubscribe(this, sub); } else { return true; } } public boolean checkPermissions (DEvent event) { if (_controller != null) { return _controller.allowDispatch(this, event); } else { return true; } } /** * Called by the distributed object manager after it has applied an * event to this object. This dispatches an event notification to all * of the listeners registered with this object. * * @param event the event that was just applied. */ public void notifyListeners (DEvent event) { if (_listeners == null) { return; } int llength = _listeners.length; for (int i = 0; i < llength; i++) { Object listener = _listeners[i]; if (listener == null) { continue; } try { // do any event specific notifications event.notifyListener(listener); // and notify them if they are listening for all events if (listener instanceof EventListener) { ((EventListener)listener).eventReceived(event); } } catch (Exception e) { Log.warning("Listener choked during notification " + "[list=" + listener + ", event=" + event + "]."); Log.logStackTrace(e); } } } /** * Called by the distributed object manager after it has applied an * event to this object. This dispatches an event notification to all * of the proxy listeners registered with this object. * * @param event the event that was just applied. */ public void notifyProxies (DEvent event) { if (_subs == null || event.isPrivate()) { return; } for (int ii = 0, ll = _subs.length; ii < ll; ii++) { Object sub = _subs[ii]; try { if (sub != null && sub instanceof ProxySubscriber) { ((ProxySubscriber)sub).eventReceived(event); } } catch (Exception e) { Log.warning("Proxy choked during notification " + "[sub=" + sub + ", event=" + event + "]."); Log.logStackTrace(e); } } } /** * Sets the named attribute to the specified value. This is only used * by the internals of the event dispatch mechanism and should not be * called directly by users. Use the generated attribute setter * methods instead. */ public void setAttribute (String name, Object value) throws ObjectAccessException { try { // for values that contain other values (arrays and DSets), we // need to clone them before putting them in the object // because otherwise a subsequent event might come along and // modify these values before the networking thread has had a // chance to propagate this event to the clients // i wish i could just call value.clone() but Object declares // clone() to be inaccessible, so we must cast the values to // their actual types to gain access to the widened clone() // methods if (value instanceof DSet) { value = ((DSet)value).clone(); } else if (value instanceof int[]) { value = ((int[])value).clone(); } else if (value instanceof String[]) { value = ((String[])value).clone(); } else if (value instanceof byte[]) { value = ((byte[])value).clone(); } else if (value instanceof long[]) { value = ((long[])value).clone(); } else if (value instanceof float[]) { value = ((float[])value).clone(); } else if (value instanceof short[]) { value = ((short[])value).clone(); } else if (value instanceof double[]) { value = ((double[])value).clone(); } // now actually set the value getField(name).set(this, value); } catch (Exception e) { String errmsg = "Attribute setting failure [name=" + name + ", value=" + value + ", vclass=" + value.getClass().getName() + "]."; throw new ObjectAccessException(errmsg, e); } } /** * Looks up the named attribute and returns a reference to it. This * should only be used by the internals of the event dispatch * mechanism and should not be called directly by users. Use the * generated attribute getter methods instead. */ public Object getAttribute (String name) throws ObjectAccessException { try { return getField(name).get(this); } catch (Exception e) { String errmsg = "Attribute getting failure [name=" + name + "]."; throw new ObjectAccessException(errmsg, e); } } /** * Posts a message event on this distrubuted object. */ public void postMessage (String name, Object[] args) { postEvent(new MessageEvent(_oid, name, args)); } /** * Posts the specified event either to our dobject manager or to the * compound event for which we are currently transacting. */ public void postEvent (DEvent event) { if (_tevent != null) { _tevent.postEvent(event); } else if (_omgr != null) { _omgr.postEvent(event); } else { Log.warning("Unable to post event, object has no omgr " + "[oid=" + getOid() + ", class=" + getClass().getName() + ", event=" + event + "]."); } } /** * Returns true if this object is active and registered with the * distributed object system. If an object is created via * <code>DObjectManager.createObject</code> it will be active until * such time as it is destroyed. */ public boolean isActive () { return _omgr != null; } /** * Don't call this function! It initializes this distributed object * with the supplied distributed object manager. This is called by the * distributed object manager when an object is created and registered * with the system. * * @see DObjectManager#createObject */ public void setManager (DObjectManager omgr) { _omgr = omgr; } /** * Don't call this function. It is called by the distributed object * manager when an object is created and registered with the system. * * @see DObjectManager#createObject */ public void setOid (int oid) { _oid = oid; } /** * Generates a concise string representation of this object. */ public String which () { StringBuffer buf = new StringBuffer(); which(buf); return buf.toString(); } /** * Used to briefly describe this distributed object. */ protected void which (StringBuffer buf) { buf.append(StringUtil.shortClassName(this)); buf.append(":").append(_oid); } /** * Generates a string representation of this object. */ public String toString () { StringBuffer buf = new StringBuffer(); toString(buf); return buf.append("]").toString(); } /** * Generates a string representation of this object. */ protected void toString (StringBuffer buf) { StringUtil.fieldsToString(buf, this, "\n"); if (buf.length() > 0) { buf.insert(0, "\n"); } buf.insert(0, _oid); buf.insert(0, "[oid="); } /** * Begins a transaction on this distributed object. In some * situations, it is desirable to cause multiple changes to * distributed object fields in one unified operation. Starting a * transaction causes all subsequent field modifications to be stored * in a single compound event which can then be committed, dispatching * and applying all included events in a single group. Additionally, * the events are dispatched over the network in a single unit which * can significantly enhance network efficiency. * * <p> When the transaction is complete, the caller must call {@link * #commitTransaction} or {@link CompoundEvent#commit} to commit the * transaction and release the object back to its normal * non-transacting state. If the caller decides not to commit their * transaction, they must call {@link #cancelTransaction} or {@link * CompoundEvent#cancel} to cancel the transaction. Failure to do so * will cause the pooch to be totally screwed. * * <p> Note: like all other distributed object operations, * transactions are not thread safe. It is expected that a single * thread will handle all distributed object operations and that * thread will begin and complete a transaction before giving up * control to unknown code which might try to operate on the * transacting distributed object. * * <p> Note also: if the object is already engaged in a transaction, a * transaction participant count will be incremented to note that an * additional call to {@link #commitTransaction} is required before * the transaction should actually be committed. Thus <em>every</em> * call to {@link #startTransaction} must be accompanied by a call to * either {@link #commitTransaction} or {@link * #cancelTransaction}. Additionally, if any transaction participant * cancels the transaction, the entire transaction is cancelled for * all participants, regardless of whether the other participants * attempted to commit the transaction. */ public void startTransaction () { if (_tevent != null) { _tcount++; } else { _tevent = new CompoundEvent(this, _omgr); } } /** * Commits the transaction in which this distributed object is * involved. * * @see CompoundEvent#commit */ public void commitTransaction () { if (_tevent == null) { String errmsg = "Cannot commit: not involved in a transaction " + "[dobj=" + this + "]"; throw new IllegalStateException(errmsg); } // if we are nested, we decrement our nesting count rather than // committing the transaction if (_tcount > 0) { _tcount } else { // we may actually be doing our final commit after someone // already cancelled this transaction, so we need to perform // the appropriate action at this point if (_tcancelled) { _tevent.cancel(); } else { _tevent.commit(); } } } /** * Returns true if this object is in the middle of a transaction or * false if it is not. */ public boolean inTransaction () { return (_tevent != null); } /** * Cancels the transaction in which this distributed object is * involved. * * @see CompoundEvent#cancel */ public void cancelTransaction () { if (_tevent == null) { String errmsg = "Cannot cancel: not involved in a transaction " + "[dobj=" + this + "]"; throw new IllegalStateException(errmsg); } // if we're in a nested transaction, make a note that it is to be // cancelled when all parties commit and decrement the nest count if (_tcount > 0) { _tcancelled = true; _tcount } else { _tevent.cancel(); } } /** * Removes this object from participation in any transaction in which * it might be taking part. */ protected void clearTransaction () { // sanity check if (_tcount != 0) { Log.warning("Transaction cleared with non-zero nesting count " + "[dobj=" + this + "]."); _tcount = 0; } // clear our transaction state _tevent = null; _tcancelled = false; } /** * Called by derived instances when an attribute setter method was * called. */ protected void requestAttributeChange (String name, Object value) { try { // dispatch an attribute changed event postEvent(new AttributeChangedEvent( _oid, name, value, getAttribute(name))); } catch (ObjectAccessException oae) { Log.warning("Unable to request attributeChange [name=" + name + ", value=" + value + ", error=" + oae + "]."); } } /** * Called by derived instances when an element updater method was * called. */ protected void requestElementUpdate (String name, Object value, int index) { try { // dispatch an attribute changed event Object oldValue = Array.get(getAttribute(name), index); postEvent(new ElementUpdatedEvent( _oid, name, value, oldValue, index)); } catch (ObjectAccessException oae) { Log.warning("Unable to request elementUpdate [name=" + name + ", value=" + value + ", index=" + index + ", error=" + oae + "]."); } } /** * Calls by derived instances when an oid adder method was called. */ protected void requestOidAdd (String name, int oid) { // dispatch an object added event postEvent(new ObjectAddedEvent(_oid, name, oid)); } /** * Calls by derived instances when an oid remover method was called. */ protected void requestOidRemove (String name, int oid) { // dispatch an object removed event postEvent(new ObjectRemovedEvent(_oid, name, oid)); } /** * Calls by derived instances when a set adder method was called. */ protected void requestEntryAdd (String name, DSet.Entry entry) { try { DSet set = (DSet)getAttribute(name); // if we're on the authoritative server, we update the set // immediately boolean alreadyApplied = false; if (_omgr != null && _omgr.isManager(this)) { if (!set.add(entry)) { Thread.dumpStack(); } alreadyApplied = true; } // dispatch an entry added event postEvent(new EntryAddedEvent(_oid, name, entry, alreadyApplied)); } catch (ObjectAccessException oae) { Log.warning("Unable to request entryAdd [name=" + name + ", entry=" + entry + ", error=" + oae + "]."); } } /** * Calls by derived instances when a set remover method was called. */ protected void requestEntryRemove (String name, Comparable key) { try { DSet set = (DSet)getAttribute(name); // if we're on the authoritative server, we update the set // immediately DSet.Entry oldEntry = null; if (_omgr != null && _omgr.isManager(this)) { oldEntry = set.get(key); set.removeKey(key); } // dispatch an entry removed event postEvent(new EntryRemovedEvent(_oid, name, key, oldEntry)); } catch (ObjectAccessException oae) { Log.warning("Unable to request entryRemove [name=" + name + ", key=" + key + ", error=" + oae + "]."); } } /** * Calls by derived instances when a set updater method was called. */ protected void requestEntryUpdate (String name, DSet.Entry entry) { try { DSet set = (DSet)getAttribute(name); // if we're on the authoritative server, we update the set // immediately DSet.Entry oldEntry = null; if (_omgr != null && _omgr.isManager(this)) { oldEntry = set.get(entry.getKey()); set.update(entry); } // dispatch an entry updated event postEvent(new EntryUpdatedEvent(_oid, name, entry, oldEntry)); } catch (ObjectAccessException oae) { Log.warning("Unable to request entryUpdate [name=" + name + ", entry=" + entry + ", error=" + oae + "]."); } } /** * Returns the {@link Field} with the specified name or null if there * is none such. */ protected final Field getField (String name) { int low = 0, high = _fields.length-1; while (low <= high) { int mid = (low + high) >> 1; Field midVal = _fields[mid]; int cmp = midVal.getName().compareTo(name); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { return midVal; // key found } } return null; // key not found. } /** Our object id. */ protected int _oid; /** An array of our fields, sorted for efficient lookup. */ protected transient Field[] _fields; /** A reference to our object manager. */ protected transient DObjectManager _omgr; /** The entity that tells us if an event or subscription request * should be allowed. */ protected transient AccessController _controller; /** A list of outstanding locks. */ protected transient Object[] _locks; /** Our subscribers list. */ protected transient Object[] _subs; /** Our event listeners list. */ protected transient Object[] _listeners; /** Our subscriber count. */ protected transient int _scount; /** The compound event associated with our transaction, if we're * currently in a transaction. */ protected transient CompoundEvent _tevent; /** The nesting depth of our current transaction. */ protected transient int _tcount; /** Whether or not our nested transaction has been cancelled. */ protected transient boolean _tcancelled; /** Indicates whether we want to be destroyed when our last subscriber * is removed. */ protected transient boolean _deathWish = false; /** Maintains a mapping of sorted field arrays for each distributed * object class. */ protected static HashMap _ftable = new HashMap(); /** Used to sort and search {@link #_fields}. */ protected static final Comparator FIELD_COMP = new Comparator() { public int compare (Object o1, Object o2) { return ((Field)o1).getName().compareTo(((Field)o2).getName()); } }; }
import java.sql.*; public class OpenDatabase { public void openConnection() throws SQLException { Connection conn = DriverManager.getConnection("jdbc url"); } public void openStatement(Connection conn) throws SQLException { Statement statement = conn.createStatement(); } public int doNotReport(Connection connection) throws SQLException { Statement statement = null; ResultSet rs = null; int id = 0; try { statement = connection.createStatement(); rs = statement.executeQuery("select blah blah"); if (!rs.next()) { throw new IllegalStateException("no row found"); } id = rs.getInt(1); } finally { try { if (rs != null) rs.close(); } catch (Throwable t) { t.printStackTrace(); } try { if (statement != null) statement.close(); } catch (Throwable t) { t.printStackTrace(); } try { if (connection != null) connection.close(); } catch (Throwable t) { t.printStackTrace(); } } return id; } } // vim:ts=3
package net.sf.picard.sam; import net.sf.picard.PicardException; import net.sf.picard.cmdline.Usage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.picard.util.PeekableIterator; import net.sf.picard.util.ProgressLogger; import net.sf.samtools.*; import net.sf.samtools.SAMFileHeader.SortOrder; import net.sf.picard.util.Log; import net.sf.samtools.util.RuntimeIOException; import net.sf.picard.cmdline.CommandLineProgram; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.StandardOptionDefinitions; import net.sf.picard.io.IoUtil; import net.sf.samtools.util.SortingCollection; /** * Class to fix mate pair information for all reads in a SAM file. Will run in fairly limited * memory unless there are lots of mate pairs that are far apart from each other in the file. * * @author Tim Fennell */ public class FixMateInformation extends CommandLineProgram { @Usage public final String USAGE = "Ensure that all mate-pair information is in sync between each read " + " and it's mate pair. If no OUTPUT file is supplied then the output is written to a temporary file " + " and then copied over the INPUT file. Reads marked with the secondary alignment flag are written " + "to the output file unchanged."; @Option(shortName=StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The input file to fix.") public List<File> INPUT; @Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, optional=true, doc="The output file to write to. If no output file is supplied, the input file is overwritten.") public File OUTPUT; @Option(shortName=StandardOptionDefinitions.SORT_ORDER_SHORT_NAME, optional=true, doc="Optional sort order if the OUTPUT file should be sorted differently than the INPUT file.") public SortOrder SORT_ORDER; private static final Log log = Log.getInstance(FixMateInformation.class); protected SAMFileWriter out; public static void main(final String[] args) { new FixMateInformation().instanceMainWithExit(args); } protected int doWork() { // Open up the input boolean allQueryNameSorted = true; final List<SAMFileReader> readers = new ArrayList<SAMFileReader>(); for (final File f : INPUT) { IoUtil.assertFileIsReadable(f); final SAMFileReader reader = new SAMFileReader(f); readers.add(new SAMFileReader(f)); if (reader.getFileHeader().getSortOrder() != SortOrder.queryname) allQueryNameSorted = false; } // Decide where to write the fixed file - into the specified output file // or into a temporary file that will overwrite the INPUT file eventually if (OUTPUT != null) OUTPUT = OUTPUT.getAbsoluteFile(); final boolean differentOutputSpecified = OUTPUT != null; if (differentOutputSpecified) { IoUtil.assertFileIsWritable(OUTPUT); } else if (INPUT.size() != 1) { throw new PicardException("Must specify either an explicit OUTPUT file or a single INPUT file to be overridden."); } else { final File soleInput = INPUT.get(0).getAbsoluteFile(); final File dir = soleInput.getParentFile().getAbsoluteFile(); try { IoUtil.assertFileIsWritable(soleInput); IoUtil.assertDirectoryIsWritable(dir); OUTPUT = File.createTempFile(soleInput.getName() + ".being_fixed.", ".bam", dir); } catch (IOException ioe) { throw new RuntimeIOException("Could not create tmp file in " + dir.getAbsolutePath()); } } // Get the input records merged and sorted by query name as needed final PeekableIterator<SAMRecord> iterator; final SAMFileHeader header; { // Deal with merging if necessary final Iterator<SAMRecord> tmp; if (INPUT.size() > 1) { final List<SAMFileHeader> headers = new ArrayList<SAMFileHeader>(readers.size()); for (final SAMFileReader reader : readers) { headers.add(reader.getFileHeader()); } final SortOrder sortOrder = (allQueryNameSorted? SortOrder.queryname: SortOrder.unsorted); final SamFileHeaderMerger merger = new SamFileHeaderMerger(sortOrder, headers, false); tmp = new MergingSamRecordIterator(merger, readers, false); header = merger.getMergedHeader(); } else { tmp = readers.get(0).iterator(); header = readers.get(0).getFileHeader(); } // And now deal with re-sorting if necessary if (allQueryNameSorted) { iterator = new PeekableIterator<SAMRecord>(tmp); } else { log.info("Sorting input into queryname order."); final SortingCollection<SAMRecord> sorter = SortingCollection.newInstance(SAMRecord.class, new BAMRecordCodec(header), new SAMRecordQueryNameComparator(), MAX_RECORDS_IN_RAM, TMP_DIR); while (tmp.hasNext()) { sorter.add(tmp.next()); } iterator = new PeekableIterator<SAMRecord>(sorter.iterator()) { @Override public void close() { super.close(); sorter.cleanup(); } }; log.info("Sorting by queryname complete."); } // Deal with the various sorting complications final SortOrder outputSortOrder = SORT_ORDER == null ? readers.get(0).getFileHeader().getSortOrder() : SORT_ORDER; log.info("Output will be sorted by " + outputSortOrder); header.setSortOrder(outputSortOrder); } if (CREATE_INDEX && header.getSortOrder() != SortOrder.coordinate){ throw new PicardException("Can't CREATE_INDEX unless sort order is coordinate"); } createSamFileWriter(header); log.info("Traversing query name sorted records and fixing up mate pair information."); final ProgressLogger progress = new ProgressLogger(log); while (iterator.hasNext()) { final SAMRecord rec1 = iterator.next(); if (rec1.getNotPrimaryAlignmentFlag()) { writeAlignment(rec1); progress.record(rec1); continue; } SAMRecord rec2 = null; // Keep peeking at next SAMRecord until one is found that is not marked as secondary alignment, // or until there are no more SAMRecords. while (iterator.hasNext()) { rec2 = iterator.peek(); if (rec2.getNotPrimaryAlignmentFlag()) { iterator.next(); writeAlignment(rec2); progress.record(rec2); rec2 = null; } else { break; } } if (rec2 != null && rec1.getReadName().equals(rec2.getReadName())) { iterator.next(); // consume the peeked record SamPairUtil.setMateInfo(rec1, rec2, header); writeAlignment(rec1); writeAlignment(rec2); progress.record(rec1, rec2); } else { writeAlignment(rec1); progress.record(rec1); } } iterator.close(); if (header.getSortOrder() == SortOrder.queryname) { log.info("Closing output file."); } else { log.info("Finished processing reads; re-sorting output file."); } closeWriter(); // Lastly if we're fixing in place, swap the files if (!differentOutputSpecified) { log.info("Replacing input file with fixed file."); final File soleInput = INPUT.get(0).getAbsoluteFile(); final File old = new File(soleInput.getParentFile(), soleInput.getName() + ".old"); if (!old.exists() && soleInput.renameTo(old)) { if (OUTPUT.renameTo(soleInput)) { if (!old.delete()) { log.warn("Could not delete old file: " + old.getAbsolutePath()); return 1; } if (CREATE_INDEX) { final File newIndex = new File(OUTPUT.getParent(), OUTPUT.getName().substring(0, OUTPUT.getName().length()-4) + ".bai"); final File oldIndex = new File(soleInput.getParent(), soleInput.getName().substring(0, soleInput.getName().length()-4) + ".bai"); if (!newIndex.renameTo(oldIndex)) { log.warn("Could not overwrite index file: " + oldIndex.getAbsolutePath()); } } } else { log.error("Could not move new file to " + soleInput.getAbsolutePath()); log.error("Input file preserved as: " + old.getAbsolutePath()); log.error("New file preserved as: " + OUTPUT.getAbsolutePath()); return 1; } } else { log.error("Could not move input file out of the way: " + soleInput.getAbsolutePath()); if (!OUTPUT.delete()) { log.error("Could not delete temporary file: " + OUTPUT.getAbsolutePath()); } return 1; } } return 0; } protected void createSamFileWriter(final SAMFileHeader header) { out = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, header.getSortOrder() == SortOrder.queryname, OUTPUT); } protected void writeAlignment(final SAMRecord sam) { out.addAlignment(sam); } protected void closeWriter() { out.close(); } }
package org.apache.fop.render.rtf; // Java import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Iterator; import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.Logger; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.EnumProperty; import org.apache.fop.fo.FOInputHandler; import org.apache.fop.fo.FObj; import org.apache.fop.datatypes.FixedLength; import org.apache.fop.fo.flow.BasicLink; import org.apache.fop.fo.flow.Block; import org.apache.fop.fo.flow.ExternalGraphic; import org.apache.fop.fo.flow.Footnote; import org.apache.fop.fo.flow.FootnoteBody; import org.apache.fop.fo.flow.Inline; import org.apache.fop.fo.flow.InstreamForeignObject; import org.apache.fop.fo.flow.Leader; import org.apache.fop.fo.flow.ListBlock; import org.apache.fop.fo.flow.ListItem; import org.apache.fop.fo.flow.ListItemLabel; import org.apache.fop.fo.flow.PageNumber; import org.apache.fop.fo.flow.Table; import org.apache.fop.fo.flow.TableColumn; import org.apache.fop.fo.flow.TableBody; import org.apache.fop.fo.flow.TableCell; import org.apache.fop.fo.flow.TableHeader; import org.apache.fop.fo.flow.TableRow; import org.apache.fop.fo.pagination.Flow; import org.apache.fop.fo.pagination.PageSequence; import org.apache.fop.fo.pagination.SimplePageMaster; import org.apache.fop.fo.Constants; import org.apache.fop.fo.FOText; import org.apache.fop.fo.Property; import org.apache.fop.fo.LengthProperty; import org.apache.fop.fo.StringProperty; import org.apache.fop.apps.Document; import org.apache.fop.render.rtf.rtflib.rtfdoc.ITableAttributes; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfAfterContainer; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfBeforeContainer; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfListContainer; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfTextrunContainer; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAfter; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfAttributes; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfBefore; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfDocumentArea; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfElement; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfExternalGraphic; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFile; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfFootnote; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfHyperLink; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfList; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem.RtfListItemLabel; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTextrun; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow; import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell; import org.apache.fop.render.rtf.rtflib.rtfdoc.IRtfTableContainer; import org.apache.fop.fonts.FontSetup; import org.xml.sax.SAXException; public class RTFHandler extends FOInputHandler { private RtfFile rtfFile; private final OutputStream os; private final Logger log = new ConsoleLogger(); private RtfSection sect; private RtfDocumentArea docArea; private int iNestCount; private boolean bDefer; //true, if each called handler shall be //processed at later time. private boolean bDeferredExecution; //true, if currently called handler was not //called while SAX parsing, but was called //by invokeDeferredEvent. private boolean bPrevHeaderSpecified = false;//true, if there has been a //header in any page-sequence private boolean bPrevFooterSpecified = false;//true, if there has been a //footer in any page-sequence private boolean bHeaderSpecified = false; //true, if there is a header //in current page-sequence private boolean bFooterSpecified = false; //true, if there is a footer //in current page-sequence private BuilderContext builderContext = new BuilderContext(null); private static final String ALPHA_WARNING = "WARNING: RTF renderer is " + "veryveryalpha at this time, see class org.apache.fop.rtf.renderer.RTFHandler"; /** * Creates a new RTF structure handler. * @param doc the Document for which this RTFHandler is processing * @param os OutputStream to write to */ public RTFHandler(Document doc, OutputStream os) { super(doc); this.os = os; bDefer = false; bDeferredExecution = false; iNestCount=0; FontSetup.setup(doc, null); log.warn(ALPHA_WARNING); } /** * @see org.apache.fop.fo.FOInputHandler#startDocument() */ public void startDocument() throws SAXException { // TODO sections should be created try { rtfFile = new RtfFile(new OutputStreamWriter(os)); docArea = rtfFile.startDocumentArea(); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? throw new SAXException(ioe); } } /** * @see org.apache.fop.fo.FOInputHandler#endDocument() */ public void endDocument() throws SAXException { try { rtfFile.flush(); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? throw new SAXException(ioe); } } /** * @see org.apache.fop.fo.FOInputHandler */ public void startPageSequence(PageSequence pageSeq) { try { if (bDefer) { return; } sect = docArea.newSection(); //read page size and margins, if specified Property prop; if ((prop = pageSeq.propertyList.get(Constants.PR_MASTER_REFERENCE)) != null) { String reference = prop.getString(); SimplePageMaster pagemaster = pageSeq.getLayoutMasterSet().getSimplePageMaster(reference); //only simple-page-master supported, so pagemaster may be null if (pagemaster != null) { sect.getRtfAttributes().set( PageAttributesConverter.convertPageAttributes( pagemaster.propertyList, null)); } } builderContext.pushContainer(sect); bHeaderSpecified = false; bFooterSpecified = false; } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? log.error("startPageSequence: " + ioe.getMessage()); //TODO throw new FOPException(ioe); } } /** * @see org.apache.fop.fo.FOInputHandler#endPageSequence(PageSequence) */ public void endPageSequence(PageSequence pageSeq) throws FOPException { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#startFlow(Flow) */ public void startFlow(Flow fl) { if (bDefer) { return; } try { if (fl.getFlowName().equals("xsl-region-body")) { // if there is no header in current page-sequence but there has been // a header in a previous page-sequence, insert an empty header. if (bPrevHeaderSpecified && !bHeaderSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfBefore.HEADER); final IRtfBeforeContainer contBefore = (IRtfBeforeContainer)builderContext.getContainer (IRtfBeforeContainer.class, true, this); contBefore.newBefore(attr); } // if there is no footer in current page-sequence but there has been // a footer in a previous page-sequence, insert an empty footer. if (bPrevFooterSpecified && !bFooterSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfAfter.FOOTER); final IRtfAfterContainer contAfter = (IRtfAfterContainer)builderContext.getContainer (IRtfAfterContainer.class, true, this); contAfter.newAfter(attr); } } else if (fl.getFlowName().equals("xsl-region-before")) { bHeaderSpecified = true; bPrevHeaderSpecified = true; final IRtfBeforeContainer c = (IRtfBeforeContainer)builderContext.getContainer( IRtfBeforeContainer.class, true, this); RtfAttributes beforeAttributes = ((RtfElement)c).getRtfAttributes(); if (beforeAttributes == null) { beforeAttributes = new RtfAttributes(); } beforeAttributes.set(RtfBefore.HEADER); RtfBefore before = c.newBefore(beforeAttributes); builderContext.pushContainer(before); } else if (fl.getFlowName().equals("xsl-region-after")) { bFooterSpecified = true; bPrevFooterSpecified = true; final IRtfAfterContainer c = (IRtfAfterContainer)builderContext.getContainer( IRtfAfterContainer.class, true, this); RtfAttributes afterAttributes = ((RtfElement)c).getRtfAttributes(); if (afterAttributes == null) { afterAttributes = new RtfAttributes(); } afterAttributes.set(RtfAfter.FOOTER); RtfAfter after = c.newAfter(afterAttributes); builderContext.pushContainer(after); } } catch (IOException ioe) { log.error("startFlow: " + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endFlow(Flow) */ public void endFlow(Flow fl) { if (bDefer) { return; } try { if (fl.getFlowName().equals("xsl-region-body")) { //just do nothing } else if (fl.getFlowName().equals("xsl-region-before")) { builderContext.popContainer(); } else if (fl.getFlowName().equals("xsl-region-after")) { builderContext.popContainer(); } } catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#startBlock(Block) */ public void startBlock(Block bl) { ++iNestCount; if (!bDeferredExecution) { //If startBlock was called while SAX parsing, defer processing of this //FO and all its elements until endBlock. This has to be done, because //attributes (for example while-space-treatment, linefeed-treatment) //are not available until endBlock. bDefer = true; } if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertAttributes(bl.propertyList, null); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.pushAttributes(rtfAttr); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? log.error("startBlock: " + ioe.getMessage()); throw new Error("IOException: " + ioe); } catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new Error("Exception: " + e); } } /** * @see org.apache.fop.fo.FOInputHandler#endBlock(Block) */ public void endBlock(Block bl) { --iNestCount; if (!bDeferredExecution && iNestCount==0) { //If endBlock was called while SAX parsing, and the passed FO is Block //nested within another Block, stop deferring. //Now process all deferred FOs. bDefer = false; bDeferredExecution=true; recurseFObj(bl); bDeferredExecution=false; //exit function, because the code has already beed executed while //deferred execution. return; } if(bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.popAttributes(); } catch (IOException ioe) { log.error("startBlock:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#startTable(Table) */ public void startTable(Table tbl) { if (bDefer) { return; } // create an RtfTable in the current table container TableContext tableContext = new TableContext(builderContext); try { RtfAttributes atts = TableAttributesConverter.convertTableAttributes(tbl.propertyList); final IRtfTableContainer tc = (IRtfTableContainer)builderContext.getContainer( IRtfTableContainer.class, true, null); builderContext.pushContainer(tc.newTable(atts, tableContext)); } catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new Error(e.getMessage()); } builderContext.pushTableContext(tableContext); } /** * @see org.apache.fop.fo.FOInputHandler#endTable(Table) */ public void endTable(Table tbl) { if (bDefer) { return; } builderContext.popTableContext(); builderContext.popContainer(); } /** * * @param tc TableColumn that is starting; */ public void startColumn(TableColumn tc) { if (bDefer) { return; } try { Integer iWidth = new Integer(tc.getColumnWidth() / 1000); builderContext.getTableContext().setNextColumnWidth(iWidth.toString() + "pt"); builderContext.getTableContext().setNextColumnRowSpanning(new Integer(0), null); } catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * * @param tc TableColumn that is ending; */ public void endColumn(TableColumn tc) { if (bDefer) { return; } } /** * @see org.apache.fop.fo.FOInputHandler#startHeader(TableBody) */ public void startHeader(TableBody th) { } /** * @see org.apache.fop.fo.FOInputHandler#endHeader(TableBody) */ public void endHeader(TableBody th) { } /** * @see org.apache.fop.fo.FOInputHandler#startFooter(TableBody) */ public void startFooter(TableBody tf) { } /** * @see org.apache.fop.fo.FOInputHandler#endFooter(TableBody) */ public void endFooter(TableBody tf) { } /** * * @param inl Inline that is starting. */ public void startInline(Inline inl) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes(inl.propertyList, null); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.pushAttributes(rtfAttr); } catch (IOException ioe) { log.error("startInline:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new Error(fe.getMessage()); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new Error(e.getMessage()); } } /** * * @param inl Inline that is ending. */ public void endInline(Inline inl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.popAttributes(); } catch (IOException ioe) { log.error("startInline:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#startBody(TableBody) */ public void startBody(TableBody tb) { if (bDefer) { return; } try { RtfAttributes atts = TableAttributesConverter.convertRowAttributes (tb.propertyList, null); RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(atts); } catch (Exception e) { log.error("startBody: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endBody(TableBody) */ public void endBody(TableBody tb) { if (bDefer) { return; } try { RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(null); } catch (Exception e) { log.error("endBody: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#startRow(TableRow) */ public void startRow(TableRow tr) { if (bDefer) { return; } try { // create an RtfTableRow in the current RtfTable final RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, null); RtfAttributes atts = TableAttributesConverter.convertRowAttributes(tr.propertyList, tbl.getHeaderAttribs()); if (tr.getParent() instanceof TableHeader) { atts.set(ITableAttributes.ATTR_HEADER); } builderContext.pushContainer(tbl.newTableRow(atts)); // reset column iteration index to correctly access column widths builderContext.getTableContext().selectFirstColumn(); } catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endRow(TableRow) */ public void endRow(TableRow tr) { if (bDefer) { return; } builderContext.popContainer(); builderContext.getTableContext().decreaseRowSpannings(); } /** * @see org.apache.fop.fo.FOInputHandler#startCell(TableCell) */ public void startCell(TableCell tc) { if (bDefer) { return; } try { TableContext tctx = builderContext.getTableContext(); final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class, true, null); //while the current column is in row-spanning, act as if //a vertical merged cell would have been specified. while (tctx.getNumberOfColumns() > tctx.getColumnIndex() && tctx.getColumnRowSpanningNumber().intValue() > 0) { row.newTableCellMergedVertically((int)tctx.getColumnWidth(), tctx.getColumnRowSpanningAttrs()); tctx.selectNextColumn(); } //get the width of the currently started cell float width = tctx.getColumnWidth(); // create an RtfTableCell in the current RtfTableRow RtfAttributes atts = TableAttributesConverter.convertCellAttributes(tc.propertyList); RtfTableCell cell = row.newTableCell((int)width, atts); //process number-rows-spanned attribute Property p = null; if ((p = tc.propertyList.get(Constants.PR_NUMBER_ROWS_SPANNED)) != null) { // Start vertical merge cell.setVMerge(RtfTableCell.MERGE_START); // set the number of rows spanned tctx.setCurrentColumnRowSpanning(new Integer(p.getNumber().intValue()), cell.getRtfAttributes()); } else { tctx.setCurrentColumnRowSpanning(new Integer(1), null); } builderContext.pushContainer(cell); } catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endCell(TableCell) */ public void endCell(TableCell tc) { if (bDefer) { return; } builderContext.popContainer(); builderContext.getTableContext().selectNextColumn(); } // Lists /** * @see org.apache.fop.fo.FOInputHandler#startList(ListBlock) */ public void startList(ListBlock lb) { if (bDefer) { return; } try { // create an RtfList in the current list container final IRtfListContainer c = (IRtfListContainer)builderContext.getContainer( IRtfListContainer.class, true, this); final RtfList newList = c.newList( ListAttributesConverter.convertAttributes(lb.propertyList)); builderContext.pushContainer(newList); } catch (IOException ioe) { log.error("startList: " + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new Error(fe.getMessage()); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endList(ListBlock) */ public void endList(ListBlock lb) { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#startListItem(ListItem) */ public void startListItem(ListItem li) { if (bDefer) { return; } // create an RtfListItem in the current RtfList try { final RtfList list = (RtfList)builderContext.getContainer( RtfList.class, true, this); builderContext.pushContainer(list.newListItem()); } catch (IOException ioe) { log.error("startList: " + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new Error(fe.getMessage()); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endListItem(ListItem) */ public void endListItem(ListItem li) { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#startListLabel() */ public void startListLabel() { if (bDefer) { return; } try { RtfListItem item = (RtfListItem)builderContext.getContainer(RtfListItem.class, true, this); RtfListItemLabel label = item.new RtfListItemLabel(item); builderContext.pushContainer(label); } catch (IOException ioe) { log.error("startPageNumber:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endListLabel() */ public void endListLabel() { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#startListBody() */ public void startListBody() { } /** * @see org.apache.fop.fo.FOInputHandler#endListBody() */ public void endListBody() { } // Static Regions /** * @see org.apache.fop.fo.FOInputHandler#startStatic() */ public void startStatic() { } /** * @see org.apache.fop.fo.FOInputHandler#endStatic() */ public void endStatic() { } /** * @see org.apache.fop.fo.FOInputHandler#startMarkup() */ public void startMarkup() { } /** * @see org.apache.fop.fo.FOInputHandler#endMarkup() */ public void endMarkup() { } /** * @see org.apache.fop.fo.FOInputHandler#startLink(BasicLink basicLink) */ public void startLink(BasicLink basicLink) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun=container.getTextrun(); RtfHyperLink link=textrun.addHyperlink(new RtfAttributes()); StringProperty internal = (StringProperty)basicLink.propertyList.get(Constants.PR_INTERNAL_DESTINATION); StringProperty external = (StringProperty)basicLink.propertyList.get(Constants.PR_EXTERNAL_DESTINATION); if(external != null) { link.setExternalURL(external.getString()); } else if(internal != null) { link.setInternalURL(internal.getString()); } builderContext.pushContainer(link); } catch (IOException ioe) { log.error("startLink:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#endLink() */ public void endLink() { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#image(ExternalGraphic) */ public void image(ExternalGraphic eg) { if (bDefer) { return; } try { final IRtfTextrunContainer c = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); final RtfExternalGraphic newGraphic = c.getTextrun().newImage(); Property p = null; //get source file if ((p = eg.propertyList.get(Constants.PR_SRC)) != null) { newGraphic.setURL (p.getString()); } else { log.error("The attribute 'src' of <fo:external-graphic> is required."); return; } //get scaling if ((p = eg.propertyList.get(Constants.PR_SCALING)) != null) { EnumProperty e = (EnumProperty)p; if (p.getEnum() == Constants.UNIFORM) { newGraphic.setScaling ("uniform"); } } //get width if ((p = eg.propertyList.get(Constants.PR_WIDTH)) != null) { LengthProperty lengthProp = (LengthProperty)p; if (lengthProp.getLength() instanceof FixedLength) { Float f = new Float(lengthProp.getLength().getValue() / 1000f); String sValue = f.toString() + "pt"; newGraphic.setWidth(sValue); } } //get height if ((p = eg.propertyList.get(Constants.PR_HEIGHT)) != null) { LengthProperty lengthProp = (LengthProperty)p; if (lengthProp.getLength() instanceof FixedLength) { Float f = new Float(lengthProp.getLength().getValue() / 1000f); String sValue = f.toString() + "pt"; newGraphic.setHeight(sValue); } } //TODO: make this configurable: // int compression = m_context.m_options.getRtfExternalGraphicCompressionRate (); int compression = 0; if (compression != 0) { if (!newGraphic.setCompressionRate(compression)) { log.warn("The compression rate " + compression + " is invalid. The value has to be between 1 and 100 %."); } } } catch (Exception e) { log.error("image: " + e.getMessage()); } } /** * @see org.apache.fop.fo.FOInputHandler#pageRef() */ public void pageRef() { } /** * @see org.apache.fop.fo.FOInputHandler#foreignObject(InstreamForeignObject) */ public void foreignObject(InstreamForeignObject ifo) { } /** * @see org.apache.fop.fo.FOInputHandler#startFootnote(Footnote) */ public void startFootnote(Footnote footnote) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertAttributes(footnote.propertyList, null); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfFootnote rtfFootnote = textrun.addFootnote(); builderContext.pushContainer(rtfFootnote); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? log.error("startFootnote: " + ioe.getMessage()); throw new Error("IOException: " + ioe); } catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new Error("Exception: " + e); } } /** * @see org.apache.fop.fo.FOInputHandler#endFootnote(Footnote) */ public void endFootnote(Footnote footnote) { if (bDefer) { return; } builderContext.popContainer(); } /** * @see org.apache.fop.fo.FOInputHandler#startFootnoteBody(FootnoteBody) */ public void startFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.startBody(); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? log.error("startFootnoteBody: " + ioe.getMessage()); throw new Error("IOException: " + ioe); } catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new Error("Exception: " + e); } } /** * @see org.apache.fop.fo.FOInputHandler#endFootnoteBody(FootnoteBody) */ public void endFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.endBody(); } catch (IOException ioe) { // TODO could we throw Exception in all FOInputHandler events? log.error("endFootnoteBody: " + ioe.getMessage()); throw new Error("IOException: " + ioe); } catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new Error("Exception: " + e); } } /** * @see org.apache.fop.fo.FOInputHandler#leader(Leader) */ public void leader(Leader l) { } /** * @see org.apache.fop.fo.FOInputHandler#characters(char[], int, int) */ public void characters(char[] data, int start, int length) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addString(new String(data, start, length)); } catch (IOException ioe) { // FIXME could we throw Exception in all FOInputHandler events? log.error("characters: " + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("characters:" + e.getMessage()); throw new Error(e.getMessage()); } } /** * * @param pagenum PageNumber that is starting. */ public void startPageNumber(PageNumber pagenum) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes( pagenum.propertyList, null); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumber(rtfAttr); } catch (IOException ioe) { log.error("startPageNumber:" + ioe.getMessage()); throw new Error(ioe.getMessage()); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new Error(e.getMessage()); } } /** * * @param pagenum PageNumber that is ending. */ public void endPageNumber(PageNumber pagenum) { if (bDefer) { return; } } /** * Calls the appropriate event handler for the passed FObj. * * @param fobj FO-object whose event is to be called * @param bStart TRUE calls the start handler, FALSE the end handler */ private void invokeDeferredEvent(FObj fobj, boolean bStart) { if (fobj instanceof Block) { if (bStart) { startBlock( (Block) fobj); } else { endBlock( (Block) fobj); } } else if (fobj instanceof Inline) { if (bStart) { startInline( (Inline) fobj); } else { endInline( (Inline) fobj); } } else if (fobj instanceof FOText) { if (bStart) { FOText text = (FOText) fobj; characters(text.ca, 0, text.length); } } else if (fobj instanceof BasicLink) { if (bStart) { startLink( (BasicLink) fobj); } else { endLink(); } } else if (fobj instanceof PageNumber) { if (bStart) { startPageNumber( (PageNumber) fobj); } else { endPageNumber( (PageNumber) fobj); } } else if (fobj instanceof Footnote) { if (bStart) { startFootnote( (Footnote) fobj); } else { endFootnote( (Footnote) fobj); } } else if (fobj instanceof FootnoteBody) { if (bStart) { startFootnoteBody( (FootnoteBody) fobj); } else { endFootnoteBody( (FootnoteBody) fobj); } } else if (fobj instanceof ListBlock) { if (bStart) { startList( (ListBlock) fobj); } else { endList( (ListBlock) fobj); } } else if (fobj instanceof ListItem) { if (bStart) { startListItem( (ListItem) fobj); } else { endListItem( (ListItem) fobj); } } else if (fobj instanceof ListItemLabel) { if (bStart) { startListLabel(); } else { endListLabel(); } } else if (fobj instanceof Table) { if (bStart) { startTable( (Table) fobj); } else { endTable( (Table) fobj); } } else if (fobj instanceof TableColumn) { if (bStart) { startColumn( (TableColumn) fobj); } else { endColumn( (TableColumn) fobj); } } else if (fobj instanceof TableRow) { if (bStart) { startRow( (TableRow) fobj); } else { endRow( (TableRow) fobj); } } else if (fobj instanceof TableCell) { if (bStart) { startCell( (TableCell) fobj); } else { endCell( (TableCell) fobj); } } } /** * Calls the event handlers for the passed FObj and all its elements. * * @param fobj FO-object which shall be recursed */ private void recurseFObj(FObj fobj) { invokeDeferredEvent(fobj, true); if (fobj.children!=null) { for(Iterator it=fobj.children.iterator();it.hasNext();) { recurseFObj( (FObj) it.next() ); } } invokeDeferredEvent(fobj, false); } }
package org.wte4j.examples.showcase.server.hsql; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import javax.sql.DataSource; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.StaticApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; public class ShowCaseDbInitializerTest { ApplicationContext context; @Test public void initializeDatabase() throws IOException { ApplicationContext context = new StaticApplicationContext(); Path directory = Files.createTempDirectory("database"); ShowCaseDbInitializer showCaseDbInitializer = new ShowCaseDbInitializer(context); HsqlServerBean serverBean = showCaseDbInitializer.createDatabase(directory); try { serverBean.startDatabase(); DataSource dataSource = serverBean.createDataSource(); assertConent(dataSource); } finally { serverBean.stopDatabase(); deleteDirectory(directory); } } private void assertConent(DataSource dataSource) { JdbcTemplate template = new JdbcTemplate(dataSource); long personCount = template.queryForObject("select count(id) from person", Long.class); assertEquals(2L, personCount); } private void deleteDirectory(Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.deleteIfExists(file); return super.visitFile(file, attrs); } }); Files.deleteIfExists(path); } }
package org.apache.log4j.xml; import java.util.*; import java.net.URL; import org.w3c.dom.*; import java.lang.reflect.Method; import org.apache.log4j.*; import org.apache.log4j.spi.*; import org.apache.log4j.or.RendererMap; import org.apache.log4j.helpers.*; import org.apache.log4j.config.PropertySetter; import org.xml.sax.InputSource; import java.io.FileInputStream; import java.io.InputStream; import java.io.Reader; import java.io.IOException; import java.net.URL; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.FactoryConfigurationError; // Contributors: Mark Womack // Arun Katkere public class DOMConfigurator implements Configurator { static final String CONFIGURATION_TAG = "log4j:configuration"; static final String OLD_CONFIGURATION_TAG = "configuration"; static final String RENDERER_TAG = "renderer"; static final String APPENDER_TAG = "appender"; static final String APPENDER_REF_TAG = "appender-ref"; static final String PARAM_TAG = "param"; static final String LAYOUT_TAG = "layout"; static final String CATEGORY = "category"; static final String LOGGER = "logger"; static final String LOGGER_REF = "logger-ref"; static final String CATEGORY_FACTORY_TAG = "categoryFactory"; static final String NAME_ATTR = "name"; static final String CLASS_ATTR = "class"; static final String VALUE_ATTR = "value"; static final String ROOT_TAG = "root"; static final String ROOT_REF = "root-ref"; static final String LEVEL_TAG = "level"; static final String PRIORITY_TAG = "priority"; static final String FILTER_TAG = "filter"; static final String ERROR_HANDLER_TAG = "errorHandler"; static final String REF_ATTR = "ref"; static final String ADDITIVITY_ATTR = "additivity"; static final String THRESHOLD_ATTR = "threshold"; static final String CONFIG_DEBUG_ATTR = "configDebug"; static final String INTERNAL_DEBUG_ATTR = "debug"; static final String RENDERING_CLASS_ATTR = "renderingClass"; static final String RENDERED_CLASS_ATTR = "renderedClass"; static final String EMPTY_STR = ""; static final Class[] ONE_STRING_PARAM = new Class[] {String.class}; final static String dbfKey = "javax.xml.parsers.DocumentBuilderFactory"; // key: appenderName, value: appender Hashtable appenderBag; Properties props; LoggerRepository repository; /** No argument constructor. */ public DOMConfigurator () { appenderBag = new Hashtable(); } /** Used internally to parse appenders by IDREF name. */ protected Appender findAppenderByName(Document doc, String appenderName) { Appender appender = (Appender) appenderBag.get(appenderName); if(appender != null) { return appender; } else { // Doesn't work on DOM Level 1 : // Element element = doc.getElementById(appenderName); // Endre's hack: Element element = null; NodeList list = doc.getElementsByTagName("appender"); for (int t=0; t < list.getLength(); t++) { Node node = list.item(t); NamedNodeMap map= node.getAttributes(); Node attrNode = map.getNamedItem("name"); if (appenderName.equals(attrNode.getNodeValue())) { element = (Element) node; break; } } // Hack finished. if(element == null) { LogLog.error("No appender named ["+appenderName+"] could be found."); return null; } else { appender = parseAppender(element); appenderBag.put(appenderName, appender); return appender; } } } /** Used internally to parse appenders by IDREF element. */ protected Appender findAppenderByReference(Element appenderRef) { String appenderName = subst(appenderRef.getAttribute(REF_ATTR)); Document doc = appenderRef.getOwnerDocument(); return findAppenderByName(doc, appenderName); } /** Used internally to parse an appender element. */ protected Appender parseAppender (Element appenderElement) { String className = subst(appenderElement.getAttribute(CLASS_ATTR)); LogLog.debug("Class name: [" + className+']'); try { Object instance = Loader.loadClass(className).newInstance(); Appender appender = (Appender)instance; PropertySetter propSetter = new PropertySetter(appender); appender.setName(subst(appenderElement.getAttribute(NAME_ATTR))); NodeList children = appenderElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); /* We're only interested in Elements */ if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element)currentNode; // Parse appender parameters if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } // Set appender layout else if (currentElement.getTagName().equals(LAYOUT_TAG)) { appender.setLayout(parseLayout(currentElement)); } // Add filters else if (currentElement.getTagName().equals(FILTER_TAG)) { parseFilters(currentElement, appender); } else if (currentElement.getTagName().equals(ERROR_HANDLER_TAG)) { parseErrorHandler(currentElement, appender); } else if (currentElement.getTagName().equals(APPENDER_REF_TAG)) { String refName = subst(currentElement.getAttribute(REF_ATTR)); if(appender instanceof AppenderAttachable) { AppenderAttachable aa = (AppenderAttachable) appender; LogLog.debug("Attaching appender named ["+ refName+ "] to appender named ["+ appender.getName()+"]."); aa.addAppender(findAppenderByReference(currentElement)); } else { LogLog.error("Requesting attachment of appender named ["+ refName+ "] to appender named ["+ appender.getName()+ "] which does not implement org.apache.log4j.spi.AppenderAttachable."); } } } } propSetter.activate(); return appender; } /* Yes, it's ugly. But all of these exceptions point to the same problem: we can't create an Appender */ catch (Exception oops) { LogLog.error("Could not create an Appender. Reported error follows.", oops); return null; } } /** Used internally to parse an {@link ErrorHandler} element. */ protected void parseErrorHandler(Element element, Appender appender) { ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName( subst(element.getAttribute(CLASS_ATTR)), org.apache.log4j.spi.ErrorHandler.class, null); if(eh != null) { eh.setAppender(appender); PropertySetter propSetter = new PropertySetter(eh); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } else if(tagName.equals(APPENDER_REF_TAG)) { eh.setBackupAppender(findAppenderByReference(currentElement)); } else if(tagName.equals(LOGGER_REF)) { String loggerName = currentElement.getAttribute(REF_ATTR); Logger logger = repository.getLogger(loggerName); eh.setLogger(logger); } else if(tagName.equals(ROOT_REF)) { Logger root = repository.getRootLogger(); eh.setLogger(root); } } } propSetter.activate(); appender.setErrorHandler(eh); } } /** Used internally to parse a filter element. */ protected void parseFilters(Element element, Appender appender) { String clazz = subst(element.getAttribute(CLASS_ATTR)); Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz, Filter.class, null); if(filter != null) { PropertySetter propSetter = new PropertySetter(filter); NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } } } propSetter.activate(); appender.addFilter(filter); } } /** Used internally to parse an category element. */ protected void parseCategory (Element loggerElement) { // Create a new org.apache.log4j.Category object from the <category> element. String catName = subst(loggerElement.getAttribute(NAME_ATTR)); Logger cat; String className = subst(loggerElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.debug("Retreiving an instance of org.apache.log4j.Logger."); cat = repository.getLogger(catName); } else { LogLog.debug("Desired logger sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method getInstanceMethod = clazz.getMethod("getLogger", ONE_STRING_PARAM); cat = (Logger) getInstanceMethod.invoke(null, new Object[] {catName}); } catch (Exception oops) { LogLog.error("Could not retrieve category ["+catName+ "]. Reported error follows.", oops); return; } } // Setting up a category needs to be an atomic operation, in order // to protect potential log operations while category // configuration is in progress. synchronized(cat) { boolean additivity = OptionConverter.toBoolean( subst(loggerElement.getAttribute(ADDITIVITY_ATTR)), true); LogLog.debug("Setting ["+cat.getName()+"] additivity to ["+additivity+"]."); cat.setAdditivity(additivity); parseChildrenOfLoggerElement(loggerElement, cat, false); } } /** Used internally to parse the category factory element. */ protected void parseCategoryFactory(Element factoryElement) { String className = subst(factoryElement.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { LogLog.error("Category Factory tag " + CLASS_ATTR + " attribute not found."); LogLog.debug("No Category Factory configured."); } else { LogLog.debug("Desired category factory: ["+className+']'); Object catFactory = OptionConverter.instantiateByClassName(className, LoggerFactory.class, null); PropertySetter propSetter = new PropertySetter(catFactory); Element currentElement = null; Node currentNode = null; NodeList children = factoryElement.getChildNodes(); final int length = children.getLength(); for (int loop=0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element)currentNode; if (currentElement.getTagName().equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } } } } } /** Used internally to parse the roor category element. */ protected void parseRoot (Element rootElement) { Logger root = repository.getRootLogger(); // category configuration needs to be atomic synchronized(root) { parseChildrenOfLoggerElement(rootElement, root, true); } } /** Used internally to parse the children of a category element. */ protected void parseChildrenOfLoggerElement(Element catElement, Logger cat, boolean isRoot) { PropertySetter propSetter = new PropertySetter(cat); // Remove all existing appenders from cat. They will be // reconstructed if need be. cat.removeAllAppenders(); NodeList children = catElement.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if (tagName.equals(APPENDER_REF_TAG)) { Element appenderRef = (Element) currentNode; Appender appender = findAppenderByReference(appenderRef); String refName = subst(appenderRef.getAttribute(REF_ATTR)); if(appender != null) LogLog.debug("Adding appender named ["+ refName+ "] to category ["+cat.getName()+"]."); else LogLog.debug("Appender named ["+ refName + "] not found."); cat.addAppender(appender); } else if(tagName.equals(LEVEL_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PRIORITY_TAG)) { parseLevel(currentElement, cat, isRoot); } else if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } } } propSetter.activate(); } /** Used internally to parse a layout element. */ protected Layout parseLayout (Element layout_element) { String className = subst(layout_element.getAttribute(CLASS_ATTR)); LogLog.debug("Parsing layout of class: \""+className+"\""); try { Object instance = Loader.loadClass(className).newInstance(); Layout layout = (Layout)instance; PropertySetter propSetter = new PropertySetter(layout); NodeList params = layout_element.getChildNodes(); final int length = params.getLength(); for (int loop = 0; loop < length; loop++) { Node currentNode = (Node)params.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) currentNode; String tagName = currentElement.getTagName(); if(tagName.equals(PARAM_TAG)) { setParameter(currentElement, propSetter); } } } propSetter.activate(); return layout; } catch (Exception oops) { LogLog.error("Could not create the Layout. Reported error follows.", oops); return null; } } protected void parseRenderer(Element element) { String renderingClass = subst(element.getAttribute(RENDERING_CLASS_ATTR)); String renderedClass = subst(element.getAttribute(RENDERED_CLASS_ATTR)); if(repository instanceof RendererSupport) { RendererMap.addRenderer((RendererSupport) repository, renderedClass, renderingClass); } } /** Used internally to parse a level element. */ protected void parseLevel(Element element, Logger logger, boolean isRoot) { String catName = logger.getName(); if(isRoot) { catName = "root"; } String priStr = subst(element.getAttribute(VALUE_ATTR)); LogLog.debug("Level value for "+catName+" is ["+priStr+"]."); if(INHERITED.equals(priStr)) { if(isRoot) { LogLog.error("Root level cannot be inherited. Ignoring directive."); } else { logger.setLevel(null); } } else { String className = subst(element.getAttribute(CLASS_ATTR)); if(EMPTY_STR.equals(className)) { logger.setLevel(Level.toLevel(priStr)); } else { LogLog.debug("Desired Level sub-class: ["+className+']'); try { Class clazz = Loader.loadClass(className); Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM); Level pri = (Level) toLevelMethod.invoke(null, new Object[] {priStr}); logger.setLevel(pri); } catch (Exception oops) { LogLog.error("Could not create level ["+priStr+ "]. Reported error follows.", oops); return; } } } LogLog.debug(catName + " level set to " + logger.getLevel()); } protected void setParameter(Element elem, PropertySetter propSetter) { String name = subst(elem.getAttribute(NAME_ATTR)); String value = (elem.getAttribute(VALUE_ATTR)); value = subst(OptionConverter.convertSpecialChars(value)); propSetter.setProperty(name, value); } /** Configure log4j using a <code>configuration</code> element as defined in the log4j.dtd. */ static public void configure (Element element) { DOMConfigurator configurator = new DOMConfigurator(); configurator.doConfigure(element, LogManager.getLoggerRepository()); } /** Like {@link #configureAndWatch(String, long)} except that the default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is used. @param configFilename A log4j configuration file in XML format. */ static public void configureAndWatch(String configFilename) { configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY); } /** Read the configuration file <code>configFilename</code> if it exists. Moreover, a thread will be created that will periodically check if <code>configFilename</code> has been created or modified. The period is determined by the <code>delay</code> argument. If a change or file creation is detected, then <code>configFilename</code> is read to configure log4j. @param configFilename A log4j configuration file in XML format. @param delay The delay in milliseconds to wait between each check. */ static public void configureAndWatch(String configFilename, long delay) { XMLWatchdog xdog = new XMLWatchdog(configFilename); xdog.setDelay(delay); xdog.start(); } public void doConfigure(String filename, LoggerRepository repository) { FileInputStream fis = null; try { fis = new FileInputStream(filename); doConfigure(fis, repository); } catch(IOException e) { LogLog.error("Could not open ["+filename+"].", e); } finally { if (fis != null) { try { fis.close(); } catch(java.io.IOException e) { LogLog.error("Could not close ["+filename+"].", e); } } } } public void doConfigure(URL url, LoggerRepository repository) { try { doConfigure(url.openStream(), repository); } catch(IOException e) { LogLog.error("Could not open ["+url+"].", e); } } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(InputStream inputStream, LoggerRepository repository) throws FactoryConfigurationError { doConfigure(new InputSource(inputStream), repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ public void doConfigure(Reader reader, LoggerRepository repository) throws FactoryConfigurationError { doConfigure(new InputSource(reader), repository); } /** Configure log4j by reading in a log4j.dtd compliant XML configuration file. */ protected void doConfigure(InputSource inputSource, LoggerRepository repository) throws FactoryConfigurationError { DocumentBuilderFactory dbf = null; this.repository = repository; try { LogLog.debug("System property is :"+ OptionConverter.getSystemProperty(dbfKey, null)); dbf = DocumentBuilderFactory.newInstance(); LogLog.debug("Standard DocumentBuilderFactory search succeded."); LogLog.debug("DocumentBuilderFactory is: "+dbf.getClass().getName()); } catch(FactoryConfigurationError fce) { Exception e = fce.getException(); LogLog.debug("Could not instantiate a DocumentBuilderFactory.", e); throw fce; } try { // This makes ID/IDREF attributes to have a meaning. Don't ask // me why. dbf.setValidating(true); //dbf.setNamespaceAware(true); DocumentBuilder docBuilder = dbf.newDocumentBuilder(); docBuilder.setErrorHandler(new SAXErrorHandler()); Class clazz = this.getClass(); URL dtdURL = clazz.getResource("/org/apache/log4j/xml/log4j.dtd"); if(dtdURL == null) { LogLog.error("Could not find [log4j.dtd]. Used ["+clazz.getClassLoader()+ "] class loader in the search."); } else { LogLog.debug("URL to log4j.dtd is [" + dtdURL.toString()+"]."); inputSource.setSystemId(dtdURL.toString()); } Document doc = docBuilder.parse(inputSource); parse(doc.getDocumentElement()); } catch (Exception e) { // I know this is miserable... LogLog.error("Could not parse input source ["+inputSource+"].", e); } } /** Configure by taking in an DOM element. */ public void doConfigure(Element element, LoggerRepository repository) { this.repository = repository; parse(element); } /** A static version of {@link #doConfigure(String, LoggerRepository)}. */ static public void configure(String filename) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } /** A static version of {@link #doConfigure(URL, LoggerRepository)}. */ static public void configure(URL url) throws FactoryConfigurationError { new DOMConfigurator().doConfigure(url, LogManager.getLoggerRepository()); } /** Used internally to configure the log4j framework by parsing a DOM tree of XML elements based on <a href="doc-files/log4j.dtd">log4j.dtd</a>. */ protected void parse(Element element) { String rootElementName = element.getTagName(); if (!rootElementName.equals(CONFIGURATION_TAG)) { if(rootElementName.equals(OLD_CONFIGURATION_TAG)) { LogLog.warn("The <"+OLD_CONFIGURATION_TAG+ "> element has been deprecated."); LogLog.warn("Use the <"+CONFIGURATION_TAG+"> element instead."); } else { LogLog.error("DOM element is - not a <"+CONFIGURATION_TAG+"> element."); return; } } String debugAttrib = subst(element.getAttribute(INTERNAL_DEBUG_ATTR)); LogLog.debug("debug attribute= \"" + debugAttrib +"\"."); // if the log4j.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if(!debugAttrib.equals("") && !debugAttrib.equals("null")) { LogLog.setInternalDebugging(OptionConverter.toBoolean(debugAttrib, true)); } else LogLog.debug("Ignoring " + INTERNAL_DEBUG_ATTR + " attribute."); String confDebug = subst(element.getAttribute(CONFIG_DEBUG_ATTR)); if(!confDebug.equals("") && !confDebug.equals("null")) { LogLog.warn("The \""+CONFIG_DEBUG_ATTR+"\" attribute is deprecated."); LogLog.warn("Use the \""+INTERNAL_DEBUG_ATTR+"\" attribute instead."); LogLog.setInternalDebugging(OptionConverter.toBoolean(confDebug, true)); } String thresholdStr = subst(element.getAttribute(THRESHOLD_ATTR)); LogLog.debug("Threshold =\"" + thresholdStr +"\"."); if(!"".equals(thresholdStr) && !"null".equals(thresholdStr)) { repository.setThreshold(thresholdStr); } //Hashtable appenderBag = new Hashtable(11); /* Building Appender objects, placing them in a local namespace for future reference */ // First configure each category factory under the root element. // Category factories need to be configured before any of // categories they support. String tagName = null; Element currentElement = null; Node currentNode = null; NodeList children = element.getChildNodes(); final int length = children.getLength(); for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY_FACTORY_TAG)) { parseCategoryFactory(currentElement); } } } for (int loop = 0; loop < length; loop++) { currentNode = children.item(loop); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { currentElement = (Element) currentNode; tagName = currentElement.getTagName(); if (tagName.equals(CATEGORY) || tagName.equals(LOGGER)) { parseCategory(currentElement); } else if (tagName.equals(ROOT_TAG)) { parseRoot(currentElement); } else if(tagName.equals(RENDERER_TAG)) { parseRenderer(currentElement); } } } } protected String subst(String value) { try { return OptionConverter.substVars(value, props); } catch(IllegalArgumentException e) { LogLog.warn("Could not perform variable substitution.", e); return value; } } } class XMLWatchdog extends FileWatchdog { XMLWatchdog(String filename) { super(filename); } /** Call {@link PropertyConfigurator#configure(String)} with the <code>filename</code> to reconfigure log4j. */ public void doOnChange() { new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository()); } }
package advanced.combinatorial.permutation.lc046_permutations; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; /** * Given a collection of distinct numbers, return all possible permutations. * For example, [1,2,3] have the following permutations: * [ * [1,2,3], * [1,3,2], * [2,1,3], * [2,3,1], * [3,1,2], * [3,2,1] * ] */ public class Solution { // Don't use iterator, which can avoid exception and tmp list // O(N!) Beat 24% public List<List<Integer>> permute(int[] nums) { Queue<List<Integer>> result = new LinkedList<>(); result.add(new ArrayList<>()); for (int num : nums) { int size = result.size(); while (size List<Integer> per = result.poll(); for (int k = 0; k <= per.size(); k++) { List<Integer> newPer = new ArrayList<>(per); newPer.add(k, num); result.add(newPer); } } } return (List<List<Integer>>) result; } // My 1st: use Set to exclude picked candidates public List<List<Integer>> permute1(int[] nums) { List<List<Integer>> result = new ArrayList<>(); Set<Integer> path = new LinkedHashSet<>(); // TreeSet is sorted by element order; LinkedHashSet retains insertion order. permute(result, path, nums, 0); return result; } private void permute(List<List<Integer>> result, Set<Integer> path, int[] nums, int k) { if (k == nums.length) { result.add(new ArrayList<>(path)); return; } for (int i = 0; i < nums.length; i++) { if (path.contains(nums[i])) { continue; } path.add(nums[i]); permute(result, path, nums, k+1); path.remove(nums[i]); // take care of this since we're using Set not array } } }
import java.util.Arrays; import java.lang.Math; import java.util.*; import java.util.stream.*; import org.apache.commons.lang3.ArrayUtils; public class GaussianNaiveBayesClassifier { private boolean fitted; private int[] classes; private int nbClasses; private int nbFeats; private int[] classCounts; private double[][] sum; private double[][] sumSquares; private double[][] theta; private double[][] sigma; private double[] classPriors; public GaussianNaiveBayesClassifier() { // Gaussian Naive Bayes classifier. // A Gaussian Naive Bayes classifier that can be trained offline or // online, and then used for prediction. It accepts any number of // classes and features. // The API was inspired by sklearn's: // http://scikit-learn.org/stabl/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB // Attributes: // fitted: True if the model has been fitted // classes: list of the integer identifier of each class for which the // model has been trained // nbClasses: number of classes for which the model has been trained // nbFeats: number of features // classCounts: number of examples seen by class // sum: used internally to update the Gaussian models (sum of all seen // examples) // sumSquares: used internally to update the Gaussian models (sum of // squares of all seen examples) // theta: means of the Gaussian models [nbClasses x nbFeats] // sigma: variances of the Gaussian models [nbClasses x nbFeats] // classPriors: prior probability of each class, computed using the // number of examples seen for each class during training // TODO: // Implement decision boundary method? fitted = false; } public void fit(double[][] X, int[] y) { // Fit the model. // Args: // X: training data, [nbExamples, nbFeatures] // y: labels [nbExamples] // Note: Calling `fit()` overwrites previous information. Use // `partial_fit()` to update the model with new training data. // If model has already been trained, re-initialize parameters this.fitted = false; partialFit(X,y); } public void partialFit(double[][] X, int[] y) { // Fit or update the model. // Fit or update the model. If the model has already been trained, this // will update the parameters instead of computing them from scratch. // Args: // X: training data, [nbExamples, nbFeatures] // y: labels [nbExamples] // Using `partialFit()` allows to update the model given new data. assert (X.length == y.length) : "X and y must contain the same number of examples."; // If model has not been trained yet, initialize parameters if (!this.fitted) { this.classes = unique(y); this.nbClasses = this.classes.length; this.nbFeats = X[0].length; this.classCounts = new int[this.nbClasses]; this.classPriors = new double[this.nbClasses]; this.sum = new double[this.nbClasses][this.nbFeats]; this.sumSquares = new double[this.nbClasses][this.nbFeats]; this.theta = new double[this.nbClasses][this.nbFeats]; this.sigma = new double[this.nbClasses][this.nbFeats]; } int[] newClassCounts = count(y,this.classes); // Compute internal variable and model parameters for each class for (int i = 0; i < this.nbClasses; i++) { classCounts[i] += newClassCounts[i]; for (int k = 0; k < this.nbFeats; k++) { // Update sum and sum of squares for (int j = 0; j < X.length; j++) { if (y[j] == this.classes[i]) { this.sum[i][k] += X[j][k]; this.sumSquares[i][k] += X[j][k] * X[j][k]; } } // Update theta and sigma this.theta[i][k] = this.sum[i][k] / this.classCounts[i]; this.sigma[i][k] = this.sumSquares[i][k] / this.classCounts[i] - this.theta[i][k] * theta[i][k]; } } // Update class priors int nbExamplesSeen = 0; for (int i = 0; i < this.nbClasses; i++) { nbExamplesSeen += classCounts[i]; } for (int i = 0; i < this.nbClasses; i++) { this.classPriors[i] = (double) classCounts[i]/nbExamplesSeen; } this.fitted = true; } public double[][] predictProba(double[][] X) { // Compute the posterior probability. // Compute the posterior probability of data X given the learned model // parameters. // Args: // X: data for which to compute the posterior probability, // [nbExamples, nbFeatures] // Returns: // posterior probability of each class for each example in X, // [nbExamples, nbClasses] // TODO: // - Add option to use classPriors double[][] prob = new double[X.length][this.nbClasses]; double partition = 0; for (int i = 0; i < X.length; i++) { partition = 0; for (int j = 0; j < this.nbClasses; j++) { prob[i][j] = 1; // Compute joint pdf of example i for (int k = 0; k < X[i].length; k++) { prob[i][j] *= gaussian(X[i][k], this.theta[j][k], this.sigma[j][k]); } partition += prob[i][j]; // Compute the partition function } // Normalize the pdfs so prob sums to 1 for each example for (int j = 0; j < this.nbClasses; j++) { prob[i][j] /= partition; } } return prob; } public int[] predict(double[][] X) { // Classify examples. // Classify examples X given the learned model parameters. // Args: // X: data to classify, [nbExamples, nbFeatures] // Returns: // predicted labels, [nbExamples] double[][] prob = predictProba(X); int[] yHat = new int[X.length]; for (int i = 0; i < X.length; i++) { yHat[i] = this.classes[argmax(prob[i])]; } return yHat; } public double score(double[][] X, int[] y) { // Estimate the accuracy of the current model. // Estimate the accuracy of the current model on data X, y. // Args: // X: data to test on, [nbExamples, nbFeatures] // y: labels for X [nbExamples] // Returns: // accuracy assert (X.length == y.length) : "X and y must contain the same number of examples."; int[] yHat = predict(X); int nbGoodDecisions = 0; for (int i = 0; i < y.length; i++) { if (yHat[i] == y[i]) { nbGoodDecisions += 1; } } return (double) nbGoodDecisions/y.length; } public double[][] getMeans() { return this.theta; } public double[][] getVariances() { return this.sigma; } public double[] getClassPriors() { return this.classPriors; } public int[] getClassCounts() { return this.classCounts; } public void setMeans(double[][] means) { // Set the means of the model. // Set the means of the model. This makes it possible to load the // parameters of a model that was trained previously. However, since the // internal state is unknown (sum, sumSquares, classCounts), we can't // allow partial training. this.theta = means; this.fitted = false; } public void setVariances(double[][] vars) { // Set the variances of the model. // Set the variances of the model. This makes it possible to load the // parameters of a model that was trained previously. However, since the // internal state is unknown (sum, sumSquares, classCounts), we can't // allow partial training. this.sigma = vars; this.fitted = false; } public void setClassPriors(double[] classPriors) { // Set the class priors of the model. // Set the class priors of the model. This makes it possible to // load the parameters of a model that was trained previously. However, // since the internal state is unknown (sum, sumSquares, classCounts), // we can't allow partial training. this.classPriors = classPriors; this.fitted = false; } // public double[][] decisionBoundary() { private double gaussian(double x, double mu, double var) { // Compute the Gaussian pdf. // Compute the univariate Gaussian pdf of mean `mu` and variance `var` // for point `x`. // Args: // x: point for which to evaluate the pdf // mu: mean of the univariate Gaussian // var: variance of the univariate Gaussian // Returns: // pdf of point `x` x -= mu; return Math.exp(-x*x / (2*var)) / (Math.sqrt(2 * Math.PI * var)); } private double[][] gaussian(double[][] X, double[] mu, double[] var) { // Compute the Gaussian pdf. // Compute the Gaussian pdfs for multiple points and features at once. // This is a helper function to simplify the use of gaussian() above // on multiple points and features at once. // Args: // X: matrix of shape [nbExamples, nbFeatures] // mu: means of the univariate Gaussians, [nbFeatures] // var: variances of the univariate Gaussians, [nbFeatures] // Returns: // pdfs of X, [nbExamples, nbFeatures] double[][] g = new double[X.length][mu.length]; for (int j = 0; j < mu.length; j++){ for (int i = 0; i < X.length; i++){ g[i][j] = gaussian(X[i][j], mu[j], var[j]); } } return g; } private int[] unique(int[] numbers) { // Find unique elements in array. // Args: // numbers: array for which to find unique values // Returns: // array containing unique values Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>(); for(int x : numbers) { setUniqueNumbers.add(x); } int[] uniqueNumbers = new int[setUniqueNumbers.size()]; Iterator<Integer> itr = setUniqueNumbers.iterator(); int i = 0; while(itr.hasNext()){ uniqueNumbers[i] = itr.next(); i++; } return uniqueNumbers; } private int[] count(int[] numbers, int[] like) { // Count the number of occurences of a specific value in an array. // Args: // numbers: list of integers in which to look for // like: integers to look for // Returns: // number of occurences for each desired element // TODO: Make a more efficient version? int[] counts = new int[like.length]; for (int i : like){ for (int j : numbers) { if (i == j){ counts[i]++; } } } return counts; } private int argmax(double[] x) { // Return the index of the element with the highest value in x. // Args: // x: array // Returns: // index of the element with the highest value in x double max = x[0]; int maxInd = 0; for (int i = 1; i < x.length; i++) { if (x[i] > max) { max = x[i]; maxInd = i; } } return maxInd; } public void print() { // Print the current state of the model. System.out.println(" "); System.out.println("Summary of GaussianNaiveBayesClassifier"); System.out.println("======================================="); System.out.println(" "); System.out.println("Classes: "+Arrays.toString(this.classes)); System.out.println("Number of classes: "+this.nbClasses); System.out.println("Number of features: "+this.nbFeats); System.out.println("Class counts: "+Arrays.toString(getClassCounts())); System.out.println("Class priors: "+Arrays.toString(getClassPriors())); System.out.println("Sums: "+Arrays.deepToString(this.sum)); System.out.println("Sums of squares: "+Arrays.deepToString(this.sumSquares)); System.out.println("Means: "+Arrays.deepToString(getMeans())); System.out.println("Variances: "+Arrays.deepToString(getVariances())); System.out.println(" "); } public static void main(String[] args) { GaussianNaiveBayesClassifier clf = new GaussianNaiveBayesClassifier(); // Make initial training set double[][] X_train = new double[][]{{1, 2}, {4, 4}, {4, 6}, {7, 8}, {10, 10}, {30, 30}}; int[] y_train = {0, 0, 0, 0, 1, 1}; // Make second training set for update double[][] X_train2 = new double[][]{{2, 3}, {5, 5}, {5, 7}, {8, 9}, {11, 11}, {31, 31}}; int[] y_train2 = {0, 0, 0, 0, 1, 1}; // Make test set double[][] X_test = new double[][]{{0, 0}, {4, 5}, {20, 20}, {100, 115}}; int[] y_test = {0, 0, 1, 1}; // Fit initial model clf.fit(X_train, y_train); clf.print(); // Update model clf.partialFit(X_train2, y_train2); clf.print(); // Train model from scratch with new data instead clf.fit(X_train2, y_train2); clf.print(); // Predict probability double[][] proba = clf.predictProba(X_test); System.out.println("Probability: "+Arrays.deepToString(proba)); // Predict int[] yHat = clf.predict(X_test); System.out.println("Prediction: "+Arrays.toString(yHat)); // Score double acc = clf.score(X_test, y_test); System.out.println("Accuracy: "+acc); } }
package org.apache.velocity.anakia; // Velocity Stuff import org.apache.velocity.runtime.Runtime; // XPath Stuff import com.werken.xpath.XPath; // JDK Stuff import java.util.List; // JDOM Stuff import org.jdom.Document; import org.jdom.Element; public class XPathTool { /** Constructor does nothing, as this is mostly just objectified static methods */ public XPathTool() { Runtime.info("XPathTool::XPathTool()"); // intentionally left blank } /** Apply an XPath to a JDOM Document @param xpathSpec The XPath to apply @param doc The Document context @return A list of selected nodes */ public List applyTo(String xpathSpec, Document doc) { Runtime.info("XPathTool::applyTo(String, Document)"); XPath xpath = new XPath( xpathSpec ); return xpath.applyTo( doc ); } /** Apply an XPath to a JDOM Element @param xpathSpec The XPath to apply @param doc The Element context @return A list of selected nodes */ public List applyTo(String xpathSpec, Element elem) { Runtime.info("XPathTool::applyTo(String, Element)"); XPath xpath = new XPath(xpathSpec); return xpath.applyTo( elem ); } /** Apply an XPath to a nodeset @param xpathSpec The XPath to apply @param doc The nodeset context @return A list of selected nodes */ public List applyTo(String xpathSpec, List nodeSet) { Runtime.info("XPathTool::applyTo(String, List)"); XPath xpath = new XPath(xpathSpec); return xpath.applyTo( nodeSet ); } }
package org.apache.velocity.convert; import java.io.File; import java.io.FileWriter; import org.apache.oro.text.perl.Perl5Util; import org.apache.velocity.util.StringUtils; import org.apache.tools.ant.DirectoryScanner; /** * This class will convert a WebMacro template to * a Velocity template. Uses the ORO Regexp package to do the * rewrites. Note, it isn't 100% perfect, but will definitely get * you about 99.99% of the way to a converted system. Please * see the website documentation for more information on how to use * this class. * * @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a> * @version $Id: WebMacro.java,v 1.10 2001/05/08 01:27:21 dlr Exp $ */ public class WebMacro { /** Name of the original webmacro template */ protected String orignalTemplate; /** Regular expression tool */ protected Perl5Util perl; /** Path separator property */ protected String pathSeparator = File.separator; protected final static String VM_EXT = ".vm"; protected final static String WM_EXT = ".wm"; /* * The regexes to use for substition. The regexes come * in pairs. The first is the string to match, the * second is the substitution to make. */ protected String[] res = { // Make #if directive match the Velocity directive style. "#if\\s*[(]\\s*(.*\\S)\\s*[)]\\s*(#begin|{)[ \\t]?", "#if( $1 )", // Remove the WM #end #else #begin usage. "[ \\t]?(#end|})\\s*#else\\s*(#begin|{)[ \\t]?(\\w)", "#else#**#$3", // avoid touching a followup word with embedded comment "[ \\t]?(#end|})\\s*#else\\s*(#begin|{)[ \\t]?", "#else", // Convert WM style #foreach to Velocity directive style. "#foreach\\s+(\\$\\w+)\\s+in\\s+(\\$[^\\s#]+)\\s*(#begin|{)[ \\t]?", "#foreach( $1 in $2 )", // Change the "}" to #end. Have to get more // sophisticated here. Will assume either {} // and no javascript, or #begin/#end with the // possibility of javascript. "\n}", // assumes that javascript is indented, WMs not!!! "\n#end", // Convert WM style #set to Velocity directive style. "#set\\s+(\\$[^\\s=]+)\\s*=\\s*(.*\\S)[ \\t]*", "#set( $1 = $2 )", "(##[# \\t\\w]*)\\)", // fix comments included at end of line ")$1", // Convert WM style #parse to Velocity directive style. "#parse\\s+([^\\s#]+)[ \\t]?", "#parse( $1 )", // Convert WM style #include to Velocity directive style. "#include\\s+([^\\s "#include( $1 )", // Convert WM formal reference to VL syntax. "\\$\\(([^\\)]+)\\)", "${$1}", "\\${([^}\\(]+)\\(([^}]+)}\\)", // fix encapsulated brakets: {(}) "${$1($2)}", // Velocity currently does not permit leading underscore. "\\$_", "$l_", "\\${(_[^}]+)}", // within a formal reference "${l$1}", // Change extensions when seen. "\\.wm", ".vm" }; /** * Iterate through the set of find/replace regexes * that will convert a given WM template to a VM template */ public void convert(String args[]) { if (args.length < 1) usage(); File file = new File(args[0]); if (!file.exists()) { System.err.println ("The specified template or directory does not exist"); System.exit(1); } if (file.isDirectory()) { String basedir = file.getAbsolutePath(); String newBasedir = basedir + VM_EXT; DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(basedir); ds.addDefaultExcludes(); ds.scan(); String[] files = ds.getIncludedFiles(); for (int i = 0; i < files.length; i++) writeTemplate(files[i], basedir, newBasedir); } else { writeTemplate(args[0], "", ""); } } /** * Write out the converted template to the given named file * and base directory. */ private boolean writeTemplate(String file, String basedir, String newBasedir) { if (file.indexOf(WM_EXT) < 0) return false; System.out.println("Converting " + file + "..."); String template; String templateDir; String newTemplate; File outputDirectory; if (basedir.length() == 0) { template = file; templateDir = ""; newTemplate = convertName(file); } else { template = basedir + pathSeparator + file; templateDir = newBasedir + extractPath(file); outputDirectory = new File(templateDir); if (! outputDirectory.exists()) outputDirectory.mkdirs(); newTemplate = newBasedir + pathSeparator + convertName(file); } String convertedTemplate = convertTemplate(template); try { FileWriter fw = new FileWriter(newTemplate); fw.write(convertedTemplate); fw.close(); } catch (Exception e) { e.printStackTrace(); } return true; } /** * Gets the path segment of the full path to a file (i.e. one * which originally included the file name). */ private final String extractPath(String file) { int lastSepPos = file.lastIndexOf(pathSeparator); return (lastSepPos == -1 ? "" : pathSeparator + file.substring(0, lastSepPos)); } /** * Simple extension conversion of .wm to .vm */ private String convertName(String name) { if (name.indexOf(WM_EXT) > 0) return name.substring(0, name.indexOf(WM_EXT)) + VM_EXT; else return name; } /** * How to use this little puppy :-) */ public void usage() { System.err.println("Usage: convert-wm <template.wm | directory>"); System.exit(1); } /** * Apply find/replace regexes to our WM template */ public String convertTemplate(String template) { orignalTemplate = StringUtils.fileContentsToString(template); // overcome current velocity 0.71 limitation if ( !orignalTemplate.endsWith("\n") ) orignalTemplate += "\n"; perl = new Perl5Util(); for (int i = 0; i < res.length; i += 2) { while (perl.match("/" + res[i] + "/", orignalTemplate)) { orignalTemplate = perl.substitute( "s/" + res[i] + "/" + res[i+1] + "/", orignalTemplate); } } return orignalTemplate; } /** * Main hook for the conversion process. */ public static void main(String[] args) { WebMacro converter = new WebMacro(); converter.convert(args); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smackx.packet.Time; import org.jivesoftware.smackx.packet.VCard; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.UserManager; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.log.Log; import java.awt.Color; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; /** * UI to display VCard Information in Wizards, Dialogs, Chat Rooms and any other container. * * @author Derek DeMoro */ public class VCardPanel extends JPanel { private final String jid; private final JLabel avatarImage; private static SimpleDateFormat utcFormat = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss"); /** * Generate a VCard Panel using the specified jid. * * @param jid the jid to use when retrieving the vcard information. */ public VCardPanel(final String jid) { setLayout(new GridBagLayout()); setOpaque(false); this.jid = jid; avatarImage = new JLabel(); SwingWorker worker = new SwingWorker() { VCard vcard = null; public Object construct() { vcard = SparkManager.getVCardManager().getVCard(jid); return vcard; } public void finished() { if (vcard == null) { // Do nothing. return; } byte[] bytes = vcard.getAvatar(); if (bytes != null) { try { ImageIcon icon = new ImageIcon(bytes); Image aImage = icon.getImage(); if (icon.getIconHeight() > 32 || icon.getIconWidth() > 32) { aImage = aImage.getScaledInstance(-1, 32, Image.SCALE_SMOOTH); } icon = new ImageIcon(aImage); if (icon.getIconWidth() > 0) { avatarImage.setIcon(icon); avatarImage.setBorder(BorderFactory.createBevelBorder(0, Color.white, Color.lightGray)); } } catch (Exception e) { Log.error(e); } } vcard.setJabberId(jid); buildUI(vcard); } }; worker.start(); } private void buildUI(final VCard vcard) { add(avatarImage, new GridBagConstraints(0, 0, 1, 4, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0)); avatarImage.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent mouseEvent) { if (mouseEvent.getClickCount() == 2) { SparkManager.getVCardManager().viewProfile(vcard.getJabberId(), avatarImage); } } }); String city = vcard.getField("CITY"); String state = vcard.getField("STATE"); String country = vcard.getField("COUNTRY"); String firstName = vcard.getFirstName(); if (firstName == null) { firstName = ""; } String lastName = vcard.getLastName(); if (lastName == null) { lastName = ""; } String title = vcard.getField("TITLE"); final JLabel usernameLabel = new JLabel(); usernameLabel.setHorizontalTextPosition(JLabel.LEFT); usernameLabel.setFont(new Font("Dialog", Font.BOLD, 11)); usernameLabel.setForeground(Color.DARK_GRAY); if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) { usernameLabel.setText(firstName + " " + lastName); } else { String nickname = SparkManager.getUserManager().getUserNicknameFromJID(jid); usernameLabel.setText(UserManager.unescapeJID(nickname)); } Roster roster = SparkManager.getConnection().getRoster(); Presence p = roster.getPresence(vcard.getJabberId()); Icon icon = SparkManager.getChatManager().getPresenceIconForContactHandler(p); if (icon != null) { usernameLabel.setIcon(icon); } add(usernameLabel, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 2, 5), 0, 0)); /* final JLabel locationLabel = new JLabel(); if (ModelUtil.hasLength(city) && ModelUtil.hasLength(state) && ModelUtil.hasLength(country)) { locationLabel.setText(" - " + city + ", " + state + " " + country); } add(locationLabel, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); */ final JLabel titleLabel = new JLabel(title); if (ModelUtil.hasLength(title)) { add(titleLabel, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0)); } /* String phone = vcard.getPhoneWork("VOICE"); if (ModelUtil.hasLength(phone)) { final JLabel phoneNumber = new JLabel("Work: " + phone); add(phoneNumber, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 5, 2, 5), 0, 0)); } */ final JLabel localTime = new JLabel(); add(localTime, new GridBagConstraints(1, 3, 2, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 5, 0, 5), 0, 0)); final Time time = new Time(); time.setType(IQ.Type.GET); String fullJID = SparkManager.getUserManager().getFullJID(jid); if (fullJID == null) { return; } time.setTo(fullJID); SwingWorker timeThread = new SwingWorker() { IQ timeResult; public Object construct() { SparkManager.getConnection().sendPacket(time); final PacketCollector packetCollector = SparkManager.getConnection().createPacketCollector(new PacketIDFilter(time.getPacketID())); timeResult = (IQ)packetCollector.nextResult(); return timeResult; } public void finished() { // Wait up to 5 seconds for a result. if (timeResult != null && timeResult.getType() == IQ.Type.RESULT) { try { Time t = (Time)timeResult; Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone(t.getTz())); // Convert the UTC time to local time. cal.setTime(new Date(utcFormat.parse(t.getUtc()).getTime() + cal.getTimeZone().getOffset(cal.getTimeInMillis()))); Date date = cal.getTime(); final SimpleDateFormat formatter = new SimpleDateFormat("h:mm a"); localTime.setText(Res.getString("label.time", formatter.format(date))); } catch (ParseException e) { Log.error(e); } } } }; timeThread.start(); localTime.setText("Retrieving time"); localTime.setText(""); } }
package org.ngsutils.mvpipe.parser; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Tokenizer { public static List<String> tokenize(String str) { List<String> tokens = extractQuotedStrings(str); tokens = correctNegNumbers(tokens); // tokens = mergeOps(tokens); // tokens = correctDollarExp(tokens); tokens = removeComments(tokens); return tokens; } private static List<String> removeComments(List<String> in) { List<String> out = new ArrayList<String>(); for (String s: in) { if (s.startsWith(" return out; } else { out.add(s); } } return out; } private static List<String> correctNegNumbers(List<String> in) { if (in.size() == 0) { return in; } List<String> out = new ArrayList<String>(); // starts with a neg, so this must be a number... if (in.get(0).equals("-")) { in.remove(0); in.set(0, "-" + in.get(0)); } // If the prior token is one of these, and we have a '-' token, the next value should be a negative number Set<String> valid = new HashSet<String>(); valid.add("+"); valid.add("-"); valid.add("*"); valid.add("/"); valid.add("%"); valid.add("**"); valid.add("("); String last = null; boolean appendNeg = false; for (String s: in) { if (last == null) { out.add(s); last = s; continue; } if (appendNeg) { out.add("-" + s); appendNeg = false; continue; } if (s.equals("-")) { if (valid.contains(last)) { appendNeg = true; continue; } } out.add(s); last = s; } return out; } // private static List<String> mergeOps(List<String> in) { // List<String> out = new ArrayList<String>(); // String last = null; // String[] validOps = new String[] { // for (String s: in) { // if (last == null) { // last = s; // continue; // String pair = last + s; // for (String op: validOps) { // if (op.equals(pair)) { // out.add(op); // last = null; // break; // if (last != null) { // out.add(last); // last = s; // if (last != null) { // out.add(last); // return out; // private static List<String> correctDollarExp(List<String> in) { // List<String> out = new ArrayList<String>(); // String buf = null; // for (String s: in) { // if (buf != null) { // buf += s; // if (s.endsWith("}")) { // out.add(buf); // buf = null; // } else if (s.startsWith("${") && !s.endsWith("}")) { // buf = s; // } else { // out.add(s); // return out; // private static List<String> correctOps(List<String> in) { // List<String> out = new ArrayList<String>(); // String buf = null; // for (String s: in) { // if (buf != null) { // buf += s; // if (s.endsWith("}")) { // out.add(buf); // buf = null; // } else if (s.startsWith("${") && !s.endsWith("}")) { // buf = s; // } else { // out.add(s); // return out; private static List<String> extractQuotedStrings(String str) { List<String> tokens = new ArrayList<String>(); String buf=""; boolean inquote = false; int i=0; while (i < str.length()) { if (inquote) { if (str.charAt(i) == '"') { if (buf.endsWith("\\")) { buf = buf.substring(0, buf.length()-1) + "\""; } else { buf += "\""; tokens.add(buf); buf = ""; inquote = false; } } else { buf += str.charAt(i); } i++; continue; } if (str.charAt(i) == '"') { buf += "\""; inquote = true; i++; continue; } boolean found = false; for (String op: Eval.opsParseOrder) { if (i+op.length() <= str.length() && str.substring(i, i+op.length()).equals(op)) { if (!buf.equals("")) { tokens.add(buf); } tokens.add(op); buf = ""; i += op.length(); found = true; break; } } if (found) { continue; } // split on parens if (str.charAt(i) == '(' || str.charAt(i) == ')') { if (!buf.equals("")) { tokens.add(buf); buf = ""; } tokens.add(""+str.charAt(i)); i++; continue; } // split on whitespace if (str.charAt(i) == ' ' || str.charAt(i) == '\t') { if (!buf.equals("")) { tokens.add(buf); buf = ""; } i++; continue; } // // remove all comments // if (str.charAt(i) == ' // if (!buf.equals("")) { // tokens.add(buf); // buf = ""; // i = str.length(); // continue; buf += str.charAt(i); i++; } if (!buf.equals("")) { tokens.add(buf); } return tokens; // for (int i=0; i<str.length(); i++) { //// String delim = "" + str.charAt(i); // switch(str.charAt(i)) { // case '"': // if (!inquote) { // // we aren't in a quoted block, so start one (naked \" isn't allowed) // buf += "\""; // inquote = true; // } else { // if (buf.endsWith("\\")){ // // we are in a quoted block, but the preceding char was '\', so just ignore the quote // buf += "\""; // } else { // // we are in a quoted block, so close it // buf += "\""; // tokens.add(buf); // buf = ""; // inquote = false; // break; // // operators // case '+': // case '-': // case '*': // case '/': // case '%': // case '?': // case '!': // case '=': // case '|': // case ':': // case '&': // case '(': // case ')': // case ' ': // case '.': // case ' // if (!inquote) { // if (buf.length()>0) { // tokens.add(buf); // buf = ""; // if (str.charAt(i) != ' ') { // tokens.add(delim); // break; // default: // buf += str.charAt(i); // break; // if (buf.length() > 0) { // tokens.add(buf); // return tokens; } }
package net.runelite.client.plugins.cannon; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.Getter; import net.runelite.api.coords.WorldPoint; public enum CannonSpots { BLOODVELDS(new WorldPoint(2439, 9821, 0), new WorldPoint(2448, 9821, 0), new WorldPoint(2472, 9833, 0), new WorldPoint(2453, 9817, 0)), FIRE_GIANTS(new WorldPoint(2393, 9782, 0), new WorldPoint(2412, 9776, 0), new WorldPoint(2401, 9780, 0)), ABBERANT_SPECTRES(new WorldPoint(2456, 9791, 0)), HELLHOUNDS(new WorldPoint(2431, 9776, 0), new WorldPoint(2413, 9786, 0), new WorldPoint(2783, 9686, 0)), BLACK_DEMONS(new WorldPoint(2859, 9778, 0), new WorldPoint(2841, 9791, 0)), ELVES(new WorldPoint(2044, 4635, 0)), SUQAHS(new WorldPoint(2114, 3943, 0)), TROLLS(new WorldPoint(2401, 3856, 0)), GREATER_DEMONS(new WorldPoint(1435, 10086, 2)), BRINE_RAT(new WorldPoint(2707, 10132, 0)), DAGGANOTH(new WorldPoint(2524, 10020, 0)), DARK_BEAST(new WorldPoint(1992, 4655, 0)), DUST_DEVIL(new WorldPoint(3218, 9366, 0)), KALPHITE(new WorldPoint(3307, 9528, 0)), LESSER_DEMON(new WorldPoint(2838, 9559, 0)), LIZARDMEN(new WorldPoint(1500, 3703, 0)), MINIONS_OF_SCARABAS(new WorldPoint(3297, 9252, 0)), SMOKE_DEVIL(new WorldPoint(2398, 9444, 0)), CAVE_HORROR(new WorldPoint(3785, 9460, 0)), BLUE_DRAGON(new WorldPoint(1933, 8973, 1)); @Getter private static final List<WorldPoint> cannonSpots = new ArrayList<>(); static { for (CannonSpots cannonSpot : values()) { cannonSpots.addAll(Arrays.asList(cannonSpot.spots)); } } private final WorldPoint[] spots; CannonSpots(WorldPoint... spots) { this.spots = spots; } }
package org.hoteia.qalingo.core.solr.service; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrRequest; import org.apache.solr.client.solrj.SolrRequest.METHOD; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.request.QueryRequest; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.QueryResponse; import org.hibernate.Hibernate; import org.hoteia.qalingo.core.domain.ProductBrand; import org.hoteia.qalingo.core.domain.Store; import org.hoteia.qalingo.core.domain.Tag; import org.hoteia.qalingo.core.service.GeolocService; import org.hoteia.qalingo.core.solr.bean.SortField; import org.hoteia.qalingo.core.solr.bean.SolrParam; import org.hoteia.qalingo.core.solr.bean.StoreSolr; import org.hoteia.qalingo.core.solr.response.StoreResponseBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("storeSolrService") @Transactional public class StoreSolrService extends AbstractSolrService { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired protected SolrServer storeSolrServer; @Autowired protected GeolocService geolocService; public void addOrUpdateStore(final Store store, final List<ProductBrand> productBrands) throws SolrServerException, IOException { StoreSolr storeSolr = populateStoreSolr(store); for (ProductBrand productBrand : productBrands) { storeSolr.addProductBrandCodes(productBrand.getCode()); } storeSolrServer.addBean(storeSolr); storeSolrServer.commit(); } public void addOrUpdateStore(final Store store) throws SolrServerException, IOException { StoreSolr storeSolr = populateStoreSolr(store); storeSolrServer.addBean(storeSolr); storeSolrServer.commit(); } protected StoreSolr populateStoreSolr(Store store){ if (store.getId() == null) { throw new IllegalArgumentException("Id cannot be blank or null."); } if (logger.isDebugEnabled()) { logger.debug("Indexing store " + store.getId() + " : " + store.getName() + " : " + store.getCity()); } StoreSolr storeSolr = new StoreSolr(); storeSolr.setId(store.getId()); storeSolr.setCode(store.getCode()); storeSolr.setName(store.getName()); if(Hibernate.isInitialized(store.getRetailer()) && store.getRetailer() != null && Hibernate.isInitialized(store.getRetailer().getCompany()) && store.getRetailer().getCompany() != null){ storeSolr.setCompanyName(store.getRetailer().getCompany().getName()); } if(store.getTags() != null){ for (Tag tag : store.getTags()) { storeSolr.addTagCodes(tag.getCode()); } } storeSolr.setActive(store.isActive()); storeSolr.setB2b(store.isB2b()); storeSolr.setB2c(store.isB2c()); storeSolr.setActive(store.isActive()); storeSolr.setAddress(store.getAddress1()); storeSolr.setPostalCode(store.getPostalCode()); storeSolr.setCity(store.getCity()); storeSolr.setCountryCode(store.getCountryCode()); storeSolr.setAddressUniqueKey(geolocService.encodeAddressWithPhoneAsUniqueKey(store.getAddress1(), store.getPostalCode(), store.getCity(), store.getCountryCode(), store.getPhone())); storeSolr.setType(store.getType()); return storeSolr; } public void removeStore(final StoreSolr storeSolr) throws SolrServerException, IOException { if (storeSolr.getId() == null) { throw new IllegalArgumentException("Id cannot be blank or null."); } if (logger.isDebugEnabled()) { logger.debug("Remove Index Store " + storeSolr.getId() + " : " + storeSolr.getName() + " : " + storeSolr.getCity()); } storeSolrServer.deleteById(storeSolr.getId().toString()); storeSolrServer.commit(); } public StoreResponseBean searchStore(final String searchQuery, final List<String> facetFields, final List<String> cities, final List<String> countries, final SolrParam solrParam) throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); if(solrParam != null){ if(solrParam.get("rows") != null){ solrQuery.setParam("rows", (String)solrParam.get("rows")); } else { solrQuery.setParam("rows", getMaxResult()); } if(solrParam.get("sortField") != null){ SortField sortField = (SortField) solrParam.get("sortField"); for (Iterator<String> iterator = sortField.keySet().iterator(); iterator.hasNext();) { String field = (String) iterator.next(); solrQuery.addSortField(field, sortField.get(field)); } } } if (StringUtils.isEmpty(searchQuery)) { throw new IllegalArgumentException("SearchQuery field can not be Empty or Blank!"); } solrQuery.setQuery(searchQuery); if (facetFields != null && facetFields.size() > 0) { solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); for (String facetField : facetFields) { solrQuery.addFacetField(facetField); } } if (cities != null && cities.size() > 0) { StringBuilder fq = new StringBuilder("city:("); for (int i = 0; i < cities.size(); i++) { String city = cities.get(i); fq.append('"' + city + '"'); if (i < cities.size() - 1) { fq.append(" OR "); } } fq.append(")"); solrQuery.addFilterQuery(fq.toString()); } if (countries != null && countries.size() > 0) { StringBuilder fq = new StringBuilder("countryCode:("); for (int i = 0; i < countries.size(); i++) { String country = countries.get(i); fq.append('"' + country + '"'); if (i < countries.size() - 1) { fq.append(" OR "); } } fq.append(")"); solrQuery.addFilterQuery(fq.toString()); } logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(storeSolrServer.request(request), storeSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<StoreSolr> solrList = response.getBeans(StoreSolr.class); StoreResponseBean storeResponseBean = new StoreResponseBean(); storeResponseBean.setStoreSolrList(solrList); if (facetFields != null && facetFields.size() > 0) { List<FacetField> solrFacetFieldList = response.getFacetFields(); storeResponseBean.setStoreSolrFacetFieldList(solrFacetFieldList); } return storeResponseBean; } @Deprecated public StoreResponseBean searchStore(String searchBy, String searchText, List<String> facetFields) throws SolrServerException, IOException { return searchStore(searchBy, searchText, facetFields, null, null); } @Deprecated public StoreResponseBean searchStore(String searchBy, String searchText, List<String> facetFields, List<String> cities, List<String> countries) throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam("rows", getMaxResult()); if (StringUtils.isEmpty(searchBy)) { throw new IllegalArgumentException("SearchBy field can not be Empty or Blank!"); } if (StringUtils.isEmpty(searchText)) { solrQuery.setQuery(searchBy + ":*"); } else { solrQuery.setQuery(searchBy + ":" + searchText + "*"); } if (facetFields != null && facetFields.size() > 0) { solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); for( String facetField : facetFields){ solrQuery.addFacetField(facetField); } } if(cities != null && cities.size() > 0){ StringBuilder fq = new StringBuilder("city:("); for (int i = 0; i < cities.size(); i++) { String city = cities.get(i); fq.append('"'+city+'"'); if(i < cities.size() - 1){ fq.append(" OR "); } } fq.append(")"); solrQuery.addFilterQuery(fq.toString()); } if(countries != null && countries.size() > 0){ StringBuilder fq = new StringBuilder("countryCode:("); for (int i = 0; i < countries.size(); i++) { String country = countries.get(i); fq.append('"'+country+'"'); if(i < countries.size() - 1){ fq.append(" OR "); } } fq.append(")"); solrQuery.addFilterQuery(fq.toString()); } logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(storeSolrServer.request(request), storeSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<StoreSolr> solrList = response.getBeans(StoreSolr.class); StoreResponseBean storeResponseBean = new StoreResponseBean(); storeResponseBean.setStoreSolrList(solrList); if (facetFields != null && facetFields.size() > 0) { List<FacetField> solrFacetFieldList = response.getFacetFields(); storeResponseBean.setStoreSolrFacetFieldList(solrFacetFieldList); } return storeResponseBean; } @Deprecated public StoreResponseBean searchStore() throws SolrServerException, IOException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setParam("rows", getMaxResult()); solrQuery.setQuery("*"); solrQuery.setFacet(true); solrQuery.setFacetMinCount(1); solrQuery.addFacetField("name"); logger.debug("QueryRequest solrQuery: " + solrQuery); SolrRequest request = new QueryRequest(solrQuery, METHOD.POST); QueryResponse response = new QueryResponse(storeSolrServer.request(request), storeSolrServer); logger.debug("QueryResponse Obj: " + response.toString()); List<StoreSolr> solrList = response.getBeans(StoreSolr.class); List<FacetField> solrFacetFieldList = response.getFacetFields(); StoreResponseBean storeResponseBean = new StoreResponseBean(); storeResponseBean.setStoreSolrList(solrList); storeResponseBean.setStoreSolrFacetFieldList(solrFacetFieldList); return storeResponseBean; } }
package com.kiwiandroiddev.sc2buildassistant.activity.fragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import com.kiwiandroiddev.sc2buildassistant.MyApplication; import com.kiwiandroiddev.sc2buildassistant.R; import com.kiwiandroiddev.sc2buildassistant.activity.BuildEditorTabView; import com.kiwiandroiddev.sc2buildassistant.activity.EditBuildItemActivity; import com.kiwiandroiddev.sc2buildassistant.activity.IntentKeys; import com.kiwiandroiddev.sc2buildassistant.database.DbAdapter; import com.kiwiandroiddev.sc2buildassistant.domain.entity.Faction; import com.kiwiandroiddev.sc2buildassistant.adapter.EditBuildItemRecyclerAdapter; import com.kiwiandroiddev.sc2buildassistant.adapter.OnBuildItemClickedListener; import com.kiwiandroiddev.sc2buildassistant.adapter.OnBuildItemRemovedListener; import com.kiwiandroiddev.sc2buildassistant.adapter.OnStartDragListener; import com.kiwiandroiddev.sc2buildassistant.adapter.SimpleItemTouchCallback; import com.kiwiandroiddev.sc2buildassistant.domain.entity.Build; import com.kiwiandroiddev.sc2buildassistant.domain.entity.BuildItem; import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.InjectView; /** * Provides a UI for displaying a list of ordered build items that the user can edit. * Through this screen users can add, delete and rearrange build items. This screen * launches another activity (EditBuildItemActivity) to allow the user to modify details * of existing build items. * * @author matt * */ public class EditBuildItemsFragment extends Fragment implements OnStartDragListener, OnBuildItemClickedListener, OnBuildItemRemovedListener, BuildEditorTabView { public static final String TAG = "EditBuildItemsFragment"; private static final String KEY_BUILD_ITEM_ARRAY = "buildItemArray"; private Faction mFaction; // current faction of build order, used to limit unit selection private DbAdapter mDb; private EditBuildItemRecyclerAdapter mAdapter; private ItemTouchHelper mTouchHelper; private ArrayList<BuildItem> mWorkingList; private Snackbar mItemDeletedSnackbar; @InjectView(R.id.fragment_edit_build_items_list_view) RecyclerView mRecyclerView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // populate list view with build items if (savedInstanceState == null) { // set up list adapter // Okay something really funky happens here... the build object we "deserialize" from the // intent arguments is actually a reference to the original build in the parent activity! // Which causes problems because the original build's items are checked against the items // returned from this fragment to see if the user has made changes. In actual fact // any changes made will affect both build item lists meaning it will appear as though the // user has never changed anything! // The solution is to deep copy the build we get, even though it was supposedly serialized // which should perform the same function as deep copy... Build callerBuild = (Build) getArguments().getSerializable(IntentKeys.KEY_BUILD_OBJECT); //Build build = callerBuild == null ? null : (Build) UnoptimizedDeepCopy.copy(callerBuild); Build build = callerBuild; mFaction = build.getFaction(); //Timber.d(this.toString(), "in EditBuildItemsFragment.onCreate(), build id = " + Integer.toHexString(System.identityHashCode(build))); mWorkingList = build.getItems() == null ? new ArrayList<BuildItem>() : build.getItems(); } else { mWorkingList = (ArrayList<BuildItem>) savedInstanceState.getSerializable(KEY_BUILD_ITEM_ARRAY); // stub: doesn't keep up to date with faction selection in Info tab! mFaction = (Faction) savedInstanceState.getSerializable(IntentKeys.KEY_FACTION_ENUM); } // get a reference to the global DB instance MyApplication app = (MyApplication) getActivity().getApplicationContext(); this.mDb = app.getDb(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_edit_build_items, container, false); ButterKnife.inject(this, v); // can be left open from info and notes editor fragments hideKeyboard(); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); //noinspection ConstantConditions mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mAdapter = new EditBuildItemRecyclerAdapter(getActivity(), this, this, this, mWorkingList); mRecyclerView.setAdapter(mAdapter); ItemTouchHelper.Callback callback = new SimpleItemTouchCallback(mAdapter); mTouchHelper = new ItemTouchHelper(callback); mTouchHelper.attachToRecyclerView(mRecyclerView); } @Override public void onStartDrag(RecyclerView.ViewHolder viewHolder) { mTouchHelper.startDrag(viewHolder); } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable(KEY_BUILD_ITEM_ARRAY, mAdapter.getBuildItems()); outState.putSerializable(IntentKeys.KEY_FACTION_ENUM, mFaction); } /** * Called when user changes the build's faction in the Info editor fragment. * When this happens, all items should be cleared from the build because they're no longer * available to the new faction. * @param selection */ public void setFaction(Faction selection) { if (selection != mFaction) { mFaction = selection; mAdapter.clear(); } } public ArrayList<BuildItem> getBuildItems() { return mWorkingList; } @Override public void onAddButtonClicked() { Intent i = new Intent(getActivity(), EditBuildItemActivity.class); i.putExtra(IntentKeys.KEY_FACTION_ENUM, mFaction); i.putExtra(EditBuildItemActivity.KEY_DEFAULT_TIME, getDuration()); // TODO pass default supply as well? startActivityForResult(i, EditBuildItemActivity.EDIT_BUILD_ITEM_REQUEST); } @Override public void onBuildItemClicked(BuildItem item, int position) { Intent i = new Intent(getActivity(), EditBuildItemActivity.class); i.putExtra(IntentKeys.KEY_FACTION_ENUM, mFaction); i.putExtra(IntentKeys.KEY_BUILD_ITEM_OBJECT, item); i.putExtra(EditBuildItemActivity.KEY_INCOMING_BUILD_ITEM_ID, Long.valueOf(position)); // TODO pass default supply as well? startActivityForResult(i, EditBuildItemActivity.EDIT_BUILD_ITEM_REQUEST); } /** * Called with the output of the item editor dialog, from either adding a new build item * to the list or selecting an existing one to edit. * * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == EditBuildItemActivity.EDIT_BUILD_ITEM_REQUEST) { // Make sure the request was successful if (resultCode == Activity.RESULT_OK) { Long id = data.getExtras().containsKey(EditBuildItemActivity.KEY_INCOMING_BUILD_ITEM_ID) ? data.getExtras().getLong(EditBuildItemActivity.KEY_INCOMING_BUILD_ITEM_ID) : null; BuildItem item = (BuildItem) data.getExtras().getSerializable(IntentKeys.KEY_BUILD_ITEM_OBJECT); //Timber.d(this.toString(), "in EditBuildItemsFragment, got item = " + item); if (id == null) { // i.e. new build item to add // slot the new build item into the correct place based on its time int position = mAdapter.autoInsert(item); // Scroll to position of newly inserted item // TODO: off-by-one error when scrolling down to newly appended items mRecyclerView.scrollToPosition(position); invalidateUndo(); } else { // an existing one should be modified //Timber.d(this.toString(), "replacing item at index " + id + " with " + item); mAdapter.replace(item, id.intValue()); } // temp testing //Timber.d(this.toString(), "added build item, items size now = " + mAdapter.getCount()); } } } @Override public void onBuildItemRemoved(final int deletedItemPosition, final BuildItem deletedItem) { String itemName = mDb.getNameString(deletedItem.getGameItemID()); String deletionMessage = deletedItem.getCount() > 1 ? getString(R.string.deleted_items_x_N, itemName, deletedItem.getCount()) : getString(R.string.deleted_item, itemName); mItemDeletedSnackbar = Snackbar.make(getView(), deletionMessage, Snackbar.LENGTH_LONG) .setAction(R.string.undo, new View.OnClickListener() { @Override public void onClick(View v) { if (deletedItemPosition != -1 && deletedItem != null) { mAdapter.insert(deletedItem, deletedItemPosition); } mItemDeletedSnackbar = null; } }); mItemDeletedSnackbar.show(); } private void invalidateUndo() { if (mItemDeletedSnackbar != null) { mItemDeletedSnackbar.dismiss(); mItemDeletedSnackbar = null; } } // Helpers /** * returns the time value for the last build item in the list * (which should probably be the maximum time in the list) * @return time in seconds */ private int getDuration() { int count = mAdapter.getBuildItems().size(); if (count > 0) { return mAdapter.getBuildItems().get(count-1).getTime(); } else { return 0; } } /** Hides the on-screen keyboard if visible */ private void hideKeyboard() { InputMethodManager imm = (InputMethodManager) getActivity().getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mRecyclerView.getWindowToken(), 0); } @Override public boolean requestsAddButton() { return true; } }
package gov.nih.nci.cananolab.security.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import gov.nih.nci.cananolab.security.CananoUserDetails; import gov.nih.nci.cananolab.security.enums.CaNanoRoleEnum; import gov.nih.nci.cananolab.util.StringUtils; @Component("userDao") public class UserDaoImpl extends JdbcDaoSupport implements UserDao { protected Logger logger = Logger.getLogger(UserDaoImpl.class); @Autowired private DataSource dataSource; @PostConstruct private void initialize() { setDataSource(dataSource); } private static final String FETCH_USER_SQL = "select u.username, u.first_name, u.last_name, u.password, u.organization, u.department, " + "u.title, u.phone_number, u.email_id, u.enabled from users u where u.username = ?"; private static final String FETCH_USER_ROLES_SQL = "SELECT a.authority rolename FROM authorities a where a.username = ?"; private static final String FETCH_USER_GROUPS_SQL = "SELECT DISTINCT g.group_name FROM groups g LEFT JOIN group_members gm ON g.id = gm.group_id WHERE (g.created_by = ? OR gm.username = ?)"; private static final String FETCH_USERS_LIKE_SQL = "SELECT u.username, u.first_name, u.last_name, u.password, u.organization, u.department, " + "u.title, u.phone_number, u.email_id, u.enabled FROM users u " + "WHERE UPPER(username) LIKE ? OR UPPER(first_name) LIKE ? OR UPPER(last_name) LIKE ?"; private static final String FETCH_ALL_USERS_SQL = "SELECT u.username, u.first_name, u.last_name, u.password, u.organization, u.department, " + "u.title, u.phone_number, u.email_id, u.enabled FROM users u"; private static final String INSERT_USER_SQL = "insert into users(username, password, first_name, last_name, organization, department, title, phone_number, email_id, enabled) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static final String INSERT_USER_AUTHORITY_SQL = "INSERT INTO authorities(username, authority) values (?, ?)"; private static final String RESET_PASSWORD_SQL = "UPDATE users SET password = ? WHERE username = ?"; private static final String FETCH_PASSWORD_SQL = "SELECT password FROM users WHERE username = ?"; private static final String UPDATE_USER_SQL = "UPDATE users SET first_name = ?, last_name = ?, organization = ?, department = ?, title = ?, phone_number = ?, email_id = ?, enabled = ? " + "WHERE username = ?"; private static final String DELETE_ROLES_SQL = "DELETE FROM authorities WHERE username = ? AND authority != '" + CaNanoRoleEnum.ROLE_ANONYMOUS.toString() + "'"; @Override public CananoUserDetails getUserByName(String username) { logger.debug("Fetching user details for user login: " + username); CananoUserDetails user = null; if (!StringUtils.isEmpty(username)) { Object[] params = new Object[] {username}; List<CananoUserDetails> userList = (List<CananoUserDetails>) getJdbcTemplate().query(FETCH_USER_SQL, params, new UserMapper()); if (userList != null && userList.size() == 1) user = userList.get(0); } return user; } @Override public List<CananoUserDetails> getUsers(String likeStr) { logger.debug("Fetching user details with username like: " + likeStr); List<CananoUserDetails> userList = new ArrayList<CananoUserDetails>(); if (!StringUtils.isEmpty(likeStr)) { String matchStr = "%" + likeStr.toUpperCase() + "%"; Object[] params = new Object[] {matchStr, matchStr, matchStr}; userList = getJdbcTemplate().query(FETCH_USERS_LIKE_SQL, params, new UserMapper()); } else userList = getJdbcTemplate().query(FETCH_ALL_USERS_SQL, new UserMapper()); return userList; } @Override public List<String> getUserGroups(String username) { logger.debug("Fetching all groups to which user belongs: " + username); List<String> userGroups = new ArrayList<String>(); if (!StringUtils.isEmpty(username)) { Object[] params = new Object[] {username, username}; userGroups = (List<String>) getJdbcTemplate().queryForList(FETCH_USER_GROUPS_SQL, params, String.class); } return userGroups; } @Override public List<String> getUserRoles(String username) { logger.debug("Fetching all roles assigned to user: " + username); List<String> userRoles = new ArrayList<String>(); if (!StringUtils.isEmpty(username)) { Object[] params = new Object[] {username}; userRoles = (List<String>) getJdbcTemplate().queryForList(FETCH_USER_ROLES_SQL, params, String.class); } return userRoles; } @Override public int insertUser(CananoUserDetails user) { logger.debug("Insert user : " + user); int enabled = (user.isEnabled()) ? 1 : 0; Object[] params = new Object[] {user.getUsername(), user.getPassword(), user.getFirstName(), user.getLastName(), user.getOrganization(), user.getDepartment(), user.getTitle(), user.getPhoneNumber(), user.getEmailId(), Integer.valueOf(enabled)}; int status = getJdbcTemplate().update(INSERT_USER_SQL, params); return status; } @Override public int insertUserAuthority(String userName, String authority) { logger.debug("Insert user authority: user = " + userName + ", authority = " + authority); Object[] params = new Object[] {userName, authority}; int status = getJdbcTemplate().update(INSERT_USER_AUTHORITY_SQL, params); return status; } @Override public int resetPassword(String userName, String password) { logger.info("Reset password for user: " + userName); Object[] params = new Object[] {password, userName}; int status = getJdbcTemplate().update(RESET_PASSWORD_SQL, params); return status; } @Override public String readPassword(String userName) { logger.info("Read password for user : " + userName); String currPassword = (String) getJdbcTemplate().queryForObject(FETCH_PASSWORD_SQL, String.class); return currPassword; } @Override public int updateUser(CananoUserDetails userDetails) { logger.info("Update user account for user: " + userDetails.getUsername()); int enabled = (userDetails.isEnabled()) ? 1 : 0; Object[] params = new Object[] {userDetails.getFirstName(), userDetails.getLastName(), userDetails.getOrganization(), userDetails.getDepartment(), userDetails.getTitle(), userDetails.getPhoneNumber(), userDetails.getEmailId(), Integer.valueOf(enabled), userDetails.getUsername()}; int status = getJdbcTemplate().update(UPDATE_USER_SQL, params); return status; } @Override public int deleteUserAssignedRoles(String username) { logger.info("Delete all user assigned roles for :" + username); Object[] params = new Object[] {username}; int status = getJdbcTemplate().update(DELETE_ROLES_SQL, params); return status; } private static final class UserMapper implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { CananoUserDetails user = new CananoUserDetails(); user.setUsername(rs.getString("USERNAME")); user.setFirstName(rs.getString("FIRST_NAME")); user.setLastName(rs.getString("LAST_NAME")); user.setPassword(rs.getString("PASSWORD")); user.setOrganization(rs.getString("ORGANIZATION")); user.setDepartment(rs.getString("DEPARTMENT")); user.setTitle(rs.getString("TITLE")); user.setPhoneNumber(rs.getString("PHONE_NUMBER")); user.setEmailId(rs.getString("EMAIL_ID")); user.setEnabled(rs.getBoolean("ENABLED")); return user; } } }
package gui; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.JTextField; import java.util.ArrayList; /** * * @author jasonfortunato * @author linneasahlberg * */ public class PopSizePane extends EvoPane { JLabel popSizeLabel; // Population size JTextField popSizeField; JLabel popConstLabel; // Population constant ButtonGroup popConstGroup; JRadioButton popConstTrue; JRadioButton popConstFalse; JLabel initPopLabel; // Initial population JTextField initPop; JLabel carryCapLabel; // Carrying Capacity JTextField carryCap; JLabel postCrashLabel; // Crash JTextField postCrash; ArrayList<Component> vPopList = new ArrayList<Component>(); public PopSizePane() { super(); popSizeLabel = new JLabel("Initial Population Size: "); popSizeField = new JTextField(TEXT_LEN_LONG); popSizeField.setName(INT); popSizeField.setInputVerifier(iv); c.gridx = 0; c.gridy = 10; c.anchor = GridBagConstraints.WEST; add(popSizeLabel, c); c.gridx = 1; c.gridy = 10; add(popSizeField, c); // population constant radio button stuff popConstLabel = new JLabel("Population Size is: "); popConstGroup = new ButtonGroup(); popConstTrue = new JRadioButton("Constant"); popConstFalse = new JRadioButton("Varying"); popConstGroup.add(popConstTrue); popConstGroup.add(popConstFalse); c.gridx = 0; c.gridy = 20; add(popConstLabel, c); c.gridx = 1; c.gridy = 20; add(popConstTrue, c); c.gridx = 2; c.gridy = 20; add(popConstFalse, c); // carrying capacity stuff - appears when popSize varying carryCapLabel = new JLabel("Carrying Capacity: "); carryCap = new JTextField(TEXT_LEN_LONG); carryCap.setName(INT); carryCap.setInputVerifier(iv); c.gridx = 1; c.gridy = 40; c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; add(carryCapLabel, c); c.gridx = 2; c.gridy = 40; c.gridwidth = 1; c.anchor = GridBagConstraints.EAST; add(carryCap, c); c.ipadx = 0; // post crash population size stuff - appears when popSize varying postCrashLabel = new JLabel("Post Crash Population Size: "); postCrash = new JTextField(TEXT_LEN_LONG); postCrash.setName(INT); postCrash.setInputVerifier(iv); c.gridx = 1; c.gridy = 50; c.gridwidth = 2; c.anchor = GridBagConstraints.WEST; add(postCrashLabel, c); c.gridx = 2; c.gridy = 50; c.gridwidth = 1; c.anchor = GridBagConstraints.EAST; //c.ipadx = -55; add(postCrash, c); c.ipadx = 0; // Add all that will be disabled when PopSize is constant to the vPopList vPopList.add(carryCapLabel); vPopList.add(carryCap); vPopList.add(postCrashLabel); vPopList.add(postCrash); // Set actions for the PopConstTrue/False radio buttons popConstTrue.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { modeConstPop(true); } }); popConstFalse.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { modeConstPop(false); } }); } private void modeConstPop(boolean b){ for(Component comp : vPopList) { comp.setEnabled(!b); } if(b == true) { // clear the two text fields carryCap.setText(""); postCrash.setText(""); } } public void submit(shared.SessionParameters p) { p.setPopSize(Integer.parseInt(popSizeField.getText())); p.setPopConst(popConstTrue.isSelected()); if(popConstFalse.isSelected()){ p.setPopCapacity(Integer.parseInt(carryCap.getText())); p.setCrashCapacity(Integer.parseInt(postCrash.getText())); } } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.util.*; import java.util.regex.*; public class Factoid { public Factoid() { } public Factoid(String subject, boolean fact, String info, long date) { this.subject = subject; this.fact = fact; this.info = info; this.date = date; } public int id; public String subject; public boolean fact; public String info; public long date; } public class FactoidEnumerator { public FactoidEnumerator() { } public FactoidEnumerator(String enumSource, int index, int count) { this.enumSource = enumSource; this.index = index; this.count = count; this.lastUsed = System.currentTimeMillis(); } public int getNext() { index++; if (index >= count) { index = 0; } lastUsed = System.currentTimeMillis(); return index; } public int id; public String enumSource; public int index; public int count; public long lastUsed; } public class Factoids2 { public String[] info() { return new String[] { "Stores, recalls and collects facts and rumours.", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } private static long ENUM_TIMEOUT = 5 * 60 * 1000; // 5 minutes private Modules mods; private IRCInterface irc; private Pattern filterFactoidsPattern; public Factoids2(Modules mods, IRCInterface irc) { this.mods = mods; this.irc = irc; filterFactoidsPattern = Pattern.compile(filterFactoidsRegex); mods.interval.callBack(null, 60000, 1); } private int countFacts(List<Factoid> definitions) { int factCount = 0; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (defn.fact) { factCount++; } } return factCount; } private int countRumours(List<Factoid> definitions) { int rumourCount = 0; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (!defn.fact) { rumourCount++; } } return rumourCount; } private Factoid pickDefinition(List<Factoid> definitions, String enumSource) { if (countFacts(definitions) > 0) return pickFact(definitions, enumSource); return pickRumour(definitions, enumSource); } private Factoid pickFact(List<Factoid> definitions, String enumSource) { return pickDefinition(definitions, true, countFacts(definitions), enumSource); } private Factoid pickRumour(List<Factoid> definitions, String enumSource) { return pickDefinition(definitions, false, countRumours(definitions), enumSource); } private Factoid pickDefinition(List<Factoid> definitions, boolean fact, int count, String enumSource) { int index = -1; enumSource = enumSource.toLowerCase(); List<FactoidEnumerator> enums = mods.odb.retrieve(FactoidEnumerator.class, "WHERE enumSource = '" + mods.odb.escapeString(enumSource) + "'"); FactoidEnumerator fEnum = null; if (enums.size() >= 1) { fEnum = enums.get(0); if (fEnum.count != count) { // Count has changed: invalidated! mods.odb.delete(fEnum); fEnum = null; } else { // Alright, step to the next one. index = fEnum.getNext(); mods.odb.update(fEnum); } } if (fEnum == null) { // No enumerator, pick random start and create one. index = (int)Math.floor(Math.random() * count); fEnum = new FactoidEnumerator(enumSource, index, count); mods.odb.save(fEnum); } Factoid rvDefn = null; for (int i = 0; i < definitions.size(); i++) { Factoid defn = definitions.get(i); if (defn.fact == fact) { if (index == 0) { rvDefn = defn; break; } index } } return rvDefn; } private List<Factoid> getDefinitions(String subject, String search) { subject = subject.toLowerCase(); String odbQuery = "WHERE subject = '" + mods.odb.escapeString(subject) + "'"; if (search.length() > 0) { if (search.startsWith("/") && search.endsWith("/")) { // Regexp odbQuery += " AND info RLIKE \"" + mods.odb.escapeString(search.substring(1, search.length() - 1)) + "\""; } else { // Substring odbQuery += " AND info LIKE \"%" + mods.odb.escapeString(search) + "%\""; } } return mods.odb.retrieve(Factoid.class, odbQuery); } // Interval public void interval(Object param) { // Clean up dead enumerators. long lastUsedCutoff = System.currentTimeMillis() - ENUM_TIMEOUT; List<FactoidEnumerator> deadEnums = mods.odb.retrieve(FactoidEnumerator.class, "WHERE lastUsed < " + lastUsedCutoff); for (int i = 0; i < deadEnums.size(); i++) { mods.odb.delete(deadEnums.get(i)); } mods.interval.callBack(null, 60000, 1); } // Collect and store rumours for things. public String filterFactoidsRegex = "(\\w{4,})\\s+((?:is|was)\\s+.{4,})"; public void filterFactoids(Message mes) throws ChoobException { Matcher rMatcher = filterFactoidsPattern.matcher(mes.getMessage()); if (rMatcher.matches()) { String subject = rMatcher.group(1).toLowerCase(); String defn = rMatcher.group(2); Factoid rumour = new Factoid(subject, false, defn, mes.getMillis()); mods.odb.save(rumour); // Remove oldest so we only have the 5 most recent. List<Factoid> results = mods.odb.retrieve(Factoid.class, "WHERE fact = 0 AND subject = '" + mods.odb.escapeString(subject) + "' SORT DESC date"); for (int i = 5; i < results.size(); i++) { Factoid oldRumour = (Factoid)results.get(i); mods.odb.delete(oldRumour); } } } // Manually add facts to the system. public String[] helpCommandAdd = { "Add a new factual definition for a term.", "<term> <defn>", "<term> is the term to which the definition applies", "<defn> is the definition itself" }; public void commandAdd(Message mes) { String[] params = mods.util.getParamArray(mes, 2); if (params.length <= 2) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Add " + helpCommandAdd[1] + "'"); return; } String subject = params[1].toLowerCase(); String defn = params[2]; Factoid fact = new Factoid(subject, true, defn, mes.getMillis()); mods.odb.save(fact); irc.sendContextReply(mes, "Added definition for '" + subject + "'."); } // Remove facts from the system. public String[] helpCommandRemove = { "Remove a definition (both facts and rumours).", "<term> [<search>]", "<term> is the term to remove", "<search> limits the removal to only matching defintions, if multiple ones exist (substring or regexp allowed)" }; public void commandRemove(Message mes) { String[] params = mods.util.getParamArray(mes, 2); if (params.length <= 1) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Remove " + helpCommandRemove[1] + "'"); return; } List<Factoid> removals = getDefinitions(params[1], (params.length > 2 ? params[2] : "")); if (removals != null) { for (int i = 0; i < removals.size(); i++) { Factoid defn = (Factoid)removals.get(i); mods.odb.delete(defn); } if (removals.size() > 1) { irc.sendContextReply(mes, removals.size() + " definitions for '" + params[1] + "' removed."); } else if (removals.size() == 1) { irc.sendContextReply(mes, "1 definition for '" + params[1] + "' removed."); } else { irc.sendContextReply(mes, "No definitions for '" + params[1] + "' found."); } } } // Retrieve definitions from the system. public String[] helpCommandGet = { "Returns a/the definition for a term.", "<term> [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGet(Message mes) throws ChoobException { String[] params = mods.util.getParamArray(mes, 2); if (params.length <= 1) { irc.sendContextReply(mes, "Syntax: 'Factoids2.Get " + helpCommandGet[1] + "'"); return; } List<Factoid> definitions = getDefinitions(params[1], (params.length > 2 ? params[2] : "")); if (definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + params[1] + "'!"); } else { int factCount = countFacts(definitions); int rumourCount = countRumours(definitions); if (factCount > 0) { Factoid fact = pickFact(definitions, mes.getContext() + ":" + params[1]); if (factCount > 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (" + (factCount - 1) + " other defns)"); } else if (factCount == 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (1 other defn)"); } else { irc.sendContextReply(mes, fact.subject + " " + fact.info); } } else { Factoid rumour = pickRumour(definitions, mes.getContext() + ":" + params[1]); if (rumourCount > 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (" + (rumourCount - 1) + " other rumours)"); } else if (rumourCount == 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (1 other rumour)"); } else { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info); } } } } public String[] helpCommandGetFact = { "Returns a/the factual definition for a term.", "<term> [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGetFact(Message mes) throws ChoobException { String[] params = mods.util.getParamArray(mes, 2); if (params.length <= 1) { irc.sendContextReply(mes, "Syntax: 'Factoids2.GetFact " + helpCommandGetFact[1] + "'"); return; } List<Factoid> definitions = getDefinitions(params[1], (params.length > 2 ? params[2] : "")); if (definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + params[1] + "'!"); } else { int factCount = countFacts(definitions); if (factCount > 0) { Factoid fact = pickFact(definitions, mes.getContext() + ":" + params[1]); if (factCount > 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (" + (factCount - 1) + " other defns)"); } else if (factCount == 2) { irc.sendContextReply(mes, fact.subject + " " + fact.info + " (1 other defn)"); } else { irc.sendContextReply(mes, fact.subject + " " + fact.info); } } else { irc.sendContextReply(mes, "Sorry, I don't have any facts about '" + params[1] + "'."); } } } public String[] helpCommandGetRumour = { "Returns a/the definition for a term.", "<term> [<search>]", "<term> is the term to define", "<search> limits the definition(s) given, if multiple ones exist (substring or regexp allowed)" }; public void commandGetRumour(Message mes) throws ChoobException { String[] params = mods.util.getParamArray(mes, 2); if (params.length <= 1) { irc.sendContextReply(mes, "Syntax: 'Factoids2.GetRumour " + helpCommandGetRumour[1] + "'"); return; } List<Factoid> definitions = getDefinitions(params[1], (params.length > 2 ? params[2] : "")); if (definitions.size() == 0) { irc.sendContextReply(mes, "Sorry, I don't know anything about '" + params[1] + "'!"); } else { int rumourCount = countRumours(definitions); if (rumourCount > 0) { Factoid rumour = pickRumour(definitions, mes.getContext() + ":" + params[1]); if (rumourCount > 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (" + (rumourCount - 1) + " other rumours)"); } else if (rumourCount == 2) { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info + " (1 other rumour)"); } else { irc.sendContextReply(mes, "Rumour has it " + rumour.subject + " " + rumour.info); } } else { irc.sendContextReply(mes, "Sorry, I don't have any rumours about '" + params[1] + "'."); } } } }
package jp.ac.ynu.pl2017.gg.reversi.server; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.net.ServerSocket; import java.net.Socket; class Server implements Serializable{ private static int maxConnection = 100; private static Socket[] incoming; private static boolean[] flag; private static InputStream[] is; private static OutputStream[] os; private static ClientProcThread[] myClientProcThread; private static int member; public static void SetFlag(int n, boolean value) { flag[n] = value; } public static void main(String[] args) { incoming = new Socket[maxConnection]; flag = new boolean[maxConnection]; is = new InputStream[maxConnection]; os = new OutputStream[maxConnection]; myClientProcThread = new ClientProcThread[maxConnection]; int n = 1; member = 0; try { System.out.println(""); ServerSocket server = new ServerSocket(50000);// 50000 while (true) { incoming[n] = server.accept(); flag[n] = true; System.out.println("Accept client No." + n); is[n] = incoming[n].getInputStream(); os[n] = incoming[n].getOutputStream(); myClientProcThread[n] = new ClientProcThread(n, incoming[n], is[n], os[n]); myClientProcThread[n].start(); member = n; n++; } } catch (Exception e) { System.err.println(": " + e); e.printStackTrace(); } } }
package org.ovirt.engine.core.bll; import org.ovirt.engine.core.common.queries.GetTagUserMapByTagNameParameters; // NOT IN USE public class GetTagUserMapByTagNameQuery<P extends GetTagUserMapByTagNameParameters> extends QueriesCommandBase<P> { public GetTagUserMapByTagNameQuery(P parameters) { super(parameters); } @Override protected void executeQueryCommand() { getQueryReturnValue() .setReturnValue(getDbFacade().getTagDAO().getTagUserMapByTagName(getParameters().getTagName())); } }
package cn.bjtu.nourriture.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v4.app.Fragment; import android.os.Bundle; import android.widget.Toast; import cn.bjtu.nourriture.AnonymousActivity; import cn.bjtu.nourriture.R; public class LogoutFragment extends Fragment { public static LogoutFragment newInstance() { LogoutFragment fragment = new LogoutFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences preferences = getActivity().getSharedPreferences( "GLOBAL", Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.remove(getString(R.string.username_pref)); editor.remove(getString(R.string.token_pref)); editor.remove(getString(R.string.user_id_pref)); editor.apply(); Toast.makeText(getContext(), "You have been disconnected", Toast.LENGTH_LONG).show(); Intent intent = new Intent(getActivity(), AnonymousActivity.class); startActivity(intent); } }
package com.example.bootweb.thymeleaf.web; import java.util.ArrayList; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import com.example.bootweb.thymeleaf.web.view.Dashboard; import com.example.bootweb.thymeleaf.web.view.Index; @Controller public class IndexController { private final Logger logger = LoggerFactory.getLogger(IndexController.class); @Value("${dashboard.number:4}") private Integer dashboardNumber; @Autowired private RequestMappingHandlerMapping handlerMapping; @RequestMapping(value = {"/index.html", "/index", "/"}) public String index(Model model) { model.addAttribute("title", "Thymeleaf"); Index index = new Index(); index.getDashboards().add(make("Git ", "https://progit.bootcss.com/", // "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==", "GitGitGitGitGit")); index.getDashboards().add(make("Metro Bootstrap", "http: "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==", "Flat UI BootstrapMetroFlat UIBootstrap")); index.getDashboards().add(make("", "http: "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==", "")); index.getDashboards().add(make("Bootstrap", "http: "data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==", "web")); index.setDashboards(new ArrayList<>(index.getDashboards()).subList(0, index.getDashboards().size() >= dashboardNumber ? dashboardNumber : index.getDashboards().size())); index.getList().addAll(index.getDashboards()); index.getList().add(make("Thymeleaf", "http: null, "Thymeleaf is a modern server-side Java template engine for both web and standalone environments.")); index.getList().add(make("git - ", "http: null, " git ")); index.getList().add(make("Layui", "http: null, "UI")); index.getList().add(make("WebJars", "http: null, "WebJars are client-side web libraries (e.g. jQuery & Bootstrap) packaged into JAR (Java Archive) files.")); index.getList().add(make("Angularjs", "https://angularjs.org/", // null, "Angularjs")); index.getList().add(make("angular.cn", "https: null, "")); index.getList().add(make("JHipster", "http: null, "JHipster is a development platform to generate, develop and deploy Spring Boot + Angular Web applications and Spring microservices. ")); index.getList().add(make("flexmark-java", "https://github.com/vsch/flexmark-java", // null, "flexmark-java is a Java implementation of CommonMark 0.28 spec parser using the blocks first, inlines after Markdown parsing architecture.")); index.getList().add(make("Spring Boot", "http: null, "Daniel WoodsNetflix")); index.getList().add(make("WindowsGit", "http: null, "WindowsGit")); index.getList().add(make("Git", "http: null, "-")); index.getList().add(make("Github spring-projects", "https://github.com/spring-projects", // null, "-")); index.getList().add(make("Github spring-guides", "https://github.com/spring-guides/", // null, "-")); index.getList().add(make("Gradle", "http: null, "-")); index.getList().add(make("", "https://github.com/qibaoguang/Study-Step-by-Step", // null, "-")); index.getList().add(make("", "https://github.com/justjavac/free-programming-books-zh_CN", // null, "-")); index.getList().add(make("&", "http://blog.csdn.net/qq1175421841/article/details/51222769", // null, "-")); index.getList().add(make("Jersey guide", "https://jersey.github.io/documentation/latest/getting-started.html", // null, "-")); index.getList().add(make("Java 8", "http: null, "-")); index.getList().add(make("springfox-demos", "https://github.com/springfox/springfox-demos", // null, "-")); index.getList().add(make("swaggerhub.com", "https://app.swaggerhub.com/help/index", // null, "-")); model.addAttribute("data", index); model.addAttribute("handlerMethods", handlerMapping.getHandlerMethods()); for (Map.Entry<RequestMappingInfo, HandlerMethod> map : handlerMapping.getHandlerMethods().entrySet()) { RequestMappingInfo info = map.getKey(); logger.info("{}-{}", map.getKey(), map.getValue()); } // StringBuilder builder = new StringBuilder("{"); // builder.append(this.patternsCondition); // if (!this.methodsCondition.isEmpty()) { // builder.append(",methods=").append(this.methodsCondition); // if (!this.paramsCondition.isEmpty()) { // builder.append(",params=").append(this.paramsCondition); // if (!this.headersCondition.isEmpty()) { // builder.append(",headers=").append(this.headersCondition); // if (!this.consumesCondition.isEmpty()) { // builder.append(",consumes=").append(this.consumesCondition); // if (!this.producesCondition.isEmpty()) { // builder.append(",produces=").append(this.producesCondition); // if (!this.customConditionHolder.isEmpty()) { // builder.append(",custom=").append(this.customConditionHolder); // builder.append('}'); return "index"; } private Dashboard make(String text, String url, String src, String desc) { Dashboard dashboard = new Dashboard(); dashboard.setText(text); dashboard.setSrc(src); dashboard.setUrl(url); dashboard.setDesc(desc); return dashboard; } }
package com.intellij.openapi.vcs.changes.committed; import com.intellij.openapi.project.Project; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.ChangesUtil; import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNodeRenderer; import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder; import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList; import com.intellij.util.ui.Tree; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import java.awt.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; /** * @author yole */ public class StructureFilteringStrategy implements ChangeListFilteringStrategy { private CopyOnWriteArrayList<ChangeListener> myListeners = new CopyOnWriteArrayList<ChangeListener>(); private MyUI myUI; private final Project myProject; private final List<FilePath> mySelection = new ArrayList<FilePath>(); public StructureFilteringStrategy(final Project project) { myProject = project; } public String toString() { return VcsBundle.message("filter.structure.name"); } @Nullable public JComponent getFilterUI() { if (myUI == null) { myUI = new MyUI(); } return myUI; } public void setFilterBase(List<CommittedChangeList> changeLists) { if (myUI == null) { myUI = new MyUI(); } myUI.buildModel(changeLists); } public void addChangeListener(ChangeListener listener) { myListeners.add(listener); } public void removeChangeListener(ChangeListener listener) { myListeners.remove(listener); } public List<CommittedChangeList> filterChangeLists(List<CommittedChangeList> changeLists) { if (mySelection.size() == 0) { return changeLists; } final ArrayList<CommittedChangeList> result = new ArrayList<CommittedChangeList>(); for(CommittedChangeList list: changeLists) { if (listMatchesSelection(list)) { result.add(list); } } return result; } private boolean listMatchesSelection(final CommittedChangeList list) { for(Change change: list.getChanges()) { FilePath path = ChangesUtil.getFilePath(change); for(FilePath selPath: mySelection) { if (path.isUnder(selPath, false)) { return true; } } } return false; } private class MyUI extends JPanel { private Tree myStructureTree; private boolean myRendererInitialized; public MyUI() { setLayout(new BorderLayout()); myStructureTree = new Tree(); myStructureTree.setRootVisible(false); myStructureTree.setShowsRootHandles(true); myStructureTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(final TreeSelectionEvent e) { mySelection.clear(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); if (node.getUserObject() instanceof FilePath) { mySelection.add((FilePath) node.getUserObject()); } for(ChangeListener listener: myListeners) { listener.stateChanged(new ChangeEvent(this)); } } }); add(new JScrollPane(myStructureTree), BorderLayout.CENTER); } public void buildModel(final List<CommittedChangeList> changeLists) { final Set<FilePath> filePaths = new HashSet<FilePath>(); for(CommittedChangeList changeList: changeLists) { for(Change change: changeList.getChanges()) { filePaths.add(ChangesUtil.getFilePath(change)); } } final TreeModelBuilder builder = new TreeModelBuilder(myProject, false); final DefaultTreeModel model = builder.buildModelFromFilePaths(filePaths); deleteLeafNodes((DefaultMutableTreeNode) model.getRoot()); myStructureTree.setModel(model); if (!myRendererInitialized) { myRendererInitialized = true; myStructureTree.setCellRenderer(new ChangesBrowserNodeRenderer(myProject, false, false)); } } private void deleteLeafNodes(final DefaultMutableTreeNode node) { for(int i=node.getChildCount()-1; i >= 0; i final TreeNode child = node.getChildAt(i); if (child.isLeaf()) { node.remove(i); } else { deleteLeafNodes((DefaultMutableTreeNode) child); } } } } }
package StepDefinitions; import Helpers.API; import cucumber.api.java.After; import cucumber.api.java.en.*; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import java.util.Random; public class Steps { static WebDriver driver; static String LanguageDependence; @Given("^Open selenium webdriver$") public void OpenDriver() { System.out.print(System.getProperty("user.dir")); System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); } @When("^Open page '(.*)'$") public void OpenPage(String url) { driver.get(url); } @When("^Click element '(.*)'$") public void ClickElement(String css) { driver.findElement(By.cssSelector(css)).click(); } @When("^Fill textbox '(.*)' as '(.*)'$") public void FillTextbox(String css, String text) { driver.findElement(By.cssSelector(css)).clear(); driver.findElement(By.cssSelector(css)).sendKeys(text); } @Then("^Verify element '(.*)' text is '(.*)'$") public void CheckText(String css, String expected) throws InterruptedException { Thread.sleep(1000); String actual = driver.findElement(By.cssSelector(css)).getText(); Assert.assertEquals(expected, actual); } @Then("^Verify element '(.*)' text is equal with the API$") public void CheckLanguageDependence(String css) throws InterruptedException { Thread.sleep(1000); String actual = driver.findElement(By.cssSelector(css)).getText(); Assert.assertEquals(LanguageDependence, actual); } @When("^Open one of the game page randomly$") public void OpenGame() { int count = driver.findElements(By.cssSelector("#collectionitems tr")).size(); int randomElement = new Random().nextInt(count - 1) + 2; ClickElement("#collectionitems tr:nth-of-type(" + randomElement + ") td:nth-of-type(1) a"); } @When("^Check most voted results in the API$") public void CheckMostVoted() throws Exception { String currentUrl = driver.getCurrentUrl(); int slashIndex = currentUrl.lastIndexOf('/'); String gameId = currentUrl.substring(36, slashIndex); String geekItemPollResponse = API.CallAPI("https://boardgamegeek.com/geekitempoll.php?action=view&itempolltype=languagedependence&objectid=" + gameId + "&objecttype=thing"); JSONObject jsonObject = new JSONObject(geekItemPollResponse); String pollId = jsonObject.getJSONObject("poll").getString("pollid"); String geekPollResponse = API.CallAPI("https://boardgamegeek.com/geekpoll.php?action=results&pollid=" + pollId); jsonObject = new JSONObject(geekPollResponse); JSONArray results = jsonObject.getJSONArray("pollquestions").getJSONObject(0).getJSONObject("results").getJSONArray("results"); for (int i = 0; i < results.length(); i++) { if (results.getJSONObject(i).getBoolean("max") == true) { LanguageDependence = results.getJSONObject(i).getString("columnbody"); } } } @After public void CloseDriver() { driver.close(); driver.quit(); } }
package com.splicemachine.mrio.api; import java.io.IOException; import java.sql.PreparedStatement; import java.util.List; import com.splicemachine.db.iapi.sql.execute.ExecRow; import com.splicemachine.db.iapi.types.RowLocation; import org.apache.hadoop.mapreduce.Job; import org.apache.spark.api.java.JavaPairRDD; import org.junit.Assert; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runner.Description; import scala.Tuple2; import com.splicemachine.derby.test.framework.SpliceSparkWatcher; import com.splicemachine.derby.test.framework.SpliceWatcher; import com.splicemachine.derby.test.framework.SpliceDataWatcher; import com.splicemachine.derby.test.framework.SpliceSchemaWatcher; import com.splicemachine.derby.test.framework.SpliceTableWatcher; import com.splicemachine.mrio.MRConstants; public class SMInputFormatIT extends BaseMRIOTest { private static final String CLASS_NAME = SMInputFormatIT.class.getSimpleName().toUpperCase(); private static SpliceWatcher classWatcher = new SpliceWatcher(CLASS_NAME); private static final SpliceSchemaWatcher schemaWatcher = new SpliceSchemaWatcher(CLASS_NAME); private static final SpliceTableWatcher tableWatcherA = new SpliceTableWatcher( "A", schemaWatcher.schemaName, "(col1 varchar(100) primary key, col2 varchar(100))"); private static final SpliceTableWatcher tableWatcherB = new SpliceTableWatcher( "B", schemaWatcher.schemaName, "(col1 bigint primary key, col2 varchar(100))"); private static final SpliceSparkWatcher sparkWatcher = new SpliceSparkWatcher(CLASS_NAME); @ClassRule public static TestRule chain = RuleChain.outerRule(classWatcher) .around(schemaWatcher) .around(tableWatcherA) .around(tableWatcherB) .around(sparkWatcher) .around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try{ PreparedStatement ps1; PreparedStatement ps2; ps1 = classWatcher.prepareStatement( "insert into " + tableWatcherA + " (col1, col2) values (?,?)"); ps1.setString(1, "John"); ps1.setString(2, "Leach"); ps1.executeUpdate(); ps1.setString(1, "Jenny"); ps1.setString(2, "Swift"); ps1.executeUpdate(); ps2 = classWatcher.prepareStatement( "insert into " + tableWatcherB + " (col1, col2) values (?,?)"); for (int i =0; i<10000;i++) { ps2.setInt(1, i); ps2.setString(2, i+"sdfasdgffdgdfgdfgdfgdfgdfgdfgd"); ps2.executeUpdate(); if (i==500) { flushTable(tableWatcherB.toString()); splitTable(tableWatcherB.toString()); } if (i==750) { flushTable(tableWatcherB.toString()); } if (i==1000) { flushTable(tableWatcherB.toString()); } } } catch (Exception e) { throw new RuntimeException(e); } finally { classWatcher.closeAll(); } } }); @Rule public SpliceWatcher methodWatcher = new SpliceWatcher(CLASS_NAME); @Test public void testSparkIntegrationWithInputFormat() throws IOException { config.set(MRConstants.SPLICE_INPUT_TABLE_NAME, tableWatcherA.toString()); Job job = new Job(config, "Test Scan"); JavaPairRDD<RowLocation, ExecRow> table = sparkWatcher.jsc.newAPIHadoopRDD(job.getConfiguration(), SMInputFormat.class, RowLocation.class, ExecRow.class); List<Tuple2<RowLocation, ExecRow>> data = table.collect(); int i = 0; for (Tuple2<RowLocation, ExecRow> tuple: data) { i++; Assert.assertNotNull(tuple._1); Assert.assertNotNull(tuple._2); } Assert.assertEquals("Incorrect Results Returned", 2,i); } @Test public void testCountOverMultipleRegionsInSpark() throws IOException { config.set(MRConstants.SPLICE_INPUT_TABLE_NAME, tableWatcherB.toString()); Job job = new Job(config, "Test Scan"); JavaPairRDD<RowLocation, ExecRow> table = sparkWatcher.jsc.newAPIHadoopRDD(job.getConfiguration(), SMInputFormat.class, RowLocation.class, ExecRow.class); List<Tuple2<RowLocation, ExecRow>> data = table.collect(); int i = 0; for (Tuple2<RowLocation, ExecRow> tuple: data) { i++; Assert.assertNotNull(tuple._1); Assert.assertNotNull(tuple._2); } Assert.assertEquals("Incorrect Results Returned", 10000,i); } }
package com.treetank.gui.view.sunburst; import java.util.List; import java.util.Stack; import com.treetank.api.IReadTransaction; import com.treetank.axis.AbsAxis; import com.treetank.diff.EDiff; import com.treetank.gui.view.sunburst.Item.Builder; import com.treetank.node.AbsStructNode; import com.treetank.settings.EFixed; import com.treetank.utils.FastStack; import processing.core.PConstants; /** * @author Johannes Lichtenberger, University of Konstanz * */ public final class SunburstCompareDescendantAxis extends AbsAxis { /** Extension stack. */ private transient Stack<Float> mExtensionStack; /** Children per depth. */ private transient Stack<Integer> mDescendantsStack; /** Angle stack. */ private transient Stack<Float> mAngleStack; /** Parent stack. */ private transient Stack<Integer> mParentStack; /** Diff stack. */ private transient Stack<Integer> mDiffStack; /** Determines movement of transaction. */ private transient EMoved mMoved; /** Index to parent node. */ private transient int mIndexToParent; /** Parent extension. */ private transient float mParExtension; /** Extension. */ private transient float mExtension; /** Depth in the tree starting at 0. */ private transient int mDepth; /** Start angle. */ private transient float mAngle; /** Current item index. */ private transient int mIndex; /** Current item. */ private transient Item mItem; /** Builder for an item. */ private transient Builder mBuilder; /** Stack for remembering next nodeKey in document order. */ private transient FastStack<Long> mRightSiblingKeyStack; /** The nodeKey of the next node to visit. */ private transient long mNextKey; /** Model which implements the method createSunburstItem(...) defined by {@link IModel}. */ private transient IModel mModel; /** {@link List} of {@link EDiff}s. */ private transient List<EDiff> mDiffs; /** Modification count. */ private transient int mModificationCount; /** Parent modification count. */ private transient int mParentModificationCount; /** Descendant count. */ private transient int mDescendantCount; /** Parent descendant count. */ private transient int mParentDescendantCount; /** * Constructor initializing internal state. * * @param paramRtx * exclusive (immutable) trx to iterate with * @param paramModel * {@link IModel} implementation which observes axis changes * @param paramDiffs * {@link List} of {@link EDiff}s */ public SunburstCompareDescendantAxis(final IReadTransaction paramRtx, final IModel paramModel, final List<EDiff> paramDiffs) { super(paramRtx); mModel = paramModel; mDiffs = paramDiffs; } /** * Constructor initializing internal state. * * @param paramRtx * exclusive (immutable) trx to iterate with * @param mIncludeSelf * determines if self is included * @param paramModel * {@link IModel} implementation which observes axis changes * @param paramDiffs * {@link List} of {@link EDiff}s */ public SunburstCompareDescendantAxis(final IReadTransaction paramRtx, final boolean mIncludeSelf, final IModel paramModel, final List<EDiff> paramDiffs) { super(paramRtx, mIncludeSelf); mModel = paramModel; mDiffs = paramDiffs; } /** * {@inheritDoc} */ @Override public void reset(final long mNodeKey) { super.reset(mNodeKey); mRightSiblingKeyStack = new FastStack<Long>(); if (isSelfIncluded()) { mNextKey = getTransaction().getNode().getNodeKey(); } else { mNextKey = ((AbsStructNode)getTransaction().getNode()).getFirstChildKey(); } mExtensionStack = new Stack<Float>(); mDescendantsStack = new Stack<Integer>(); mAngleStack = new Stack<Float>(); mParentStack = new Stack<Integer>(); mDiffStack = new Stack<Integer>(); mAngle = 0F; mDepth = 0; mModificationCount = 0; mParentModificationCount = 0; mDescendantCount = 0; mParentDescendantCount = 0; mMoved = EMoved.STARTRIGHTSIBL; mIndexToParent = -1; mParExtension = PConstants.TWO_PI; mExtension = PConstants.TWO_PI; mIndex = -1; mItem = Item.ITEM; mBuilder = Item.BUILDER; } /** * {@inheritDoc} */ @Override public boolean hasNext() { resetToLastKey(); // Check for deletions. if (!mDiffs.isEmpty()) { final EDiff diff = mDiffs.remove(0); if (diff == EDiff.DELETED) { // FIXME mExtension = mModel.createSunburstItem(mItem, mDepth, mIndex); return true; } } // Fail if there is no node anymore. if (mNextKey == (Long)EFixed.NULL_NODE_KEY.getStandardProperty()) { resetToStartKey(); return false; } getTransaction().moveTo(mNextKey); // Fail if the subtree is finished. if (((AbsStructNode)getTransaction().getNode()).getLeftSiblingKey() == getStartKey()) { resetToStartKey(); return false; } // Always follow first child if there is one. if (((AbsStructNode)getTransaction().getNode()).hasFirstChild()) { mNextKey = ((AbsStructNode)getTransaction().getNode()).getFirstChildKey(); if (((AbsStructNode)getTransaction().getNode()).hasRightSibling()) { mRightSiblingKeyStack.push(((AbsStructNode)getTransaction().getNode()).getRightSiblingKey()); } processMove(); mExtension = mModel.createSunburstItem(mItem, mDepth, mIndex); final int diffCounts = countDiffs(); mDiffStack.push(diffCounts); mAngleStack.push(mAngle); mExtensionStack.push(mExtension); mParentStack.push(mIndex); mDescendantsStack.push(mDescendantCount); mDepth++; mMoved = EMoved.CHILD; return true; } // Then follow right sibling if there is one. if (((AbsStructNode)getTransaction().getNode()).hasRightSibling()) { mNextKey = ((AbsStructNode)getTransaction().getNode()).getRightSiblingKey(); processMove(); mExtension = mModel.createSunburstItem(mItem, mDepth, mIndex); mAngle += mExtension; mMoved = EMoved.STARTRIGHTSIBL; return true; } // Then follow right sibling on stack. if (mRightSiblingKeyStack.size() > 0) { mNextKey = mRightSiblingKeyStack.pop(); processMove(); mExtension = mModel.createSunburstItem(mItem, mDepth, mIndex); // Next node will be a right sibling of an anchestor node or the traversal ends. mMoved = EMoved.ANCHESTSIBL; final long currNodeKey = getTransaction().getNode().getNodeKey(); boolean first = true; do { if (((AbsStructNode)getTransaction().getNode()).hasParent() && getTransaction().getNode().getNodeKey() != mNextKey) { if (first) { // Do not pop from stack if it's a leaf node. first = false; } else { mDiffStack.pop(); mAngleStack.pop(); mExtensionStack.pop(); mParentStack.pop(); mDescendantsStack.pop(); } getTransaction().moveToParent(); mDepth } else { break; } } while (!((AbsStructNode)getTransaction().getNode()).hasRightSibling()); getTransaction().moveTo(currNodeKey); return true; } // Then end. mNextKey = (Long)EFixed.NULL_NODE_KEY.getStandardProperty(); return true; } /** Process movement. */ private void processMove() { mBuilder.set(mAngle, mParExtension, mIndexToParent).setDescendantCount(mDescendantCount) .setParentDescendantCount(mParentDescendantCount).setModificationCount(mModificationCount) .setParentModificationCount(mParentModificationCount).set(); mMoved.processCompareMove(getTransaction(), mItem, mAngleStack, mExtensionStack, mParentStack, mParentStack, mDiffStack); mModificationCount = mItem.mModificationCount; mParentModificationCount = mItem.mParentModificationCount; mDescendantCount = mItem.mDescendantCount; mParentDescendantCount = mItem.mParentDescendantCount; mAngle = mItem.mAngle; mParExtension = mItem.mExtension; mIndexToParent = mItem.mIndexToParent; mIndex++; } /** * Increment diff counter if it's a modified diff. * * @param paramIndex * index of diff to get * @param paramDiffCounts * diff counter * @return modified diff counter */ private int incrDiffCounter(final int paramIndex, int paramDiffCounts) { final EDiff intermDiff = mDiffs.get(paramIndex); if (intermDiff != EDiff.SAME && intermDiff != EDiff.DONE) { paramDiffCounts++; } return paramDiffCounts; } /** * Count how many differences in the subtree exists. * * @return number of differences */ private int countDiffs() { int index = 0; int diffCounts = 0; final long nodeKey = getTransaction().getNode().getNodeKey(); do { boolean done = false; diffCounts = incrDiffCounter(index++, diffCounts); if (((AbsStructNode)getTransaction().getNode()).hasFirstChild()) { getTransaction().moveToFirstChild(); diffCounts = incrDiffCounter(index++, diffCounts); } else if (((AbsStructNode)getTransaction().getNode()).hasFirstChild()) { getTransaction().moveToRightSibling(); diffCounts = incrDiffCounter(index++, diffCounts); } else { do { if (((AbsStructNode)getTransaction().getNode()).hasParent() && getTransaction().getNode().getNodeKey() != nodeKey) { getTransaction().moveToParent(); } else { done = true; break; } } while (!((AbsStructNode)getTransaction().getNode()).hasRightSibling()); if (!done) { getTransaction().moveToRightSibling(); diffCounts = incrDiffCounter(index++, diffCounts); } } } while (getTransaction().getNode().getNodeKey() != nodeKey); getTransaction().moveTo(nodeKey); return diffCounts; } }
package cz.quinix.condroid.model; import java.io.Serializable; import java.util.Date; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import android.content.ContentValues; import cz.quinix.condroid.R; import cz.quinix.condroid.abstracts.DBInsertable; public class Annotation implements Serializable, DBInsertable { private static final long serialVersionUID = 29890241539328629L; private String pid; private String talker; private String title; private String length; private String mainType; private String additonalTypes = ""; private String programLine; private String annotation = ""; private Date startTime; private Date endTime; private String location; public static DateTimeFormatter dateISOFormatter = ISODateTimeFormat .dateTimeNoMillis(); public static DateTimeFormatter lameISOFormatter = DateTimeFormat .forPattern("yyyy-MM-dd'T'HH:mmZZ"); public static DateTimeFormatter dateSQLFormatter = DateTimeFormat .forPattern("yyyy-MM-dd HH:mm:ss").withZoneUTC(); private int lid; public Date getStartTime() { return startTime; } public Date getEndTime() { return endTime; } public void setStartTime(String startTime) { this.startTime = parseDate(startTime, dateISOFormatter); } public void setEndTime(String endTime) { this.endTime = parseDate(endTime, dateISOFormatter); } public void setSQLStartTime(String startTime) { this.startTime = parseDate(startTime, dateSQLFormatter); } public void setSQLEndTime(String endTime) { this.endTime = parseDate(endTime, dateSQLFormatter); } private Date parseDate(String date, DateTimeFormatter formatter) { if (date == null || date.trim().equals("")) return null; date = date.trim(); Date x = null; try { if(date.length() < 25 && formatter.equals(dateISOFormatter)) { date = date.substring(0, date.length()-6)+":00"+date.substring(date.length()-6); } x = formatter.parseDateTime(date).toDate(); } catch (IllegalArgumentException e) { //if (formatter.equals(dateISOFormatter)) //x = lameISOFormatter.parseDateTime(date).toDate(); //else throw e; } return x; } public void setAdditonalTypes(String additonalTypes) { this.additonalTypes = additonalTypes; } public String getPid() { return pid; } public String getAuthor() { return talker; } public String getTitle() { return title; } public String getLength() { return length; } public String getType() { return mainType; } public int getProgramIcon() { String type = this.mainType; if (type.equalsIgnoreCase("P")) { return R.drawable.lecture; } if (type.equalsIgnoreCase("B")) { return R.drawable.discussion; } if (type.equalsIgnoreCase("C")) { return R.drawable.theatre; } if (type.equalsIgnoreCase("D")) { return R.drawable.projection; } if (type.equalsIgnoreCase("F")) { return R.drawable.projection; } if (type.equalsIgnoreCase("G")) { return R.drawable.game; } if (type.equalsIgnoreCase("H")) { return R.drawable.music; } if (type.equalsIgnoreCase("Q")) { return R.drawable.game; } if (type.equalsIgnoreCase("W")) { return R.drawable.workshop; } return R.drawable.program_unknown; } /** * Use only during processing new XML! * * @return */ public String getProgramLine() { return programLine; } public String getAnnotation() { return annotation; } public void setPid(String pid) { this.pid = pid.trim(); } public void setAuthor(String talker) { this.talker = talker.trim(); } public void setTitle(String title) { this.title = title.trim(); } public void setLength(String length) { // this.length = length.trim(); } public void setType(String type) { String[] types = type.trim().split("\\+"); if (types.length > 0) { mainType = types[0].trim(); } if (types.length > 1) { for (int i = 1; i < types.length; i++) { additonalTypes += types[i] + "+"; } additonalTypes = (String) additonalTypes.subSequence(0, additonalTypes.length() - 1); // removes last + } } public void setProgramLine(String programLine) { this.programLine = programLine.trim(); } public void setAnnotation(String annotation) { this.annotation = annotation.trim(); } public ContentValues getContentValues() { if (startTime != null && endTime != null && startTime.after(endTime)) { endTime.setDate(endTime.getDate() + 1); } ContentValues ret = new ContentValues(); ret.put("pid", this.pid); ret.put("talker", talker); ret.put("title", title); ret.put("length", length); ret.put("mainType", mainType); ret.put("additionalTypes", additonalTypes); ret.put("lid", lid); ret.put("location", location); ret.put("annotation", annotation); if (startTime != null) { ret.put("startTime", dateSQLFormatter.print(startTime.getTime())); } if (endTime != null) { ret.put("endTime", dateSQLFormatter.print(endTime.getTime())); } return ret; } public void setLid(Integer integer) { lid = integer.intValue(); } public int getLid() { return lid; } public void setLocation(String nextText) { location = nextText; } public String getLocation() { return location; } public String[] getAdditionalTypes() { return additonalTypes.split("\\+"); } }
package org.jasig.cas.audit.spi; import org.aspectj.lang.JoinPoint; import org.jasig.cas.CentralAuthenticationService; import org.jasig.cas.authentication.Credential; import org.jasig.cas.ticket.InvalidTicketException; import org.jasig.cas.ticket.ServiceTicket; import org.jasig.cas.ticket.Ticket; import org.jasig.cas.ticket.TicketGrantingTicket; import org.jasig.cas.util.AopUtils; import org.jasig.cas.web.support.WebUtils; import org.jasig.inspektr.common.spi.PrincipalResolver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.validation.constraints.NotNull; /** * PrincipalResolver that can retrieve the username from either the Ticket or from the Credential. * * @author Scott Battaglia * @since 3.1.2 * */ @Component("auditablePrincipalResolver") public final class TicketOrCredentialPrincipalResolver implements PrincipalResolver { /** Logger instance. */ private static final Logger LOGGER = LoggerFactory.getLogger(TicketOrCredentialPrincipalResolver.class); @NotNull @Resource(name="centralAuthenticationService") private CentralAuthenticationService centralAuthenticationService; @Autowired(required = false) @Qualifier("principalIdProvider") private PrincipalIdProvider principalIdProvider = new DefaultPrincipalIdProvider(); private TicketOrCredentialPrincipalResolver() {} /** * Instantiates a new Ticket or credential principal resolver. * * @param centralAuthenticationService the central authentication service * @since 4.1.0 */ public TicketOrCredentialPrincipalResolver(final CentralAuthenticationService centralAuthenticationService) { this.centralAuthenticationService = centralAuthenticationService; } @Override public String resolveFrom(final JoinPoint joinPoint, final Object retVal) { return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint)); } @Override public String resolveFrom(final JoinPoint joinPoint, final Exception retVal) { return resolveFromInternal(AopUtils.unWrapJoinPoint(joinPoint)); } @Override public String resolve() { return UNKNOWN_USER; } /** * Resolve the principal from the join point given. * * @param joinPoint the join point * @return the principal id, or {@link PrincipalResolver#UNKNOWN_USER} */ protected String resolveFromInternal(final JoinPoint joinPoint) { final StringBuilder builder = new StringBuilder(); final Object arg1 = joinPoint.getArgs()[0]; if (arg1.getClass().isArray()) { final Object[] args1AsArray = (Object[]) arg1; for (final Object arg: args1AsArray) { builder.append(resolveArgument(arg)); } } else { builder.append(resolveArgument(arg1)); } return builder.toString(); } /** * Resolve the join point argument. * * @param arg1 the arg * @return the resolved string */ private String resolveArgument(final Object arg1) { LOGGER.debug("Resolving argument [{}] for audit", arg1.getClass().getSimpleName()); if (arg1 instanceof Credential) { return arg1.toString(); } else if (arg1 instanceof String) { try { final Ticket ticket = this.centralAuthenticationService.getTicket((String) arg1, Ticket.class); org.jasig.cas.authentication.Authentication casAuthentication = null; if (ticket instanceof ServiceTicket) { casAuthentication = ServiceTicket.class.cast(ticket).getGrantingTicket().getAuthentication(); } else if (ticket instanceof TicketGrantingTicket) { casAuthentication = TicketGrantingTicket.class.cast(ticket).getAuthentication(); } return this.principalIdProvider.getPrincipalIdFrom(casAuthentication); } catch (final InvalidTicketException e) { LOGGER.trace(e.getMessage(), e); } LOGGER.debug("Could not locate ticket [{}] in the registry", arg1); } else { return WebUtils.getAuthenticatedUsername(); } LOGGER.debug("Unable to determine the audit argument. Returning [{}]", UNKNOWN_USER); return UNKNOWN_USER; } /** * Default implementation that simply returns principal#id. */ public static class DefaultPrincipalIdProvider implements PrincipalIdProvider { @Override public String getPrincipalIdFrom(final org.jasig.cas.authentication.Authentication authentication) { return authentication.getPrincipal().getId(); } } }
package de.lmu.ifi.dbs.distance; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * TODO comment * @author Arthur Zimek (<a href="mailto:zimek@dbs.ifi.lmu.de">zimek@dbs.ifi.lmu.de</a>) */ public class BitDistance extends NumberDistance<BitDistance> { /** * Generated serial version UID */ private static final long serialVersionUID = 6514853467081717551L; /** * The bit value of this distance. */ private boolean bit; public BitDistance() { super(); } public BitDistance(boolean bit) { super(); this.bit = bit; } /** * * @see de.lmu.ifi.dbs.distance.NumberDistance#getDoubleValue() */ @Override public double getDoubleValue() { return bit ? 1 : 0; } /** * * @see de.lmu.ifi.dbs.distance.AbstractDistance#hashCode() */ @Override public int hashCode() { return this.isBit() ? 1231 : 1237; } /** * * @see de.lmu.ifi.dbs.distance.Distance#plus(de.lmu.ifi.dbs.distance.Distance) */ public BitDistance plus(BitDistance distance) { return new BitDistance(this.isBit() || distance.isBit()); } /** * * @see de.lmu.ifi.dbs.distance.Distance#minus(de.lmu.ifi.dbs.distance.Distance) */ public BitDistance minus(BitDistance distance) { return new BitDistance(this.isBit() ^ distance.isBit() ); } /** * * @see de.lmu.ifi.dbs.distance.Distance#externalizableSize() */ public int externalizableSize() { return 1; } /** * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(BitDistance o) { return ((Boolean) this.isBit()).compareTo(o.isBit()); } /** * * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ public void writeExternal(ObjectOutput out) throws IOException { out.writeBoolean(this.isBit()); } /** * * @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.bit = in.readBoolean(); } public boolean isBit() { return this.bit; } }
package de.lmu.ifi.dbs.elki.data; /** * RealVector is an abstract super class for all feature vectors having real numbers as values. * * @param <V> the concrete type of this RealVector * @param <N> the type of number, this RealVector consists of (i.e., a RealVector {@code v} of type {@code V} * and dimensionality {@code d} is an element of {@code N}<sup><code>d</code></sup>) * * @author Elke Achtert */ public abstract class RealVector<V extends RealVector<V,N>,N extends Number> extends NumberVector<V,N> { /** * Returns a new RealVector of N for the given values. * * @param values the values of the featureVector * @return a new FeatureVector of T for the given values */ public abstract V newInstance(double[] values); }
package edu.duke.cabig.c3pr.web.admin; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.map.HashedMap; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndViewDefiningException; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.util.WebUtils; import edu.duke.cabig.c3pr.dao.HealthcareSiteDao; import edu.duke.cabig.c3pr.dao.HealthcareSiteInvestigatorDao; import edu.duke.cabig.c3pr.dao.InvestigatorGroupDao; import edu.duke.cabig.c3pr.domain.Arm; import edu.duke.cabig.c3pr.domain.CoordinatingCenterStudyStatus; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.HealthcareSite; import edu.duke.cabig.c3pr.domain.HealthcareSiteInvestigator; import edu.duke.cabig.c3pr.domain.InvestigatorGroup; import edu.duke.cabig.c3pr.domain.SiteInvestigatorGroupAffiliation; import edu.duke.cabig.c3pr.domain.TreatmentEpoch; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.utils.StringUtils; import edu.duke.cabig.c3pr.utils.web.ControllerTools; import edu.duke.cabig.c3pr.utils.web.propertyeditors.CustomDaoEditor; import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.SimpleFormAjaxableController; import edu.duke.cabig.c3pr.web.beans.DefaultObjectPropertyReader; import gov.nih.nci.cabig.ctms.web.tabs.Flow; public class CreateInvestigatorGroupsController extends SimpleFormAjaxableController<HealthcareSite, HealthcareSiteDao>{ // private C3PRDefaultTabConfigurer c3PRDefaultTabConfigurer; // private Flow<InvestigatorGroupsCommand> flow; /*public CreateInvestigatorGroupsController() { super(); flow = new Flow<InvestigatorGroupsCommand>("Investigator Groups"); flow.addTab(new InvestigatorsGroupsTab<InvestigatorGroupsCommand>("Investigator Groups","Investigator Groups","admin/investigator_groups_create")); }*/ InvestigatorGroupDao investigatorGroupDao; HealthcareSiteDao healthcareSiteDao; private HealthcareSiteInvestigatorDao healthcareSiteInvestigatorDao; private Logger log = Logger.getLogger(CreateInvestigatorGroupsController.class); /*private InvestigatorGroupsValidator investigatorGroupsValidator; public void setInvestigatorGroupsValidator( InvestigatorGroupsValidator investigatorGroupsValidator) { this.investigatorGroupsValidator = investigatorGroupsValidator; }*/ public CreateInvestigatorGroupsController() { super(); } public HealthcareSiteInvestigatorDao getHealthcareSiteInvestigatorDao() { return healthcareSiteInvestigatorDao; } public void setHealthcareSiteInvestigatorDao( HealthcareSiteInvestigatorDao healthcareSiteInvestigatorDao) { this.healthcareSiteInvestigatorDao = healthcareSiteInvestigatorDao; } public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) { this.healthcareSiteDao = healthcareSiteDao; } public void setInvestigatorGroupDao(InvestigatorGroupDao investigatorGroupDao) { this.investigatorGroupDao = investigatorGroupDao; } @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(Date.class, ControllerTools.getDateEditor(true)); binder.registerCustomEditor(HealthcareSite.class, new CustomDaoEditor(healthcareSiteDao)); binder.registerCustomEditor(HealthcareSiteInvestigator.class, new CustomDaoEditor( healthcareSiteInvestigatorDao)); } @Override protected Map referenceData(HttpServletRequest request, Object command, Errors error) throws Exception { Map map=new HashMap(); InvestigatorGroupsCommand investigatorGroupsCommand=(InvestigatorGroupsCommand)command; if(investigatorGroupsCommand.getHealthcareSite()!=null){ if(investigatorGroupsCommand.getHealthcareSite().getId()!=null && request.getParameter("groupId")!="" && request.getParameter("groupId")!=null){ for(int i=0 ; i<investigatorGroupsCommand.getHealthcareSite().getInvestigatorGroups().size() ; i++){ if(investigatorGroupsCommand.getHealthcareSite().getInvestigatorGroups().get(i).getId().equals(Integer.parseInt(request.getParameter("groupId")))){ map.put("groupIndex", i); map.put("newGroup", new Boolean(false)); return map; } } } map.put("groupIndex", investigatorGroupsCommand.getHealthcareSite().getInvestigatorGroups().size()); map.put("newGroup", new Boolean(true)); } return map; } @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { //this.c3PRDefaultTabConfigurer.injectDependencies(this.getPage()); return super.formBackingObject(request); } @Override protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { InvestigatorGroupsCommand investigatorGroupsCommand=(InvestigatorGroupsCommand)command; int id; if(WebUtils.hasSubmitParameter(request, "groupId")){ id=Integer.parseInt(request.getParameter("groupId")); log.debug("groupId:"+id); if (errors.hasErrors()){ response.getWriter().println(id); /*@Override protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception { int id; super.onBindAndValidate(request, command, errors); if(((InvestigatorGroupsCommand)command).getHealthcareSite()!=null){ if(((InvestigatorGroupsCommand)command).getHealthcareSite().getId()!=null && WebUtils.hasSubmitParameter(request, "groupId")){ for(int i=0 ; i<((InvestigatorGroupsCommand)command).getHealthcareSite().getInvestigatorGroups().size() ; i++){ if(((InvestigatorGroupsCommand)command).getHealthcareSite().getInvestigatorGroups().get(i).getId().equals(Integer.parseInt(request.getParameter("groupId")))){ InvestigatorGroup investigatorGroup = ((InvestigatorGroupsCommand)command).getHealthcareSite().getInvestigatorGroups().get(i); validateInvestigatorGroup(((InvestigatorGroupsCommand)command).getHealthcareSite(), investigatorGroup, errors); validateSiteInvestigatorGroupAffiliations(((InvestigatorGroupsCommand)command).getHealthcareSite().getInvestigatorGroups().get(i), errors); } } } } }*/ public void validateInvestigatorGroup(HealthcareSite healthcareSite, InvestigatorGroup investigatorGroup, Errors errors) { if ((investigatorGroup.getStartDate()!=null && investigatorGroup.getEndDate()!=null && investigatorGroup.getStartDate().after(investigatorGroup.getEndDate()))) { /* public C3PRDefaultTabConfigurer getC3PRDefaultTabConfigurer() { return c3PRDefaultTabConfigurer; } @Required public void setC3PRDefaultTabConfigurer( C3PRDefaultTabConfigurer c3PRDefaultTabConfigurer) { this.c3PRDefaultTabConfigurer = c3PRDefaultTabConfigurer; }*/ @Override protected HealthcareSiteDao getDao() { return healthcareSiteDao; } @Override protected HealthcareSite getPrimaryDomainObject(HealthcareSite command) { return command; } /*public Flow<InvestigatorGroupsCommand> getFlow() { return flow; } public void setFlow(Flow<InvestigatorGroupsCommand> flow) { this.flow = flow; }*/ }
package edu.duke.cabig.c3pr.web.registration; import java.util.HashMap; import java.util.Map; import edu.duke.cabig.c3pr.domain.CompanionStudyAssociation; import edu.duke.cabig.c3pr.domain.RegistrationDataEntryStatus; import edu.duke.cabig.c3pr.domain.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.ScheduledEpochDataEntryStatus; import edu.duke.cabig.c3pr.domain.ScheduledEpochWorkFlowStatus; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.service.StudySubjectService; import edu.duke.cabig.c3pr.tools.Configuration; import edu.duke.cabig.c3pr.utils.StringUtils; import edu.duke.cabig.c3pr.web.ajax.StudySubjectXMLFileImportAjaxFacade; public class RegistrationControllerUtils { private StudySubjectService studySubjectService; private Configuration configuration; public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public void setStudySubjectService(StudySubjectService studySubjectService) { this.studySubjectService = studySubjectService; } public boolean isRegisterableOnPage(StudySubject studySubject) { return studySubject.isDataEntryComplete() && !studySubject.getScheduledEpoch().getRequiresRandomization() && !studySubjectService.requiresExternalApprovalForRegistration(studySubject) && (studySubject.getScheduledEpoch().getEpoch().isEnrolling()?registrableStandalone(studySubject):true); } public static boolean registrableStandalone(StudySubject studySubject){ return studySubject.getParentStudySubject()==null && studySubject.getStudySite().getStudy().getCompanionStudyAssociations().size()==0; } public Map buildMap(StudySubject studySubject) { Map map = new HashMap(); boolean reg_unregistered = false; boolean reg_registered = false; boolean reg_unapproved = false; boolean reg_pending = false; boolean reg_reserved = false; boolean reg_disapproved = false; boolean reg_nonenrolled = false; boolean reg_unrandomized = false; boolean epoch_unapproved = false; boolean epoch_pending = false; boolean epoch_approved = false; boolean epoch_nonenrolled = false; boolean epoch_unrandomized = false; boolean epoch_disapproved = false; boolean newRegistration = true; String armAssigned = ""; String armAssignedLabel = ""; if ((studySubject.getScheduledEpoch()).getScheduledArm() != null) { if (studySubject.getStudySite().getStudy().getBlindedIndicator()) { armAssigned = (studySubject.getScheduledEpoch()) .getScheduledArm().getKitNumber(); armAssignedLabel = "Kit Assigned"; } else if ((studySubject.getScheduledEpoch()).getScheduledArm() .getArm() != null) { armAssigned = (studySubject.getScheduledEpoch()) .getScheduledArm().getArm().getName(); armAssignedLabel = "Arm Assigned"; } } int count = 0; for (ScheduledEpoch scheduledEpoch : studySubject.getScheduledEpochs()) { count++; } if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) { count } else if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() == ScheduledEpochWorkFlowStatus.APPROVED) { reg_nonenrolled = true; epoch_nonenrolled = true; } if (studySubject.getScheduledEpochs().size() > 1) newRegistration = false; if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.COMPLETE && studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.COMPLETE && studySubject.getScheduledEpoch().getRequiresRandomization() && studySubject.getScheduledEpoch().getScEpochWorkflowStatus() == ScheduledEpochWorkFlowStatus.UNAPPROVED) { reg_unrandomized = true; epoch_unrandomized = true; } switch (studySubject.getRegWorkflowStatus()) { case UNREGISTERED: reg_unregistered = true; break; case REGISTERED: reg_registered = true; break; case PENDING: reg_pending = true; break; case RESERVED: reg_reserved = true; break; case DISAPPROVED: reg_disapproved = true; break; } switch (studySubject.getScheduledEpoch().getScEpochWorkflowStatus()) { case UNAPPROVED: epoch_unapproved = true; break; case APPROVED: epoch_approved = true; break; case PENDING: epoch_pending = true; break; case DISAPPROVED: epoch_disapproved = true; break; } map.put("reg_unregistered", reg_unregistered); map.put("reg_registered", reg_registered); map.put("reg_unapproved", reg_unapproved); map.put("reg_pending", reg_pending); map.put("reg_reserved", reg_reserved); map.put("reg_disapproved", reg_disapproved); map.put("epoch_unapproved", epoch_unapproved); map.put("epoch_pending", epoch_pending); map.put("epoch_approved", epoch_approved); map.put("epoch_disapproved", epoch_disapproved); map.put("newRegistration", newRegistration); map.put("armAssigned", armAssigned); map.put("armAssignedLabel", armAssignedLabel); map.put("reg_nonenrolled", reg_nonenrolled); map.put("reg_unrandomized", reg_unrandomized); map.put("epoch_nonenrolled", epoch_nonenrolled); map.put("epoch_unrandomized", epoch_unrandomized); map.put("hasParent", studySubject.getParentStudySubject()!=null); map.put("hasCompanions", studySubject.getStudySite().getStudy().getCompanionStudyAssociations().size()>0); map.put("registerableWithCompanions", registerableAsorWithCompanion(studySubject)); map.put("isDataEntryComplete", studySubject.isDataEntryComplete()); return map; } public void addAppUrls(Map<String, Object> map) { if (this.configuration.get(this.configuration.AUTHENTICATION_MODEL) .equals("webSSO")) { map.put("hotlinkEnable", new Boolean(true)); if (!StringUtils.getBlankIfNull( this.configuration.get(this.configuration.PSC_BASE_URL)) .equalsIgnoreCase("")) { map.put("pscBaseUrl", this.configuration .get(this.configuration.PSC_BASE_URL)); } if (!StringUtils.getBlankIfNull( this.configuration.get(this.configuration.CAAERS_BASE_URL)) .equalsIgnoreCase("")) { map.put("caaersBaseUrl", this.configuration .get(this.configuration.CAAERS_BASE_URL)); } if (!StringUtils.getBlankIfNull( this.configuration.get(this.configuration.C3D_BASE_URL)) .equalsIgnoreCase("")) { map.put("c3dBaseUrl", this.configuration .get(this.configuration.C3D_BASE_URL)); } } else { map.put("hotlinkEnable", new Boolean(false)); } } public boolean registerableAsorWithCompanion(StudySubject studySubject) { if(studySubject.getParentStudySubject()!=null) return false; if (studySubject.getStudySite().getStudy() .getCompanionStudyAssociations().size() > 0) { Map<Integer, Object> compIds = new HashMap<Integer, Object>(); for (CompanionStudyAssociation companionStudyAssociation : studySubject .getStudySite().getStudy().getCompanionStudyAssociations()) { if (companionStudyAssociation.getMandatoryIndicator()) { compIds.put(companionStudyAssociation.getCompanionStudy() .getId(), new Object()); } } for (StudySubject stSubject : studySubject.getChildStudySubjects()) { if (stSubject.getRegWorkflowStatus() != RegistrationWorkFlowStatus.READY_FOR_REGISTRATION) { return false; } compIds.remove(stSubject.getStudySite().getStudy().getId()); } if (compIds.size() > 0) return false; } return true; } public void updateStatusForEmbeddedStudySubjet(StudySubject studySubject){ if(studySubject.getParentStudySubject()!=null && studySubject.isDataEntryComplete()){ studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.READY_FOR_REGISTRATION); studySubject.getScheduledEpoch().setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.APPROVED); } } }
package org.openforis.collect.earth.app.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.openforis.collect.earth.app.CollectEarthUtils; import org.openforis.collect.earth.app.EarthConstants; import org.openforis.collect.earth.app.EarthConstants.CollectDBDriver; import org.openforis.collect.earth.app.EarthConstants.OperationMode; import org.openforis.collect.earth.app.desktop.EarthApp; import org.openforis.collect.earth.app.service.AnalysisSaikuService; import org.openforis.collect.earth.app.service.EarthProjectsService; import org.openforis.collect.earth.app.service.LocalPropertiesService; import org.openforis.collect.earth.app.service.LocalPropertiesService.EarthProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Alfonso Sanchez-Paus Diaz * */ public class OptionWizard extends JDialog { private static final ComboBoxItem COMBO_BOX_ITEM_CENTRAL_POINT = new ComboBoxItem(1, Messages.getString("OptionWizard.54")); private static final ComboBoxItem COMBO_BOX_ITEM_SQUARE = new ComboBoxItem(0, Messages.getString("OptionWizard.53")); private static final long serialVersionUID = -6760020609229102842L; private final HashMap<Enum<?>, JComponent[]> propertyToComponent = new HashMap<Enum<?>, JComponent[]>(); private final Logger logger = LoggerFactory.getLogger(this.getClass()); JPanel postgresPanel; JPanel sqlitePanel; LocalPropertiesService localPropertiesService; String backupFolder; private AnalysisSaikuService saikuService; private EarthProjectsService projectsService; private boolean restartRequired; private String oldSelectedDistance; public OptionWizard(JFrame frame, LocalPropertiesService localPropertiesService, EarthProjectsService projectsService, String backupFolder, AnalysisSaikuService saikuService) { super(frame, Messages.getString("OptionWizard.0")); //$NON-NLS-1$ this.localPropertiesService = localPropertiesService; this.projectsService = projectsService; this.backupFolder = backupFolder; this.saikuService = saikuService; this.setLocationRelativeTo(null); this.setSize(new Dimension(600, 620)); this.setModal(true); this.setResizable(false); initilizeInputs(); buildMainPane(); centreWindow(); } private void centreWindow() { Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); int x = (int) ((dimension.getWidth() - getWidth()) / 2); int y = (int) ((dimension.getHeight() - getHeight()) / 2); setLocation(x, y); } private void buildMainPane() { final JPanel panel = new JPanel(new BorderLayout()); panel.add(getOptionTabs(), BorderLayout.CENTER); final JPanel buttonPanel = new JPanel(); buttonPanel.add(getApplyChangesButton()); buttonPanel.add(getCancelButton()); panel.add(buttonPanel, BorderLayout.PAGE_END); this.add(panel); } public void enableContainer(Container container, boolean enable) { final Component[] components = container.getComponents(); for (final Component component : components) { component.setEnabled(enable); if (component instanceof Container) { enableContainer((Container) component, enable); } } } private JComponent getAdvancedOptionsPanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridwidth = 2; panel.add(propertyToComponent.get(EarthProperty.OPEN_EARTH_ENGINE)[0], constraints); constraints.gridy++; panel.add(propertyToComponent.get(EarthProperty.OPEN_TIMELAPSE)[0], constraints); constraints.gridy++; panel.add(propertyToComponent.get(EarthProperty.OPEN_BING_MAPS)[0], constraints); constraints.gridy++; panel.add(propertyToComponent.get(EarthProperty.OPEN_YANDEX_MAPS)[0], constraints); constraints.gridy++; panel.add(propertyToComponent.get(EarthProperty.OPEN_STREET_VIEW)[0], constraints); // Removed Here Maps temporarily // constraints.gridy++; // panel.add(propertyToComponent.get(EarthProperty.OPEN_HERE_MAPS)[0], constraints); constraints.gridy++; panel.add(propertyToComponent.get(EarthProperty.OPEN_GEE_PLAYGROUND)[0], constraints); final JPanel browserChooserPanel = new JPanel(); final Border browserBorder = new TitledBorder(new BevelBorder(BevelBorder.LOWERED), Messages.getString("OptionWizard.1")); //$NON-NLS-1$ browserChooserPanel.setBorder(browserBorder); final ButtonGroup browserChooser = new ButtonGroup(); final JComponent[] browsers = propertyToComponent.get(EarthProperty.BROWSER_TO_USE); for (final JComponent broserRadioButton : browsers) { browserChooserPanel.add(broserRadioButton); browserChooser.add((AbstractButton) broserRadioButton); } constraints.gridy++; panel.add(browserChooserPanel, constraints); constraints.gridy++; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.FIREFOX_BINARY_PATH)[0], constraints); constraints.gridy++; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.CHROME_BINARY_PATH)[0], constraints); constraints.gridy++; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.SAIKU_SERVER_FOLDER)[0], constraints); return panel; } private Component getApplyChangesButton() { final JButton applyChanges = new JButton(Messages.getString("OptionWizard.15")); //$NON-NLS-1$ applyChanges.addActionListener(new ApplyOptionChangesListener(this, localPropertiesService, propertyToComponent){ @Override protected void applyProperties() { savePropertyValues(); if(restartRequired ){ restartEarth(); }else{ new Thread(){ public void run() { // Only regenerate KML and reload try { SwingUtilities.invokeAndWait( new Runnable() { @Override public void run() { CollectEarthWindow.startWaiting(OptionWizard.this); } }); EarthApp.loadKmlInGoogleEarth(true); SwingUtilities.invokeAndWait( new Runnable() { @Override public void run() { CollectEarthWindow.endWaiting(OptionWizard.this); OptionWizard.this.closeDialog(); } }); } catch (Exception e) { logger.error("Error loading the KML",e); try { EarthApp.loadKmlInGoogleEarth(true); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }; }.start(); } } }); return applyChanges; } protected void closeDialog() { this.dispose(); } private Component getCancelButton() { final JButton cancelButton = new JButton(Messages.getString("OptionWizard.24")); //$NON-NLS-1$ cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { OptionWizard.this.dispose(); } }); return cancelButton; } private JComponent getOperationModePanel() { final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; final JPanel typeOfUsePanel = new JPanel(new GridBagLayout()); final Border border = new TitledBorder(new BevelBorder(BevelBorder.LOWERED), Messages.getString("OptionWizard.2")); //$NON-NLS-1$ typeOfUsePanel.setBorder(border); JPanel serverPanel = getServerPanel(); typeOfUsePanel.add(serverPanel, constraints); return typeOfUsePanel; } public void enableDBOptions(boolean isPostgreDb) { enableContainer(postgresPanel, isPostgreDb); enableContainer( sqlitePanel, !isPostgreDb); } private ActionListener getDbTypeListener() { return new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final JRadioButton theJRB = (JRadioButton) e.getSource(); boolean isPostgreDb = theJRB.getName().equals(CollectDBDriver.POSTGRESQL.name() ); enableDBOptions( isPostgreDb ); } }; } private JTabbedPane getOptionTabs() { final JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.setSize(550, 300); final JComponent panel1 = getSampleDataPanel(); tabbedPane.addTab(Messages.getString("OptionWizard.31"), panel1); //$NON-NLS-1$ final JComponent panel2 = getPlotOptionsPanel(); tabbedPane.addTab(Messages.getString("OptionWizard.32"), panel2); //$NON-NLS-1$ final JComponent panel3 = getSurveyDefinitonPanel(); tabbedPane.addTab(Messages.getString("OptionWizard.33"), panel3); //$NON-NLS-1$ final JComponent panel4 = getAdvancedOptionsPanel(); tabbedPane.addTab(Messages.getString("OptionWizard.34"), panel4); //$NON-NLS-1$ final JComponent panel5 = getOperationModePanelScroll(); tabbedPane.addTab(Messages.getString("OptionWizard.25"), panel5); //$NON-NLS-1$ final JComponent panel6 = getProjectsPanelScroll(); tabbedPane.addTab(Messages.getString("OptionWizard.40"), panel6); //$NON-NLS-1$ return tabbedPane; } private JComponent getProjectsPanelScroll() { final JComponent projectsPanel = getProjectsPanel(); JScrollPane scroll = new JScrollPane(projectsPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); return scroll; } private JComponent getProjectsPanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.fill = GridBagConstraints.BOTH; JButton importNewButton = new JButton( Messages.getString("OptionWizard.41") ); //$NON-NLS-1$ importNewButton.addActionListener( new ApplyOptionChangesListener(this, localPropertiesService) { @Override protected void applyProperties() { final File[] selectedProjectFile = JFileChooserExistsAware.getFileChooserResults( DataFormat.PROJECT_DEFINITION_FILE, false, false, null,localPropertiesService, (JFrame) OptionWizard.this.getParent()); if( selectedProjectFile.length == 1 ){ try { projectsService.loadCompressedProjectFile( selectedProjectFile[0]); restartEarth(); } catch (Exception e1) { JOptionPane.showMessageDialog( OptionWizard.this, e1.getMessage(), Messages.getString("OptionWizard.51"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ logger.error("Error importing project file " + selectedProjectFile[0].getAbsolutePath(), e1); //$NON-NLS-1$ } } } }); panel.add(importNewButton, constraints); final JPanel typeOfDbPanel = new JPanel(new GridBagLayout()); final Border border = new TitledBorder(new BevelBorder(BevelBorder.RAISED), Messages.getString("OptionWizard.57")); //$NON-NLS-1$ typeOfDbPanel.setBorder(border); constraints.gridx = 0; constraints.gridy = 1; panel.add(typeOfDbPanel, constraints); List<String> listOfProjectsByName = new ArrayList<String>(); listOfProjectsByName.addAll(projectsService.getProjectList().keySet()); Collections.sort(listOfProjectsByName); final JList<String> listOfProjects = new JList<String>( listOfProjectsByName.toArray(new String[0]) ); //data has type Object[] listOfProjects.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); listOfProjects.setLayoutOrientation(JList.VERTICAL); listOfProjects.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(listOfProjects); listScroller.setPreferredSize(new Dimension(250, 300)); constraints.gridy = 0; constraints.gridx = GridBagConstraints.RELATIVE; typeOfDbPanel.add(listScroller, constraints); final JButton openProject = new JButton(Messages.getString("OptionWizard.56")); //$NON-NLS-1$ openProject.setEnabled(false); openProject.addActionListener( new ApplyOptionChangesListener(this, localPropertiesService) { @Override protected void applyProperties() { File projectFolder = projectsService.getProjectList().get( listOfProjects.getSelectedValue()); try { projectsService.loadProjectInFolder( projectFolder ); restartEarth(); } catch (Exception e1) { JOptionPane.showMessageDialog( OptionWizard.this, e1.getMessage(), Messages.getString("OptionWizard.55"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ logger.error("Error importing project folder " + projectFolder.getAbsolutePath(), e1); //$NON-NLS-1$ } } }); listOfProjects.addListSelectionListener( new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { openProject.setEnabled( listOfProjects.getSelectedValue() != null ); } }); typeOfDbPanel.add(openProject); return panel; } private JScrollPane getOperationModePanelScroll() { final JComponent operationModePanel = getOperationModePanel(); JScrollPane scroll = new JScrollPane(operationModePanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); return scroll; } private JComponent getPlotOptionsPanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.fill = GridBagConstraints.HORIZONTAL; JLabel label = new JLabel(Messages.getString("OptionWizard.35")); //$NON-NLS-1$ panel.add(label, constraints); constraints.gridx = 1; JComboBox numberPoints = (JComboBox) propertyToComponent.get(EarthProperty.NUMBER_OF_SAMPLING_POINTS_IN_PLOT)[0]; panel.add(numberPoints, constraints); constraints.gridx = 0; constraints.gridy = 1; label = new JLabel(Messages.getString("OptionWizard.36")); //$NON-NLS-1$ panel.add(label, constraints); constraints.gridx = 1; JComboBox distanceBetweenPoints = (JComboBox) propertyToComponent.get(EarthProperty.DISTANCE_BETWEEN_SAMPLE_POINTS)[0]; panel.add(new JScrollPane(distanceBetweenPoints), constraints); constraints.gridx = 0; constraints.gridy = 2; label = new JLabel(Messages.getString("OptionWizard.37")); //$NON-NLS-1$ panel.add(label, constraints); constraints.gridx = 1; JComboBox distanceToFrame = (JComboBox) propertyToComponent.get(EarthProperty.DISTANCE_TO_PLOT_BOUNDARIES)[0]; panel.add(new JScrollPane(distanceToFrame), constraints); constraints.gridx = 0; constraints.gridy = 3; label = new JLabel(Messages.getString("OptionWizard.95") ); //$NON-NLS-1$ panel.add(label, constraints); constraints.gridx = 1; JComboBox dotsSide = (JComboBox) propertyToComponent.get(EarthProperty.INNER_SUBPLOT_SIDE)[0]; panel.add(new JScrollPane(dotsSide), constraints); constraints.gridx = 0; constraints.gridy = 4; label = new JLabel( "Area (hectares)" ); panel.add(label, constraints); constraints.gridx = 1; JLabel area = new JLabel( calculateArea( numberPoints, distanceBetweenPoints, distanceToFrame, dotsSide) ); panel.add(new JScrollPane(area), constraints); ActionListener calculateAreas = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { area.setText( calculateArea( numberPoints, distanceBetweenPoints, distanceToFrame, dotsSide ) ); } }; numberPoints.addActionListener(calculateAreas); distanceBetweenPoints.addActionListener(calculateAreas); distanceToFrame.addActionListener(calculateAreas); return panel; } private String calculateArea(JComboBox numberOfPoints, JComboBox distanceBetweenPoints, JComboBox distanceToFrame, JComboBox dotsSide) { double side = 0; try{ int numberOfPointsI = ((ComboBoxItem)numberOfPoints.getSelectedItem() ).getNumberOfPoints(); int distanceBetweenPointsI = Integer.parseInt( (String) distanceBetweenPoints.getSelectedItem() ) ; int distanceToFrameI = Integer.parseInt( (String) distanceToFrame.getSelectedItem() ) ; if( numberOfPointsI==0 || numberOfPointsI==1){ side = 2d* distanceToFrameI; if(oldSelectedDistance == null ){ oldSelectedDistance = (String) distanceBetweenPoints.getSelectedItem(); distanceBetweenPoints.setEnabled(false); } distanceBetweenPoints.setSelectedItem("0"); if( numberOfPointsI == 0 ){ dotsSide.setEnabled(false); }else if( numberOfPointsI == 1 ){ dotsSide.setEnabled(true); } }else{ if( oldSelectedDistance!=null ){ distanceBetweenPoints.setSelectedItem( oldSelectedDistance ); oldSelectedDistance = null; } distanceBetweenPoints.setEnabled(true); distanceToFrame.setEnabled( true ); dotsSide.setEnabled(true); double pointsByLines = Math.sqrt( numberOfPointsI ) ; side = 2d * distanceToFrameI + ( pointsByLines - 1 ) * distanceBetweenPointsI; } }catch(RuntimeException e){ logger.error("Error calculating area of the plot", e); } DecimalFormat df = new DecimalFormat(" return df.format( side*side / 10000d ); } private JPanel getPostgreSqlPanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; final Border border = new TitledBorder(new BevelBorder(BevelBorder.RAISED), Messages.getString("OptionWizard.6")); //$NON-NLS-1$ panel.setBorder(border); JLabel label = new JLabel(Messages.getString("OptionWizard.7")); //$NON-NLS-1$ constraints.gridx = 0; panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.DB_USERNAME)[0], constraints); constraints.gridy++; label = new JLabel(Messages.getString("OptionWizard.8")); //$NON-NLS-1$ constraints.gridx = 0; panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.DB_PASSWORD)[0], constraints); constraints.gridy++; label = new JLabel(Messages.getString("OptionWizard.9")); //$NON-NLS-1$ constraints.gridx = 0; panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.DB_NAME)[0], constraints); constraints.gridy++; label = new JLabel(Messages.getString("OptionWizard.26")); //$NON-NLS-1$ constraints.gridx = 0; panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.DB_HOST)[0], constraints); constraints.gridy++; label = new JLabel(Messages.getString("OptionWizard.29")); //$NON-NLS-1$ constraints.gridx = 0; panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.DB_PORT)[0], constraints); constraints.gridx = 2; panel.add( new JLabel ("Default: 5432"), constraints); constraints.gridy++; constraints.gridx = 1; JButton button = new JButton("Test Connection"); //$NON-NLS-1$ button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String host = ( (JTextField)(propertyToComponent.get(EarthProperty.DB_HOST)[0]) ).getText(); String port = ( (JTextField)(propertyToComponent.get(EarthProperty.DB_PORT)[0]) ).getText(); String dbName = ( (JTextField)(propertyToComponent.get(EarthProperty.DB_NAME)[0]) ).getText(); String username = ( (JTextField)(propertyToComponent.get(EarthProperty.DB_USERNAME)[0]) ).getText(); String password = ( (JTextField)(propertyToComponent.get(EarthProperty.DB_PASSWORD)[0]) ).getText(); String message = CollectEarthUtils.testPostgreSQLConnection( host, port, dbName, username, password); JOptionPane.showMessageDialog(OptionWizard.this.getOwner(), message , "PostgreSQL Connection test", JOptionPane.INFORMATION_MESSAGE); } }); panel.add(button, constraints); return panel; } private JPanel getSqlLitePanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; final Border border = new TitledBorder(new BevelBorder(BevelBorder.RAISED), Messages.getString("OptionWizard.30")); //$NON-NLS-1$ panel.setBorder(border); panel.add(propertyToComponent.get(EarthProperty.AUTOMATIC_BACKUP)[0], constraints); constraints.gridx++; panel.add(getOpenBackupFolderButton() ); return panel; } private JComponent getSampleDataPanel() { final JPlotCsvTable samplePlots = new JPlotCsvTable( localPropertiesService.getValue(EarthProperty.CSV_KEY) ); final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; final JFilePicker refreshTableOnFileChange = getFilePickerSamplePlots(samplePlots); panel.add(refreshTableOnFileChange, constraints); samplePlots.setFillsViewportHeight(true); constraints.gridy = 1; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.gridheight = GridBagConstraints.REMAINDER; samplePlots.setPreferredScrollableViewportSize(samplePlots.getPreferredSize()); panel.add(new JScrollPane(samplePlots, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), constraints); return panel; } private JFilePicker getFilePickerSamplePlots(final JPlotCsvTable samplePlots) { final JFilePicker refreshTableOnFileChange = (JFilePicker) (propertyToComponent.get(EarthProperty.CSV_KEY)[0]); refreshTableOnFileChange.addChangeListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { refreshTable(); } @Override public void insertUpdate(DocumentEvent e) { refreshTable(); } @Override public void removeUpdate(DocumentEvent e) { refreshTable(); } private void refreshTable() { samplePlots.refreshTable(refreshTableOnFileChange.getSelectedFilePath()); } }); return refreshTableOnFileChange; } private JPanel getServerPanel() { final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; final JPanel typeOfDbPanel = new JPanel(new GridBagLayout()); final Border border = new TitledBorder(new BevelBorder(BevelBorder.RAISED), Messages.getString("OptionWizard.3")); //$NON-NLS-1$ typeOfDbPanel.setBorder(border); JLabel label = new JLabel(Messages.getString("OptionWizard.4") + CollectEarthUtils.getComputerIp()); //$NON-NLS-1$ typeOfDbPanel.add(label, constraints); constraints.gridy++; label = new JLabel(Messages.getString("OptionWizard.5")); //$NON-NLS-1$ constraints.gridx = 0; typeOfDbPanel.add(label, constraints); constraints.gridx = 1; typeOfDbPanel.add(propertyToComponent.get(EarthProperty.HOST_PORT_KEY)[0], constraints); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.gridy++; constraints.gridx = 0; final ButtonGroup bg = new ButtonGroup(); final JComponent[] dbTypes = propertyToComponent.get(EarthProperty.DB_DRIVER); postgresPanel = getPostgreSqlPanel(); sqlitePanel = getSqlLitePanel(); boolean usingPostgreSQL = localPropertiesService.getCollectDBDriver().equals(CollectDBDriver.POSTGRESQL); enableDBOptions( usingPostgreSQL ); for (final JComponent typeRadioButton : dbTypes) { final JRadioButton dbTypeButton = (JRadioButton) typeRadioButton; bg.add(dbTypeButton); typeOfDbPanel.add(dbTypeButton, constraints); constraints.gridy++; dbTypeButton.addActionListener(getDbTypeListener()); if (dbTypeButton.getName().equals(EarthConstants.CollectDBDriver.POSTGRESQL.name() ) ) { typeOfDbPanel.add(postgresPanel, constraints); constraints.gridy++; }else{ typeOfDbPanel.add(sqlitePanel, constraints); constraints.gridy++; } } return typeOfDbPanel; } private Component getOpenBackupFolderButton() { AbstractAction backupAction = new AbstractAction(Messages.getString("OptionWizard.10") ){ //$NON-NLS-1$ private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { try { CollectEarthUtils.openFolderInExplorer( backupFolder ); } catch (final IOException e1) { logger.error("Error when opening the explorer window to visualize backups", e1); //$NON-NLS-1$ } } }; return new JButton( backupAction ); } private JComponent getSurveyDefinitonPanel() { final JPanel panel = new JPanel(new GridBagLayout()); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.anchor = GridBagConstraints.LINE_START; constraints.insets = new Insets(5, 5, 5, 5); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = 2; panel.add(propertyToComponent.get(EarthProperty.OPEN_BALLOON_IN_BROWSER)[0], constraints); constraints.gridy++; constraints.gridwidth = 1; final JLabel label = new JLabel(Messages.getString("OptionWizard.43")); //$NON-NLS-1$ panel.add(label, constraints); constraints.gridx = 1; panel.add(propertyToComponent.get(EarthProperty.SURVEY_NAME)[0], constraints); constraints.gridy++; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.KML_TEMPLATE_KEY)[0], constraints); constraints.gridy++; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.BALLOON_TEMPLATE_KEY)[0], constraints); constraints.gridy++; constraints.gridx = 0; panel.add(propertyToComponent.get(EarthProperty.METADATA_FILE)[0], constraints); return panel; } private void initilizeInputs() { final JCheckBox backupCheckbox = new JCheckBox(Messages.getString("OptionWizard.44")); //$NON-NLS-1$ backupCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.AUTOMATIC_BACKUP))); propertyToComponent.put(EarthProperty.AUTOMATIC_BACKUP, new JComponent[] { backupCheckbox }); final JCheckBox openEarthEngineCheckbox = new JCheckBox(Messages.getString("OptionWizard.45")); //$NON-NLS-1$ openEarthEngineCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_EARTH_ENGINE))); propertyToComponent.put(EarthProperty.OPEN_EARTH_ENGINE, new JComponent[] { openEarthEngineCheckbox }); final JCheckBox openTimelapseCheckbox = new JCheckBox(Messages.getString("OptionWizard.46")); //$NON-NLS-1$ openTimelapseCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_TIMELAPSE))); propertyToComponent.put(EarthProperty.OPEN_TIMELAPSE, new JComponent[] { openTimelapseCheckbox }); final JCheckBox openBingCheckbox = new JCheckBox(Messages.getString("OptionWizard.47")); //$NON-NLS-1$ openBingCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_BING_MAPS))); propertyToComponent.put(EarthProperty.OPEN_BING_MAPS, new JComponent[] { openBingCheckbox }); final JCheckBox openYandexCheckbox = new JCheckBox("Open Yandex maps for the plot area"); openYandexCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_YANDEX_MAPS))); propertyToComponent.put(EarthProperty.OPEN_YANDEX_MAPS, new JComponent[] { openYandexCheckbox }); final JCheckBox openStreetViewCheckbox = new JCheckBox("Open Street View"); openStreetViewCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_STREET_VIEW))); propertyToComponent.put(EarthProperty.OPEN_STREET_VIEW, new JComponent[] { openStreetViewCheckbox }); final JCheckBox openHereCheckbox = new JCheckBox(Messages.getString("OptionWizard.59")); //$NON-NLS-1$ openHereCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_HERE_MAPS))); propertyToComponent.put(EarthProperty.OPEN_HERE_MAPS, new JComponent[] { openHereCheckbox }); final JCheckBox openGeePlaygroundCheckbox = new JCheckBox(Messages.getString("OptionWizard.58")); //$NON-NLS-1$ openGeePlaygroundCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_GEE_PLAYGROUND))); propertyToComponent.put(EarthProperty.OPEN_GEE_PLAYGROUND, new JComponent[] { openGeePlaygroundCheckbox }); final JCheckBox openInSeparateWindowCheckbox = new JCheckBox(Messages.getString("OptionWizard.48")); //$NON-NLS-1$ openInSeparateWindowCheckbox.setSelected(Boolean.parseBoolean(localPropertiesService.getValue(EarthProperty.OPEN_BALLOON_IN_BROWSER))); propertyToComponent.put(EarthProperty.OPEN_BALLOON_IN_BROWSER, new JComponent[] { openInSeparateWindowCheckbox }); final JFilePicker csvWithPlotData = new JFilePicker( Messages.getString("OptionWizard.49"), localPropertiesService.getValue(EarthProperty.CSV_KEY), //$NON-NLS-1$ Messages.getString("OptionWizard.50")); //$NON-NLS-1$ csvWithPlotData.setMode(JFilePicker.MODE_OPEN); csvWithPlotData.addFileTypeFilter(".csv,.ced", Messages.getString("OptionWizard.52"), true); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.CSV_KEY, new JComponent[] { csvWithPlotData }); final JComboBox<ComboBoxItem> comboNumberOfPoints = new JComboBox<ComboBoxItem>( new ComboBoxItem[] { COMBO_BOX_ITEM_SQUARE, COMBO_BOX_ITEM_CENTRAL_POINT, new ComboBoxItem(4, "2x2"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ new ComboBoxItem(9, "3x3"), new ComboBoxItem(16, "4x4"), new ComboBoxItem(25, "5x5"), new ComboBoxItem(36, "6x6"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ new ComboBoxItem(49, "7x7") }); //$NON-NLS-1$ comboNumberOfPoints.setSelectedItem(new ComboBoxItem(Integer.parseInt(localPropertiesService .getValue(EarthProperty.NUMBER_OF_SAMPLING_POINTS_IN_PLOT)), "")); //$NON-NLS-1$ propertyToComponent.put(EarthProperty.NUMBER_OF_SAMPLING_POINTS_IN_PLOT, new JComponent[] { comboNumberOfPoints }); final String[] listOfNumbers = new String[995]; final String[] listOfNumbersFromTwo = new String[995]; for (int index = 0; index < listOfNumbers.length; index++) { listOfNumbers[index] = index + ""; //$NON-NLS-1$ listOfNumbersFromTwo[index] = (index+2) + ""; //$NON-NLS-1$ } // JTextField listOfDistanceBetweenPoints = new JTextField( localPropertiesService.getValue( EarthProperty.DISTANCE_BETWEEN_SAMPLE_POINTS) ); final JComboBox<String> listOfDistanceBetweenPoints = new JComboBox<String>(listOfNumbers); listOfDistanceBetweenPoints.setSelectedItem(localPropertiesService.getValue(EarthProperty.DISTANCE_BETWEEN_SAMPLE_POINTS)); listOfDistanceBetweenPoints.setAutoscrolls(true); propertyToComponent.put(EarthProperty.DISTANCE_BETWEEN_SAMPLE_POINTS, new JComponent[] { listOfDistanceBetweenPoints }); // JTextField listOfDistanceToBorder = new JTextField(localPropertiesService.getValue( EarthProperty.DISTANCE_TO_PLOT_BOUNDARIES) ); final JComboBox<String> listOfDistanceToBorder = new JComboBox<String>(listOfNumbers); listOfDistanceToBorder.setSelectedItem(localPropertiesService.getValue(EarthProperty.DISTANCE_TO_PLOT_BOUNDARIES)); listOfDistanceToBorder.setAutoscrolls(true); propertyToComponent.put(EarthProperty.DISTANCE_TO_PLOT_BOUNDARIES, new JComponent[] { listOfDistanceToBorder }); // JTextField listOfDistanceToBorder = new JTextField(localPropertiesService.getValue( EarthProperty.DISTANCE_TO_PLOT_BOUNDARIES) ); final JComboBox<String> listOfSizeofSamplingDot = new JComboBox<String>(listOfNumbersFromTwo); listOfSizeofSamplingDot.setSelectedItem(localPropertiesService.getValue(EarthProperty.INNER_SUBPLOT_SIDE)); listOfSizeofSamplingDot.setAutoscrolls(true); propertyToComponent.put(EarthProperty.INNER_SUBPLOT_SIDE, new JComponent[] { listOfSizeofSamplingDot }); final JRadioButton chromeChooser = new JRadioButton("Chrome"); //$NON-NLS-1$ chromeChooser.setSelected(localPropertiesService.getValue(EarthProperty.BROWSER_TO_USE).trim().equals(EarthConstants.CHROME_BROWSER)); chromeChooser.setName(EarthConstants.CHROME_BROWSER); final JRadioButton firefoxChooser = new JRadioButton("Firefox"); //$NON-NLS-1$ firefoxChooser.setSelected(localPropertiesService.getValue(EarthProperty.BROWSER_TO_USE).trim().equals(EarthConstants.FIREFOX_BROWSER)); firefoxChooser.setName(EarthConstants.FIREFOX_BROWSER); propertyToComponent.put(EarthProperty.BROWSER_TO_USE, new JComponent[] { firefoxChooser, chromeChooser }); final JFilePicker saikuPath = new JFilePicker(Messages.getString("OptionWizard.65"), //$NON-NLS-1$ localPropertiesService.getValue(EarthProperty.SAIKU_SERVER_FOLDER), Messages.getString("OptionWizard.66")); //$NON-NLS-1$ saikuPath.setMode(JFilePicker.MODE_OPEN); saikuPath.setFolderChooser(); saikuPath.addChangeListener(new DocumentListener() { private void showSaikuWarning(){ final File saikuFolder = new File(saikuPath.getSelectedFilePath()); if( saikuFolder!=null && !saikuService.isSaikuFolder( saikuFolder )){ JOptionPane.showMessageDialog( OptionWizard.this, Messages.getString("OptionWizard.27"), Messages.getString("OptionWizard.28"), JOptionPane.INFORMATION_MESSAGE ); //$NON-NLS-1$ //$NON-NLS-2$ saikuPath.getTextField().setBackground(CollectEarthWindow.ERROR_COLOR); }else{ saikuPath.getTextField().setBackground(Color.white); } } @Override public void removeUpdate(DocumentEvent e) { } @Override public void insertUpdate(DocumentEvent e) { showSaikuWarning(); } @Override public void changedUpdate(DocumentEvent e) { } }); propertyToComponent.put(EarthProperty.SAIKU_SERVER_FOLDER, new JComponent[] { saikuPath }); final JFilePicker firefoxBinaryPath = new JFilePicker(Messages.getString("OptionWizard.67"), //$NON-NLS-1$ localPropertiesService.getValue(EarthProperty.FIREFOX_BINARY_PATH), Messages.getString("OptionWizard.68")); //$NON-NLS-1$ firefoxBinaryPath.setMode(JFilePicker.MODE_OPEN); firefoxBinaryPath.addFileTypeFilter(".exe", Messages.getString("OptionWizard.70"), true); //$NON-NLS-1$ //$NON-NLS-2$ firefoxBinaryPath.addFileTypeFilter(".bin", Messages.getString("OptionWizard.72"), false); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.FIREFOX_BINARY_PATH, new JComponent[] { firefoxBinaryPath }); final JFilePicker chromeBinaryPath = new JFilePicker(Messages.getString("OptionWizard.73"), //$NON-NLS-1$ localPropertiesService.getValue(EarthProperty.CHROME_BINARY_PATH), Messages.getString("OptionWizard.74")); //$NON-NLS-1$ chromeBinaryPath.setMode(JFilePicker.MODE_OPEN); chromeBinaryPath.addFileTypeFilter(".exe", Messages.getString("OptionWizard.76"), true); //$NON-NLS-1$ //$NON-NLS-2$ chromeBinaryPath.addFileTypeFilter(".bin", Messages.getString("OptionWizard.78"), false); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.CHROME_BINARY_PATH, new JComponent[] { chromeBinaryPath }); final JFilePicker kmlTemplatePath = new JFilePicker(Messages.getString("OptionWizard.79"), //$NON-NLS-1$ localPropertiesService.getValue(EarthProperty.KML_TEMPLATE_KEY), Messages.getString("OptionWizard.80")); //$NON-NLS-1$ kmlTemplatePath.setMode(JFilePicker.MODE_OPEN); kmlTemplatePath.addFileTypeFilter(".fmt", Messages.getString("OptionWizard.82"), true); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.KML_TEMPLATE_KEY, new JComponent[] { kmlTemplatePath }); final JFilePicker htmlBalloonPath = new JFilePicker(Messages.getString("OptionWizard.83"), //$NON-NLS-1$ localPropertiesService.getValue(EarthProperty.BALLOON_TEMPLATE_KEY), Messages.getString("OptionWizard.84")); //$NON-NLS-1$ htmlBalloonPath.setMode(JFilePicker.MODE_OPEN); htmlBalloonPath.addFileTypeFilter(".html,.htm", Messages.getString("OptionWizard.86"), true); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.BALLOON_TEMPLATE_KEY, new JComponent[] { htmlBalloonPath }); final JFilePicker idmPath = new JFilePicker( Messages.getString("OptionWizard.87"), localPropertiesService.getImdFile(), //$NON-NLS-1$ Messages.getString("OptionWizard.88")); //$NON-NLS-1$ idmPath.setMode(JFilePicker.MODE_OPEN); idmPath.addFileTypeFilter(".xml", Messages.getString("OptionWizard.90"), true); //$NON-NLS-1$ //$NON-NLS-2$ propertyToComponent.put(EarthProperty.METADATA_FILE, new JComponent[] { idmPath }); final JTextField surveyNameTextField = new JTextField(localPropertiesService.getValue(EarthProperty.SURVEY_NAME)); surveyNameTextField.setEnabled(false); propertyToComponent.put(EarthProperty.SURVEY_NAME, new JComponent[] { surveyNameTextField }); // Database options final JRadioButton instanceTypeServer = new JRadioButton(Messages.getString("OptionWizard.91")); //$NON-NLS-1$ instanceTypeServer.setSelected(localPropertiesService.getOperationMode().equals( OperationMode.SERVER_MODE ) ); instanceTypeServer.setName(EarthConstants.OperationMode.SERVER_MODE.name()); final JRadioButton instanceTypeClient = new JRadioButton(Messages.getString("OptionWizard.92")); //$NON-NLS-1$ instanceTypeClient.setSelected( localPropertiesService.getOperationMode().equals( OperationMode.CLIENT_MODE ) ); instanceTypeClient.setName(EarthConstants.OperationMode.CLIENT_MODE.name()); propertyToComponent.put(EarthProperty.OPERATION_MODE, new JComponent[] { instanceTypeServer, instanceTypeClient }); final JTextField collectEarthServerIp = new JTextField(localPropertiesService.getValue(EarthProperty.HOST_KEY)); propertyToComponent.put(EarthProperty.HOST_KEY, new JComponent[] { collectEarthServerIp }); final JTextField collectEarthServerIpPort = new JTextField( localPropertiesService.getPort() ); final JTextField collectEarthServerLocalPort = new JTextField(localPropertiesService.getValue(EarthProperty.HOST_PORT_KEY)); propertyToComponent.put(EarthProperty.HOST_PORT_KEY, new JComponent[] { collectEarthServerIpPort, collectEarthServerLocalPort }); final JRadioButton sqliteDbType = new JRadioButton(Messages.getString("OptionWizard.93")); //$NON-NLS-1$ sqliteDbType.setSelected(localPropertiesService.getCollectDBDriver().equals(CollectDBDriver.SQLITE)); sqliteDbType.setName(CollectDBDriver.SQLITE.name()); final JRadioButton postgresDbType = new JRadioButton(Messages.getString("OptionWizard.94")); //$NON-NLS-1$ boolean usingPostgreSQL = localPropertiesService.getCollectDBDriver().equals(CollectDBDriver.POSTGRESQL); postgresDbType.setSelected(usingPostgreSQL); postgresDbType.setName(CollectDBDriver.POSTGRESQL.name()); propertyToComponent.put(EarthProperty.DB_DRIVER, new JComponent[] { sqliteDbType, postgresDbType }); final JTextField dbUserName = new JTextField(localPropertiesService.getValue(EarthProperty.DB_USERNAME)); propertyToComponent.put(EarthProperty.DB_USERNAME, new JComponent[] { dbUserName }); final JTextField dbPassword = new JTextField(localPropertiesService.getValue(EarthProperty.DB_PASSWORD)); propertyToComponent.put(EarthProperty.DB_PASSWORD, new JComponent[] { dbPassword }); final JTextField dbName = new JTextField(localPropertiesService.getValue(EarthProperty.DB_NAME)); propertyToComponent.put(EarthProperty.DB_NAME, new JComponent[] { dbName }); final JTextField dbHost = new JTextField(localPropertiesService.getValue(EarthProperty.DB_HOST)); propertyToComponent.put(EarthProperty.DB_HOST, new JComponent[] { dbHost }); final JTextField dbPort = new JTextField(localPropertiesService.getValue(EarthProperty.DB_PORT)); propertyToComponent.put(EarthProperty.DB_PORT, new JComponent[] { dbPort }); } public boolean isRestartRequired() { return restartRequired; } public void setRestartRequired(boolean restartRequired) { this.restartRequired = restartRequired; } }
package org.ow2.proactive_grid_cloud_portal.common.client; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Window; import com.smartgwt.client.util.BooleanCallback; import com.smartgwt.client.util.SC; import com.smartgwt.client.widgets.events.ClickEvent; import com.smartgwt.client.widgets.events.ClickHandler; import com.smartgwt.client.widgets.toolbar.ToolStripButton; public class ToolButtonsRender { private static final String GREY_BUTTON_BORDER = "1px solid #858585"; public ToolStripButton getSchedulerLinkButton() { return getToolStripButton(Images.instance.scheduler_30(), "Scheduling & Orchestration", "/scheduler/"); } public ToolStripButton getSchedulerHighlightedLinkButton() { return getToolStripButtonHighlighted(Images.instance.scheduler_30(), "Scheduling & Orchestration", "/scheduler/"); } public ToolStripButton getStudioLinkButton() { ImageResource imageResource = Images.instance.studio_30(); String title = "Workflow Studio"; String url = "/studio/"; return getToolStripButton(imageResource, title, url); } public ToolStripButton getResourceManagerLinkButton() { return getToolStripButton(Images.instance.rm_30(), "Resource Manager", "/rm/"); } public ToolStripButton getResourceManagerHighlightedLinkButton() { return getToolStripButtonHighlighted(Images.instance.rm_30(), "Resource Manager", "/rm/"); } public ToolStripButton getAutomationDashboardLinkButton() { return getToolStripButton(Images.instance.automation_dashboard_30(), "Automation Dashboard", "/automation-dashboard/"); } public ToolStripButton getLogoutButton(String login, final Controller controller) { ToolStripButton logoutButton = getSimpleToolStripButton(Images.instance.logout_30(), login); logoutButton.setIconOrientation("right"); logoutButton.setTooltip("Logout"); logoutButton.setBorder(GREY_BUTTON_BORDER); logoutButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { SC.confirm("Logout", "Are you sure you want to exit?", new BooleanCallback() { public void execute(Boolean value) { if (value) { controller.logout(); } } }); } }); return logoutButton; } private ToolStripButton getToolStripButton(ImageResource imageResource, String title, final String url) { ToolStripButton toolStripButton = getToolStripButtonWithoutBorder(imageResource, title, url); toolStripButton.setBorder(GREY_BUTTON_BORDER); return toolStripButton; } private ToolStripButton getToolStripButtonHighlighted(ImageResource imageResource, String title, final String url) { ToolStripButton toolStripButton = getToolStripButtonWithoutBorder(imageResource, title, url); toolStripButton.setBorder(GREY_BUTTON_BORDER); toolStripButton.setBackgroundColor("#e6e6e6"); return toolStripButton; } private ToolStripButton getToolStripButtonWithoutBorder(ImageResource imageResource, String title, final String url) { ToolStripButton toolStripButton = getSimpleToolStripButton(imageResource, title); toolStripButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { Window.open(url, url, ""); } }); return toolStripButton; } private ToolStripButton getSimpleToolStripButton(ImageResource imageResource, String title) { ToolStripButton toolStripButton = new ToolStripButton(title); toolStripButton.setIcon(imageResource.getSafeUri().asString()); toolStripButton.setIconSize(25); return toolStripButton; } }
package com.nectarjs.nectar_android_app; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { private WebView mainWebView; private ValueCallback<Uri> mUploadMessage; public ValueCallback<Uri[]> uploadMessage; public static final int REQUEST_SELECT_FILE = 100; private final static int FILECHOOSER_RESULTCODE = 1; private static final String TAG = MainActivity.class.getSimpleName(); private String mCM; private ValueCallback mUM; private ValueCallback<Uri[]> mUMA; private final static int FCR=1; // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } private String checkVersion() { // Restore preferences SharedPreferences settings = getSharedPreferences("NECTAR_APP_PREF", 0); String version = settings.getString("version", ""); return version; } class NectarInterface { @JavascriptInterface public void fireEvent(final String event) { runOnUiThread(new Runnable() { @Override public void run() { callbackFromJNI(event); } }); } } private void copyAssets(String base) { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(base); } catch (IOException e) { Log.e("tag", "Failed to get asset file list.", e); } final File newFile = new File(getFilesDir() + "/" + base); newFile.mkdir(); if (files != null) for (String filename : files) { InputStream in = null; OutputStream out = null; try { Log.d("File", base + "/" + filename); in = assetManager.open(base + "/" + filename); File outFile = new File(getFilesDir() + "/" + base + "/", filename); out = new FileOutputStream(outFile); copyFile(in, out); } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + base + "/" + filename, e); copyAssets(base + "/" + filename); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // NOOP } } if (out != null) { try { out.close(); } catch (IOException e) { // NOOP } } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { try { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } catch(Exception e){} } boolean deleteDirectory(File directoryToBeDeleted) { File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) { for (File file : allContents) { deleteDirectory(file); } } return directoryToBeDeleted.delete(); } public static String loadAssetFile(Context context, String fileName) { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName))); StringBuilder out= new StringBuilder(); String eachline = bufferedReader.readLine(); while (eachline != null) { out.append(eachline); eachline = bufferedReader.readLine(); } return out.toString(); } catch (IOException e) { Log.e("Load Asset File",e.toString()); } return null; } public static void triggerRebirth(Context context) { PackageManager packageManager = context.getPackageManager(); Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName()); ComponentName componentName = intent.getComponent(); Intent mainIntent = Intent.makeRestartActivityTask(componentName); context.startActivity(mainIntent); Runtime.getRuntime().exit(0); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent){ super.onActivityResult(requestCode, resultCode, intent); if(Build.VERSION.SDK_INT >= 21){ Uri[] results = null; //Check if response is positive if(resultCode== Activity.RESULT_OK){ if(requestCode == FCR){ if(null == mUMA){ return; } if(intent == null || intent.getData() == null){ //Capture Photo if no image available if(mCM != null){ results = new Uri[]{Uri.parse(mCM)}; } }else{ String dataString = intent.getDataString(); if(dataString != null){ results = new Uri[]{Uri.parse(dataString)}; } } } } mUMA.onReceiveValue(results); mUMA = null; }else{ if(requestCode == FCR){ if(null == mUM) return; Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); mUM.onReceiveValue(result); mUM = null; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA}, 1); } setContentView(R.layout.activity_main); mainWebView = findViewById(R.id.WebView); mainWebView.setWebViewClient(new WebViewClient()); WebSettings webSettings = mainWebView.getSettings(); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setBuiltInZoomControls(true); webSettings.setAllowFileAccess(true); webSettings.setAllowContentAccess(true); webSettings.setSupportZoom(true); webSettings.setGeolocationEnabled(true); mainWebView.addJavascriptInterface(new NectarInterface(), "Nectar"); mainWebView.setWebChromeClient(new WebChromeClient() { public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); } // For 3.0+ Devices (Start) // onActivityResult attached before constructor protected void openFileChooser(ValueCallback uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); /* public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { if (uploadMessage != null) { uploadMessage.onReceiveValue(null); uploadMessage = null; } uploadMessage = filePathCallback; Intent intent = fileChooserParams.createIntent(); try { startActivityForResult(intent, REQUEST_SELECT_FILE); } catch (ActivityNotFoundException e) { uploadMessage = null; //Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show(); return false; } return true; } */ // Create an image file private File createImageFile() throws IOException{ @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "img_"+timeStamp+"_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); return File.createTempFile(imageFileName,".jpg",storageDir); } public boolean onShowFileChooser( WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){ if(mUMA != null){ mUMA.onReceiveValue(null); } mUMA = filePathCallback; Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){ File photoFile = null; try{ photoFile = createImageFile(); takePictureIntent.putExtra("PhotoPath", mCM); }catch(IOException ex){ Log.e(TAG, "Image file creation failed", ex); } if(photoFile != null){ mCM = "file:" + photoFile.getAbsolutePath(); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); }else{ takePictureIntent = null; } } Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT); contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE); contentSelectionIntent.setType("*/*"); Intent[] intentArray; if(takePictureIntent != null){ intentArray = new Intent[]{takePictureIntent}; }else{ intentArray = new Intent[0]; } Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER); chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent); chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray); startActivityForResult(chooserIntent, FCR); return true; } //For Android 4.1 only protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { mUploadMessage = uploadMsg; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE);
package org.hisp.dhis.android.core.organisationunit; import android.database.Cursor; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.gabrielittner.auto.value.cursor.ColumnName; import com.google.auto.value.AutoValue; import org.hisp.dhis.android.core.common.BaseModel; import org.hisp.dhis.android.core.utils.Utils; @AutoValue public abstract class OrganisationUnitProgramLinkModel extends BaseModel { public static final String TABLE = "OrganisationUnitProgramLink"; public static class Columns extends BaseModel.Columns { public static final String PROGRAM = "program"; public static final String ORGANISATION_UNIT = "organisationUnit"; @Override public String[] all() { return Utils.appendInNewArray(super.all(), PROGRAM, ORGANISATION_UNIT); } } @Nullable @ColumnName(Columns.PROGRAM) public abstract String program(); @Nullable @ColumnName(Columns.ORGANISATION_UNIT) public abstract String organisationUnit(); @NonNull public static OrganisationUnitProgramLinkModel create(Cursor cursor) { return AutoValue_OrganisationUnitProgramLinkModel.createFromCursor(cursor); } @NonNull public static Builder builder() { return new $$AutoValue_OrganisationUnitProgramLinkModel.Builder(); } @AutoValue.Builder public static abstract class Builder extends BaseModel.Builder<Builder> { public abstract Builder program(@Nullable String program); public abstract Builder organisationUnit(@Nullable String organisationUnit); public abstract OrganisationUnitProgramLinkModel build(); } }
package com.arjuna.databroker.data.jee.store; import java.io.Serializable; import java.util.Collections; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.InitialContext; import com.arjuna.databroker.data.DataFlowNodeState; public class StoreDataFlowNodeState implements DataFlowNodeState { private static final Logger logger = Logger.getLogger(StoreDataFlowNodeState.class.getName()); // TODO: Remove - for testing only public StoreDataFlowNodeState() { logger.log(Level.WARNING, "StoreDataFlowNodeState: for testing only"); try { _dataFlowNodeUtils = (DataFlowNodeUtils) new InitialContext().lookup("java:global/databroker/data-common-jee-store/DataFlowNodeUtils"); } catch (Throwable throwable) { logger.log(Level.WARNING, "StoreDataFlowNodeState: no dataFlowNodeUtils found", throwable); } _id = UUID.randomUUID().toString(); _dataFlowNodeUtils.create(_id, "Test", Collections.<String, String>emptyMap(), "The Node Class Name"); } public StoreDataFlowNodeState(String name, Map<String, String> properties, String nodeClassName) { logger.log(Level.WARNING, "StoreDataFlowNodeState: " + name + ", " + properties + ", " + nodeClassName); try { _dataFlowNodeUtils = (DataFlowNodeUtils) new InitialContext().lookup("java:global/databroker/data-common-jee-store/DataFlowNodeUtils"); } catch (Throwable throwable) { logger.log(Level.WARNING, "StoreDataFlowNodeState: no dataFlowNodeUtils found", throwable); } _id = UUID.randomUUID().toString(); _dataFlowNodeUtils.create(_id, name, properties, nodeClassName); } public StoreDataFlowNodeState(String id) { logger.log(Level.FINE, "StoreDataFlowNodeState: " + id); try { _dataFlowNodeUtils = (DataFlowNodeUtils) new InitialContext().lookup("java:global/databroker/data-common-jee-store/DataFlowNodeUtils"); } catch (Throwable throwable) { logger.log(Level.WARNING, "StoreDataFlowNodeState: no dataFlowNodeUtils found", throwable); } _id = id; } public String getId() { return _id; } @Override public Serializable getState() { return _dataFlowNodeUtils.getState(_id); } @Override public void setState(Serializable state) { _dataFlowNodeUtils.setState(_id, state); } private String _id; private DataFlowNodeUtils _dataFlowNodeUtils; }
package unitTests.gcmdeployment.virtualnode; import java.util.List; import java.util.Map; import java.net.URL; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.ProActiveRandom; import org.objectweb.proactive.core.xml.VariableContractImpl; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.GCMApplicationInternal; import org.objectweb.proactive.extensions.gcmdeployment.GCMApplication.NodeProvider; import org.objectweb.proactive.gcmdeployment.GCMVirtualNode; import org.objectweb.proactive.gcmdeployment.Topology; public class GCMApplicationDescriptorMockup implements GCMApplicationInternal { public long deploymentId; public GCMApplicationDescriptorMockup() { deploymentId = ProActiveRandom.nextInt(); } public List<Node> getAllCurrentNodes() { throw new RuntimeException("Not implemented"); } public Topology getAllCurrentNodesTopology() { throw new RuntimeException("Not implemented"); } public List<Node> getCurrentUnmappedNodes() { throw new RuntimeException("Not implemented"); } public long getDeploymentId() { return deploymentId; } public VariableContractImpl getVariableContract() { throw new RuntimeException("Not implemented"); } public URL getDescriptorURL() { throw new RuntimeException("Not implemented"); } public GCMVirtualNode getVirtualNode(String vnName) { throw new RuntimeException("Not implemented"); } public Map<String, ? extends GCMVirtualNode> getVirtualNodes() { throw new RuntimeException("Not implemented"); } public boolean isStarted() { throw new RuntimeException("Not implemented"); } public void kill() { throw new RuntimeException("Not implemented"); } public void startDeployment() { throw new RuntimeException("Not implemented"); } public void updateTopology(Topology topology) { throw new RuntimeException("Not implemented"); } public void addNode(Node node) { // Do nothing } public NodeProvider getNodeProviderFromTopologyId(Long topologyId) { throw new RuntimeException("Not implemented"); } public String debugUnmappedNodes() { throw new RuntimeException("Not implemented"); } public long getNbUnmappedNodes() { throw new RuntimeException("Not implemented"); } public void waitReady() { throw new RuntimeException("Not implemented"); } }
// JxpScriptContext.java package ed.appserver.jxp; import java.io.*; import java.util.*; import javax.script.*; import ed.js.*; import ed.js.engine.*; import ed.appserver.*; import ed.net.httpserver.*; import ed.lang.*; public class JxpScriptContext implements ScriptContext { public JxpScriptContext( ObjectConvertor convertor , Scope s ){ _convertor = convertor; _scope = s; _writer = new OutputStreamWriter( System.out ); } public JxpScriptContext( ObjectConvertor convertor , HttpRequest request , HttpResponse response , AppRequest ar ){ _convertor = convertor; _scope = ar.getScope(); _writer = ar.getServletWriter().asJavaWriter(); } public Object getAttribute(String name){ return getAttribute( name , 0 ); } public Object getAttribute(String name, int scope){ Object o = null; if ( name.equals( "_10gen" ) || name.equals( "_xgen" ) ) o = _scope; else o = _scope.get( name ); if ( _convertor != null ) o = _convertor.toOther( o ); return o; } public int getAttributesScope(String name){ throw new RuntimeException( "what?" ); } public Bindings getBindings(int scope){ return _scope; } public Writer getErrorWriter(){ return new OutputStreamWriter( System.err ); } public Reader getReader(){ return null; } public List<Integer> getScopes(){ return SCOPES; } public Writer getWriter(){ return _writer; } public Object removeAttribute(String name, int scope){ throw new RuntimeException( "not done" ); } public void setAttribute(String name, Object value, int scope){ if ( _convertor != null ) value = _convertor.toJS( value ); _scope.put( name , value , false ); } public void setBindings(Bindings bindings, int scope){ throw new RuntimeException( "not done" ); } public void setErrorWriter(Writer writer){ throw new RuntimeException( "you can't change the ErrorWriter" ); } public void setReader(Reader reader){ throw new RuntimeException( "you can't change the reader" ); } public void setWriter(Writer writer){ throw new RuntimeException( "you can't change the writer" ); } public ObjectConvertor getObjectConvertor(){ return _convertor; } public void setObjectConvertor( ObjectConvertor convertor ){ _convertor = convertor; } final Scope _scope; final Writer _writer; ObjectConvertor _convertor; static final List<Integer> SCOPES; static { List<Integer> lst = new LinkedList<Integer>(); lst.add( 0 ); SCOPES = Collections.unmodifiableList( lst ); } }
package app.config; import com.mpalourdio.springboottemplate.properties.CredentialsProperties; import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String BASIC_AUTH_ENDPOINT = "/basicauth"; private static final String ADMIN_ROLE = "ADMIN"; private static final String ACTUATOR_ROLE = "ACTUATOR"; private final CredentialsProperties credentialsProperties; public WebSecurityConfig(CredentialsProperties credentialsProperties) { this.credentialsProperties = credentialsProperties; } @Override protected void configure(HttpSecurity http) throws Exception { //We disable csrf protection for actuator endpoints so we can post with curl //ex : the refresh endpoint http.csrf().ignoringRequestMatchers(EndpointRequest.toAnyEndpoint()); http.logout() .logoutSuccessUrl("/") .invalidateHttpSession(true) .clearAuthentication(true) .logoutSuccessHandler(logoutHandler()) .logoutRequestMatcher(new AntPathRequestMatcher("/logout")); http.authorizeRequests() .antMatchers(BASIC_AUTH_ENDPOINT) .hasRole(ADMIN_ROLE) .requestMatchers(EndpointRequest.toAnyEndpoint()) .hasRole(ACTUATOR_ROLE) .and() .httpBasic(); } @Bean public InMemoryUserDetailsManager inMemoryUserDetailsManager() { return new InMemoryUserDetailsManager( User.withDefaultPasswordEncoder() .username(credentialsProperties.getUsername()) .password(credentialsProperties.getPassword()) .roles(ADMIN_ROLE, ACTUATOR_ROLE) .build() ); } private LogoutSuccessHandler logoutHandler() { SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler(); DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); redirectStrategy.setContextRelative(false); logoutSuccessHandler.setRedirectStrategy(redirectStrategy); return logoutSuccessHandler; } }
package base.grid.header; import java.util.ArrayList; import java.util.List; public class TableHeader { private Class<? extends TableCellHeader> header; private String selector; private int rowModifier = 0; public TableHeader(Class<? extends TableCellHeader> header, String selector) { this.header = header; this.selector = selector; } public void setRowModifier(int rowModifier) { this.rowModifier = rowModifier; } private List<CellHeader> getHeaders() { List<CellHeader> cellsHeader = new ArrayList<CellHeader>(); TableCellHeader[] headerColumns = header.getEnumConstants(); int row = 1 + rowModifier; int column; for (TableCellHeader headerColumn : headerColumns) { column = headerColumn.getIndex(); cellsHeader.add(new CellHeader(selector, row, column, headerColumn)); } return cellsHeader; } public List<CellHeader> getCellsHeader() { return getHeaders(); } public CellHeader getCellHeader(TableCellHeader cellHeader) { return getHeaders().get(cellHeader.getIndex() - 1); } }
package bisq.desktop.app; import bisq.desktop.common.UITimer; import bisq.desktop.common.view.guice.InjectorViewFactory; import bisq.desktop.setup.DesktopPersistedDataHost; import bisq.core.app.BisqExecutable; import bisq.common.UserThread; import bisq.common.app.AppModule; import bisq.common.proto.persistable.PersistedDataHost; import bisq.common.setup.CommonSetup; import com.google.inject.Injector; import javafx.application.Application; import javafx.application.Platform; import lombok.extern.slf4j.Slf4j; @Slf4j public class BisqAppMain extends BisqExecutable { private BisqApp application; public static void main(String[] args) throws Exception { if (BisqExecutable.setupInitialOptionParser(args)) { // For some reason the JavaFX launch process results in us losing the thread context class loader: reset it. // In order to work around a bug in JavaFX 8u25 and below, you must include the following code as the first line of your realMain method: Thread.currentThread().setContextClassLoader(BisqAppMain.class.getClassLoader()); new BisqAppMain().execute(args); } } // First synchronous execution tasks @Override protected void configUserThread() { UserThread.setExecutor(Platform::runLater); UserThread.setTimerClass(UITimer.class); } @Override protected void launchApplication() { BisqApp.setAppLaunchedHandler(application -> { BisqAppMain.this.application = (BisqApp) application; // Map to user thread! UserThread.execute(this::onApplicationLaunched); }); Application.launch(BisqApp.class); } // As application is a JavaFX application we need to wait for onApplicationLaunched @Override protected void onApplicationLaunched() { super.onApplicationLaunched(); application.setGracefulShutDownHandler(this); CommonSetup.setup(application); } // We continue with a series of synchronous execution tasks @Override protected AppModule getModule() { return new BisqAppModule(bisqEnvironment); } @Override protected void applyInjector() { super.applyInjector(); application.setInjector(injector); injector.getInstance(InjectorViewFactory.class).setInjector(injector); } @Override protected void setupPersistedDataHosts(Injector injector) { super.setupPersistedDataHosts(injector); PersistedDataHost.apply(DesktopPersistedDataHost.getPersistedDataHosts(injector)); } @Override protected void startApplication() { // We need to be in user thread! We mapped at launchApplication already... application.startApplication(); } }
package br.com.dbsoft.util; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.Date; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.context.FacesContext; public class DBSFormat { public static String[] ZERO_DDI_DDDs = new String[]{ "800", "300" }; public class MASK{ public static final String CURRENCY = "###,##0.00"; } public final static class REGEX{ public static final String ZIP = "\\d{5}-\\d{3}"; public static final String LICENSE_PLATE = "[A-Z]{3}-\\d{4}"; // public static final String PHONE_NUMBER = "^([(+]{0,1})([0-9]{0,2})([)\\-\\s]{0,1})([(\\-\\s]{0,1})([0-9]{0,3})([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; public static final String PHONE_NUMBER = "^([(+]{0,1})(([0-9]{2,3})|([0-9]{0}))([)\\-\\s]{0,1})([(\\-\\s]{0,1})(([0-9]{2,3})|([0-9]{0}))([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; // public static final String PHONE_NUMBER = "^([(+]{0,1})([0-9]{2,3})([)\\-\\s]{0,1})([(\\-\\s]{0,1})([0-9]{2,3})([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; public static final String ONLY_NUMBERS = "^[0-9]+$"; } private static Pattern wPHONE_NUMBER; public static enum NUMBER_SIGN{ NONE, CRDB_PREFIX, CRDB_SUFFIX, MINUS_SUFFIX, MINUS_PREFIX, PARENTHESES; } DBSFormat(){ wPHONE_NUMBER = Pattern.compile(REGEX.PHONE_NUMBER); } // //## public properties # // public static String getFormattedDate(Long pDate){ return getFormattedDate(DBSDate.toDate(pDate)); } public static String getFormattedDate(Object pDate){ if (DBSObject.isEmpty(pDate)){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy"); return xFormat.format(DBSDate.toDate(pDate)); } } public static String getFormattedDate(Date pDate){ if (pDate == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy"); return xFormat.format(pDate); } } public static String getFormattedDate(Timestamp pDate){ if (pDate == null){ return ""; }else{ Date xDate = DBSDate.toDate(pDate); return getFormattedDate(xDate); } } public static String getFormattedAno(Object pDate) { if (pDate == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("yyyy"); return xFormat.format(DBSDate.toDate(pDate)); } } public static String getFormattedDateTimes(Long pLong){ if (pLong == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return xFormat.format(pLong); } } public static String getFormattedDateTimes(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return xFormat.format(pDate); } public static String getFormattedDateTimes(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedDateTimes(xDate); } public static String getFormattedTimes(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("HH:mm:ss"); return xFormat.format(pDate.getTime()); } public static String getFormattedDateTime(Long pLong){ if (pLong == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); return xFormat.format(pLong); } } public static String getFormattedDateTime(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); return xFormat.format(pDate); } public static String getFormattedDateTime(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedDateTime(xDate); } public static String getFormattedTime(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("HH:mm"); return xFormat.format(pDate.getTime()); } public static String getFormattedDateCustom(Object pDate, String pMask){ if (DBSObject.isNull(pDate)) { return ""; } SimpleDateFormat xFormat = new SimpleDateFormat(pMask); return xFormat.format(DBSDate.toDate(pDate)); } public static String getFormattedTime(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedTimes(xDate); } public static String getFormattedNumberUnsigned(Double pValue, Object pDecimalPlaces){ return getFormattedNumberUnsigned(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumberUnsigned(Object pValue, Object pDecimalPlaces){ return getFormattedNumberUnsigned(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumberUnsigned(Object pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), NUMBER_SIGN.NONE, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedNumber(BigDecimal pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumber(BigDecimal pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), pDecimalPlaces, pLocale); } public static String getFormattedNumber(Double pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), getLocale()); } public static String getFormattedNumber(Double pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(pValue, NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedNumber(Object pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumber(Object pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedCurrency(Object pValor){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, getLocale())); } public static String getFormattedCurrency(Object pValor, Locale pLocale){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, pLocale), pLocale); } public static String getFormattedCurrency(Double pValor){ return getFormattedCurrency(pValor, NUMBER_SIGN.MINUS_PREFIX); } public static String getFormattedCurrency(Double pValor, Locale pLocale){ return getFormattedCurrency(pValor, NUMBER_SIGN.MINUS_PREFIX, pLocale); } public static String getFormattedCurrency(Object pValor, NUMBER_SIGN pSign){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, getLocale()), pSign, getLocale()); } public static String getFormattedCurrency(Object pValor, NUMBER_SIGN pSign, Locale pLocale){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, pLocale), pSign, pLocale); } public static String getFormattedCurrency(Double pValor, NUMBER_SIGN pSign){ return getFormattedNumber(pValor, pSign, MASK.CURRENCY, getLocale()); } public static String getFormattedCurrency(Double pValor, NUMBER_SIGN pSign, Locale pLocale){ return getFormattedNumber(pValor, pSign, MASK.CURRENCY, pLocale); } public static String getFormattedNumber(Object pValor, NUMBER_SIGN pSign, String pNumberMask){ return getFormattedNumber(DBSNumber.toDouble(pValor, 0D, getLocale()), pSign, pNumberMask, getLocale()); } public static String getFormattedNumber(Object pValor, NUMBER_SIGN pSign, String pNumberMask, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValor, 0D, pLocale), pSign, pNumberMask, pLocale); } public static String getFormattedNumber(Double pValor, NUMBER_SIGN pSign, String pNumberMask){ return getFormattedNumber(pValor, pSign, pNumberMask, getLocale()); } public static String getFormattedNumber(Double pValor, NUMBER_SIGN pSign, String pNumberMask, Locale pLocale){ if (DBSObject.isEmpty(pValor)) { return null; } DecimalFormatSymbols xOtherSymbols = new DecimalFormatSymbols(pLocale); // xOtherSymbols.setDecimalSeparator(getDecimalSeparator().charAt(0)); // xOtherSymbols.setGroupingSeparator(getGroupSeparator().charAt(0)); DecimalFormat xDF = new DecimalFormat(pNumberMask, xOtherSymbols); // DecimalFormat xDF = new DecimalFormat(pNumberMask); xDF.get xDF.setRoundingMode(RoundingMode.HALF_UP); switch (pSign) { case NONE: xDF.setNegativePrefix(""); xDF.setNegativeSuffix(""); break; case CRDB_PREFIX: xDF.setPositivePrefix("CR "); xDF.setNegativePrefix("DB "); break; case CRDB_SUFFIX: xDF.setPositiveSuffix(" CR"); xDF.setNegativeSuffix(" DB"); xDF.setNegativePrefix(""); break; case MINUS_PREFIX: xDF.setPositivePrefix(""); xDF.setNegativePrefix("-"); break; case MINUS_SUFFIX: xDF.setPositivePrefix(""); xDF.setNegativePrefix(""); xDF.setNegativeSuffix("-"); break; case PARENTHESES: xDF.setPositivePrefix(""); xDF.setNegativePrefix("("); xDF.setNegativeSuffix(")"); break; default: xDF.setPositivePrefix(""); xDF.setNegativePrefix("-"); break; } return xDF.format(pValor); } public static String getNumberMask(int pDecimalPlaces, boolean pUseSeparator){ return getNumberMask(pDecimalPlaces, pUseSeparator, 0); } public static String getNumberMask(int pDecimalPlaces, int pLeadingZeroSize){ return getNumberMask(pDecimalPlaces, false, pLeadingZeroSize); } public static String getNumberMask(int pDecimalPlaces){ return getNumberMask(pDecimalPlaces, true,0 ); } public static String getNumberMask(int pDecimalPlaces, boolean pUseSeparator, int pLeadingZeroSize){ String xF; if (pUseSeparator){ xF = " }else{ if (pLeadingZeroSize > 0){ xF = DBSString.repeat("0",pLeadingZeroSize); }else{ xF = " } } if (pDecimalPlaces < 0){ return null; } if (pDecimalPlaces > 0){ xF = xF + "." + DBSString.repeat("0",pDecimalPlaces); } return xF; } public static String getNumeroSemPontoMilhar(Double pValor, int pCasasDecimais){ if (DBSObject.isEmpty(pValor)){ return null; } String xS = getFormattedNumber(pValor, getNumberMask(pCasasDecimais)); return DBSString.changeStr(xS, ",", ""); } public static String getCNPJ(Object pCNPJ) { return getFormattedMask(pCNPJ, "99.999.999/9999-99", " "); } public static String getCPF(Object pCPF) { return getFormattedMask(pCPF, "999.999.9999-99", " "); } public static String getCEP(Object pCEP) { return getFormattedMask(pCEP, "99999-999", " "); } public static String getCPFCNPJ(Object pPessoaFisica, Object pValue){ String xValue = DBSString.toString(pValue); xValue = DBSNumber.getOnlyNumber(xValue); if (DBSBoolean.toBoolean(pPessoaFisica)){ return getCPF(pValue); }else{ return getCNPJ(pValue); } } /** * Retorna o caracter utilizado para separar a casa decimal * @return */ public static String getDecimalSeparator(){ DecimalFormat xFormat = (DecimalFormat) DecimalFormat.getInstance(getLocale()); DecimalFormatSymbols xD = xFormat.getDecimalFormatSymbols(); return Character.toString(xD.getDecimalSeparator()); } public static String getGroupSeparator(){ DecimalFormat xFormat = (DecimalFormat) DecimalFormat.getInstance(getLocale()); DecimalFormatSymbols xD = xFormat.getDecimalFormatSymbols(); return Character.toString(xD.getGroupingSeparator()); } public static String getFormattedMask(Object pValue, String pMask){ return getFormattedMask(pValue, pMask, ""); } public static String getFormattedMask(Object pValue, String pMask, String pEmptyChr){ if (pValue ==null || pEmptyChr == null){ return ""; } if (pMask.equals("")){ return pValue.toString(); } //9=Numeric; a=Alpha; x=AlphaNumeric String xFV = ""; String xValue = pValue.toString(); int xVI = 0; boolean xAchou; for (int xMI =0 ; xMI < pMask.length(); xMI++){ String xMC = pMask.substring(xMI, xMI+1).toUpperCase(); if (xMC.equals("9")|| xMC.equals("A")){ xAchou = false; while (xVI < xValue.length()){ char xVC = xValue.charAt(xVI); xVI++; if(Character.isLetterOrDigit(xVC)){ xFV = xFV + xVC; xAchou = true; break; } } if (!xAchou){ xFV = xFV + pEmptyChr; } }else{ xFV = xFV + xMC; } } return xFV; } public static String numberSimplify(Number pValue){ Double xVal = pValue.doubleValue(); Integer xIntVal = pValue.intValue(); Integer xLength = xIntVal.toString().length(); if (xLength == 0){return "";} Double xSimple = (xVal / Math.pow(10, ((xLength -1) - ((xLength -1) % 3)))); String xSuf = ""; // String xFormated = ""; if (xLength > 15){ xSuf = "quatri"; }else if (xLength > 12){ xSuf = "tri"; }else if (xLength > 9){ xSuf = "bi"; }else if (xLength > 6){ xSuf = "mi"; }else if (xLength > 3){ xSuf = "mil"; } if (xSuf != ""){ return getFormattedNumber(xSimple, 0) + " " + xSuf; }else{ return getFormattedNumber(xVal, 2); } } //Validation public static Matcher isPhone(String pString){ if (pString == null){ return null; } Matcher xP = wPHONE_NUMBER.matcher(pString); return xP; } public static String getPhoneNumber(Object pDDI, Object pDDD, Object pNumber){ return getPhoneNumber(DBSString.toString(pDDI),DBSString.toString(pDDD),DBSString.toString(pNumber)); } public static String getPhoneNumber(String pDDI, String pDDD, String pNumber){ StringBuilder xSB = new StringBuilder(); if (DBSObject.isEmpty(pNumber)){ return ""; } if (!DBSObject.isEmpty(pDDI)){ xSB.append("("); xSB.append(pDDI); xSB.append(")"); } if (!DBSObject.isEmpty(pDDD)){ xSB.append("("); xSB.append(pDDD); xSB.append(")"); } xSB.append(pNumber); return getPhoneNumber(xSB.toString()); } public static String getPhoneNumber(String pPhoneNumber){ StringBuilder xFormattedNumber = new StringBuilder(); String xChar; Boolean xIsNumber = false; Boolean xWasNumber = null; Integer xGroup = 1; StringBuilder xValue = new StringBuilder(); for (int i=pPhoneNumber.length(); i>0; i xChar = pPhoneNumber.substring(i-1, i); xIsNumber = xChar.matches(REGEX.ONLY_NUMBERS); if (xWasNumber == null){ xWasNumber = xIsNumber; }else if (xIsNumber != xWasNumber){ xGroup = pvPhoneNumber(xFormattedNumber, xGroup, xValue.toString(), xWasNumber); if (xGroup == null){ return null; } xValue = new StringBuilder(); xWasNumber = xIsNumber; if (!xIsNumber){ xChar = "-"; } }else if (!xIsNumber){ xChar = null; } if (xChar != null){ xValue.insert(0, xChar); } } if (!DBSObject.isEmpty(xValue.toString())){ xGroup = pvPhoneNumber(xFormattedNumber, xGroup, xValue.toString(), xWasNumber); } String xFN = xFormattedNumber.toString(); if (xGroup == null || DBSObject.isEmpty(xFN)){ return null; }else{ if (xFN.startsWith(")")){ xFN = xFN.substring(1, xFN.length()); } return xFN; } } /** * DDI DDD NUMERO * xxx xxx xxxx-xxxx * @param pFormattedNumber * @param pGroup * @param pValue * @param pIsNumber * @return */ private static Integer pvPhoneNumber(StringBuilder pFormattedNumber, Integer pGroup, String pValue, Boolean pIsNumber){ String xValue = null; int xB = 0; int xE = 0; Integer xMin = 0; Integer xMax = null; if (DBSObject.isEmpty(pValue)){return pGroup;} xE = pValue.length(); if (pGroup > 8){ return null; }else if (pGroup==2 //Separadores || pGroup==4 || pGroup==6 || pGroup==8){ if (pGroup==8){ xValue = "("; }else if (pGroup==6){ xValue = ")("; }else if (pGroup==4){ xValue = ")"; }else if (pGroup==2){ xValue = "-"; } if (!pIsNumber){ pValue = ""; } }else{ if (!pIsNumber){ return null; } if (pGroup==1){ xMin = 4; xMax = 4; }else if (pGroup==3){ xMin = 3; xMax = 5; //DDD }else if (pGroup==5){ xMin = 2; xMax = 3; //DDI }else if (pGroup==7){ xMin = 1; xMax = 3; } xB = xE - xMax +1; if (xB<=0){ xB=1; } //Valor utilizado xValue = DBSString.getSubString(pValue, xB, xE); //DDD e DDI: Retira os zeros a esquerda if (pGroup==5 || pGroup==7){ xValue = getFormattedNumber(xValue, NUMBER_SIGN.NONE, " } if (xValue.equals("0") || xValue.length() < xMin){ return null; //Erro } //Resto pValue = DBSString.getSubString(pValue, 1, xB-1); } pGroup++; //Adiciona a string pFormattedNumber.insert(0, xValue); pIsNumber = pValue.matches(REGEX.ONLY_NUMBERS); return pvPhoneNumber(pFormattedNumber, pGroup, pValue, pIsNumber); } /** * Retorna o Locale corrente, dando prioridade ao locale da view e depois do sistema. * @return */ public static Locale getLocale(){ Locale xLocale; if (FacesContext.getCurrentInstance() != null){ xLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); }else{ xLocale = DBSNumber.LOCALE_PTBR; //Locale.getDefault(); } return xLocale; } }
package br.com.dbsoft.util; import java.awt.geom.Point2D; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; import java.util.List; import java.util.Locale; import org.apache.commons.math3.distribution.NormalDistribution; import org.apache.commons.math3.stat.correlation.Covariance; import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation; import org.apache.commons.math3.stat.descriptive.moment.Variance; import org.apache.commons.math3.stat.descriptive.rank.Percentile; import org.apache.log4j.Logger; public class DBSNumber { protected static Logger wLogger = Logger.getLogger(DBSNumber.class); public static Locale LOCALE_PTBR = new Locale("pt", "BR"); public static Double PIDiameter = Math.PI * 2; public static Double PIDiameterFactor = PIDiameter / 100; public static BigDecimal subtract(Object... pX){ BigDecimal xX = BigDecimal.ZERO; for (int i=0; i < pX.length; i++){ if (i==0){ xX = toBigDecimal(pX[i]); }else{ xX = xX.subtract(toBigDecimal(pX[i])); } } return toBigDecimal(xX); } public static BigDecimal add(Object... pX){ BigDecimal xX = BigDecimal.ZERO; for (int i=0; i < pX.length; i++){ if (i==0){ xX = toBigDecimal(pX[i]); }else{ xX = xX.add(toBigDecimal(pX[i])); } } return toBigDecimal(xX); } public static BigDecimal multiply(Object... pX){ BigDecimal xX = BigDecimal.ZERO; for (int i=0; i < pX.length; i++){ if (i==0){ xX = toBigDecimal(pX[i]); }else{ xX = xX.multiply(toBigDecimal(pX[i])); } } return toBigDecimal(xX); } public static BigDecimal divide(Object... pX){ BigDecimal xX = BigDecimal.ZERO; for (int i=0; i < pX.length; i++){ if (i==0){ xX = toBigDecimal(pX[i]); }else{ BigDecimal xD = toBigDecimal(pX[i]); //Teste para evitar exception di division by zero if (xD.compareTo(BigDecimal.ZERO) != 0){ xX = xX.divide(xD, 30, RoundingMode.HALF_UP); }else{ return null; } } } return toBigDecimal(xX); } public static BigDecimal exp(Object pBase, Object pExpoente){ Double xX = toDouble(pBase); Double xY = toDouble(pExpoente); return toBigDecimal(Math.pow(xX, xY)); } public static BigDecimal exp(Object pExpoente){ Double xBase = 2.71828182845904D; return exp(xBase, pExpoente); } /** * Logaritmo Natural * @param pX Valor que se deseja retornar o Log * @return Restorna log do pX */ public static BigDecimal log(Object pX){ if (DBSObject.isEmpty(pX)){ return null; } Double xX = toDouble(pX); return toBigDecimal(Math.log(xX)); } /** * Logaritmo na Base 10 * @param pX Valor que se deseja retornar o Log * @return Restorna log do pX */ public static BigDecimal log10(Object pX){ if (DBSObject.isEmpty(pX)){ return null; } Double xX = toDouble(pX); return toBigDecimal(Math.log10(xX)); } /** * Rais Quadrada * @param pX Valor que se deseja calcular a Raiz Quadrada * @return Retorno da Raiz quadrada de pX */ public static BigDecimal sqrt(Object pX) { return toBigDecimal(Math.sqrt(toDouble(pX))); } public static BigDecimal average(List<Double> pAmostra) { Double xMedia = 0D; if (DBSObject.isNull(pAmostra) || pAmostra.isEmpty()) { return toBigDecimal(xMedia); } for (Double xValor : pAmostra) { xMedia = add(xMedia,xValor).doubleValue(); } xMedia = divide(xMedia, pAmostra.size()).doubleValue(); return toBigDecimal(xMedia); } public static Point2D circlePoint(Point2D pCenter, Double pRadius, Double p2PIPercentual){ Point2D xX = new Point2D.Double(); xX.setLocation(DBSNumber.round(pCenter.getX() + (pRadius * Math.sin(p2PIPercentual)), 2), DBSNumber.round(pCenter.getY() - (pRadius * Math.cos(p2PIPercentual)), 2)); return xX; } /** * Retorna centro a partir da altura e largura * @param pWidth * @param pHeight * @return */ public static Point2D centerPoint(Double pWidth, Double pHeight){ Point2D xCentro = new Point2D.Double(); xCentro.setLocation((pWidth / 2D), (pHeight / 2D)); return xCentro; } public static BigDecimal desvioPadrao(List<Double> pAmostra) { Double xDesvioPadrao = 0D; double[] xArray = new double[pAmostra.size()]; StandardDeviation xSD = new StandardDeviation(); if (DBSObject.isNull(pAmostra) || pAmostra.isEmpty()) { return toBigDecimal(xDesvioPadrao); } for (int xI = 0; xI < pAmostra.size(); xI++) { xArray[xI] = pAmostra.get(xI); } xDesvioPadrao = xSD.evaluate(xArray); return toBigDecimal(xDesvioPadrao); } public static BigDecimal distribuicaoNormalInvertida(Double pNivelConfianca, Double pMedia, Double pDesvioPadrao) { Double xResultado = 0D; NormalDistribution xDistribution = new NormalDistribution(pMedia, pDesvioPadrao); xResultado = xDistribution.inverseCumulativeProbability(pNivelConfianca); return toBigDecimal(xResultado); } public static BigDecimal distribuicaoNormal(Double pValor, Double pMedia, Double pDesvioPadrao, boolean pCumulativo) { Double xResultado = 0D; NormalDistribution xDistribution = new NormalDistribution(pMedia, pDesvioPadrao); if (pCumulativo) { xResultado = xDistribution.cumulativeProbability(pValor); } else { xResultado = xDistribution.density(pValor); } return toBigDecimal(xResultado); } public static BigDecimal covariancia(List<Double> pAmostra1, List<Double> pAmostra2) { return covariancia(pAmostra1, pAmostra2, false); } public static BigDecimal covariancia(List<Double> pAmostra1, List<Double> pAmostra2, boolean pImparcial) { Double xResultado = 0D; double[] xArray1 = new double[pAmostra1.size()]; double[] xArray2 = new double[pAmostra2.size()]; Covariance xCovariance = new Covariance(); for (int xI = 0; xI < pAmostra1.size(); xI++) { xArray1[xI] = pAmostra1.get(xI); } for (int xI = 0; xI < pAmostra2.size(); xI++) { xArray2[xI] = pAmostra2.get(xI); } xResultado = xCovariance.covariance(xArray1, xArray2, pImparcial); return toBigDecimal(xResultado); } public static BigDecimal variancia(List<Double> pAmostra) { Double xResultado = 0D; double[] xArray = new double[pAmostra.size()]; Variance xVariancia = new Variance(); for (int xI = 0; xI < pAmostra.size(); xI++) { xArray[xI] = pAmostra.get(xI); } xResultado = xVariancia.evaluate(xArray); return toBigDecimal(xResultado); } public static BigDecimal percentil(List<Double> pAmostra, Double pQuantile) { Double xResultado = 0D; double[] xAmostra = new double[pAmostra.size()]; Percentile xPercentil = new Percentile().withEstimationType(Percentile.EstimationType.R_7); for (int xI = 0; xI < pAmostra.size(); xI++) { xAmostra[xI] = pAmostra.get(xI); } xResultado = xPercentil.evaluate(xAmostra, pQuantile); return toBigDecimal(xResultado); } /** * Emulates Excel/Calc's PMT(interest_rate, number_payments, PV, FV, Type) * function, which calculates the mortgage or annuity payment / yield per * period. * * @param pI - periodic interest rate represented as a decimal. * @param pNPer - number of total payments / periods. * @param pPV - present value -- borrowed or invested principal. * @param pFV - future value of loan or annuity. * @param pType - when payment is made: beginning of period is 1; end, 0. * @return <code>double</code> representing periodic payment amount. */ public static BigDecimal pmt(double pI, int pNPer, double pPV, double pFV, int pType) { // pmt = i / ((1 + i)^N - 1) * -(pv * (1 + i)^N + fv) double xPmt = pI / (Math.pow(1 + pI, pNPer) - 1) * -(pPV * Math.pow(1 + pI, pNPer) + pFV); // account for payments at beginning of period versus end. if (pType == 1) { xPmt /= (1 + pI); } // return results to caller. return toBigDecimal(xPmt); } /** * Overloaded pmt() call omitting type, which defaults to 0. * * @see #pmt(double, int, double, double, int) */ public static BigDecimal pmt(double r, int nper, double pv, double fv) { return pmt(r, nper, pv, fv, 0); } /** * Overloaded pmt() call omitting fv and type, which both default to 0. * * @see #pmt(double, int, double, double, int) */ public static BigDecimal pmt(double r, int nper, double pv) { return pmt(r, nper, pv, 0); } /** * Emulates Excel/Calc's IPMT(interest_rate, period, number_payments, PV, * FV, Type) function, which calculates the portion of the payment at a * given period that is the interest on previous balance. * * @param r * - periodic interest rate represented as a decimal. * @param per * - period (payment number) to check value at. * @param nper * - number of total payments / periods. * @param pv * - present value -- borrowed or invested principal. * @param fv * - future value of loan or annuity. * @param type * - when payment is made: beginning of period is 1; end, 0. * @return <code>double</code> representing interest portion of payment. * * @see #pmt(double, int, double, double, int) * @see #fv(double, int, double, double, int) */ public static BigDecimal ipmt(double r, int per, int nper, double pv, double fv, int type) { // Prior period (i.e., per-1) balance times periodic interest rate. // i.e., ipmt = fv(r, per-1, c, pv, type) * r // where c = pmt(r, nper, pv, fv, type) double ipmt = fv(r, per - 1, pmt(r, nper, pv, fv, type).doubleValue(), pv, type).doubleValue() * r; // account for payments at beginning of period versus end. if (type == 1) ipmt /= (1 + r); // return results to caller. return toBigDecimal(ipmt); } /** * Emulates Excel/Calc's FV(interest_rate, number_payments, payment, PV, * Type) function, which calculates future value or principal at period N. * * @param r * - periodic interest rate represented as a decimal. * @param nper * - number of total payments / periods. * @param c * - periodic payment amount. * @param pv * - present value -- borrowed or invested principal. * @param type * - when payment is made: beginning of period is 1; end, 0. * @return <code>double</code> representing future principal value. */ public static BigDecimal fv(double r, int nper, double c, double pv, int type) { // account for payments at beginning of period versus end. // since we are going in reverse, we multiply by 1 plus interest rate. if (type == 1) c *= (1 + r); // fv = -(((1 + r)^N - 1) / r * c + pv * (1 + r)^N); double fv = -((Math.pow(1 + r, nper) - 1) / r * c + pv * Math.pow(1 + r, nper)); // return results to caller. return toBigDecimal(fv); } /** * Overloaded fv() call omitting type, which defaults to 0. * * @see #fv(double, int, double, double, int) */ public static BigDecimal fv(double r, int nper, double c, double pv) { return fv(r, nper, c, pv); } /** * Emulates Excel/Calc's PPMT(interest_rate, period, number_payments, PV, * FV, Type) function, which calculates the portion of the payment at a * given period that will apply to principal. * * @param r * - periodic interest rate represented as a decimal. * @param per * - period (payment number) to check value at. * @param nper * - number of total payments / periods. * @param pv * - present value -- borrowed or invested principal. * @param fv * - future value of loan or annuity. * @param type * - when payment is made: beginning of period is 1; end, 0. * @return <code>double</code> representing principal portion of payment. * * @see #pmt(double, int, double, double, int) * @see #ipmt(double, int, int, double, double, int) */ public static BigDecimal ppmt(double r, int per, int nper, double pv, double fv, int type) { // Calculated payment per period minus interest portion of that period. // i.e., ppmt = c - i // where c = pmt(r, nper, pv, fv, type) // and i = ipmt(r, per, nper, pv, fv, type) return subtract(pmt(r, nper, pv, fv, type), ipmt(r, per, nper, pv, fv, type)); } public static BigDecimal TIR(double[] pFluxo, int[] pPeriodo) { return TIR(pFluxo, pPeriodo, 0.00001); } public static BigDecimal TIR(double[] pFluxo, int[] pPeriodo, double pVPL) { int xIteracoesMaxima = 20; double xPrecisao = 1E-7; double x0 = pVPL; double x1; int xCount = 0; while (xCount < xIteracoesMaxima) { //pFluxo.length double xValue = 0; double fDerivado = 0; for (int xIndice = 0; xIndice < pFluxo.length; xIndice++) { if (DBSObject.isEmpty(pPeriodo)) { xValue += pFluxo[xIndice] / Math.pow(1.0 + x0, xIndice); fDerivado += -xIndice * pFluxo[xIndice] / Math.pow(1.0 + x0, xIndice + 1); } else { xValue += pFluxo[xIndice] / Math.pow(1.0 + x0, pPeriodo[xIndice]); fDerivado += -(pPeriodo[xIndice] * pFluxo[xIndice]) / Math.pow(1.0 + x0, pPeriodo[xIndice] + 1); } } x1 = x0 - xValue/fDerivado; if (Math.abs(x1 - x0) <= xPrecisao) { return toBigDecimal(x1); } x0 = x1; ++xCount; } return BigDecimal.ZERO; } public static BigDecimal calculaPuMedio(Object pPuAtual, Object pQuantidadeAtual, Object pPuOperado, Object pQuantidadeOperada, boolean pExclusao){ if (pPuAtual == null || pQuantidadeAtual == null || pPuOperado == null || pQuantidadeOperada == null){ return null; } Double xSaldo; Double xFinOperado; Double xFinAtual; BigDecimal xPuAtual = toBigDecimal(pPuAtual); BigDecimal xPuOperado = toBigDecimal(pPuOperado); Double xQuantidadeAtual = toDouble(pQuantidadeAtual); Double xQuantidadeOperada = toDouble(pQuantidadeOperada); xSaldo = add(xQuantidadeAtual, xQuantidadeOperada).doubleValue(); if (xSaldo.equals(0D)){ return xPuAtual; } else { if (isRealizacao(pQuantidadeAtual, pQuantidadeOperada) == pExclusao){ xFinOperado = multiply(pQuantidadeOperada, pPuOperado).doubleValue(); xFinAtual = multiply(pQuantidadeAtual, pPuAtual).doubleValue(); return divide(add(xFinOperado, xFinAtual), xSaldo); } else { if (isPosicaoVirada(pQuantidadeAtual, pQuantidadeOperada)){ return xPuOperado; } else { return xPuAtual; } } } } public static boolean isPosicaoVirada(Object pQuantidadeAtual, Object pQuantidadeOperada){ if (pQuantidadeAtual == null || pQuantidadeOperada == null){ return false; } Double xSaldo; Double xQuantidadeAtual = toDouble(pQuantidadeAtual); Double xQuantidadeOperada = toDouble(pQuantidadeOperada); xSaldo = add(xQuantidadeAtual, xQuantidadeOperada).doubleValue(); if (!xSaldo.equals(0D) && (sign(xSaldo).intValue() != sign(xQuantidadeAtual).intValue() || xQuantidadeAtual.equals(0D))){ return true; } return false; } public static boolean isRealizacao(Object pQuantidadeAtual, Object pQuantidadeOperada){ if (pQuantidadeAtual == null || pQuantidadeOperada == null){ return false; } Double xQuantidadeAtual = toDouble(pQuantidadeAtual); Double xQuantidadeOperada= toDouble(pQuantidadeOperada); if ((xQuantidadeAtual < 0 && xQuantidadeOperada > 0) || (xQuantidadeAtual > 0 && xQuantidadeOperada < 0)){ return true; } return false; } /** * Sinal do valor * @param pValue Valor que se deseja conhecer o sinal * @return Retorna 0 = Zero / 1 = Positivo / -1 = Negativo */ public static Integer sign(Object pValue){ return toBigDecimal(pValue).signum(); } public static BigDecimal random(){ return toBigDecimal(Math.random()); } /** * Retornar o valor sem sinal * @param pValue Valor que se deseja retinar o sinal * @return Restorna valor sem sinal * @throws SecurityException * @throws NoSuchMethodException */ public static Double abs(Double pValue) { return pvAbs(pValue, Double.class); } /** * Retornar o valor sem sinal * @param pValue Valor que se deseja retinar o sinal * @return Restorna valor sem sinal * @throws SecurityException * @throws NoSuchMethodException */ public static Long abs(Long pValue) { return pvAbs(pValue, Long.class); } /** * Retornar o valor sem sinal * @param pValue Valor que se deseja retinar o sinal * @return Restorna valor sem sinal * @throws SecurityException * @throws NoSuchMethodException */ public static Integer abs(Integer pValue) { return pvAbs(pValue, Integer.class); } /** * Retornar o valor sem sinal * @param pValue Valor que se deseja retinar o sinal * @return Restorna valor sem sinal * @throws SecurityException * @throws NoSuchMethodException */ public static BigDecimal abs(Object pValue) { return pvAbs(pValue, Object.class); } public static Double trunc(Double pValue, Integer pDecimalPlaces) { return pvTrunc(pValue, pDecimalPlaces, Double.class); } public static Long trunc(Long pValue, Integer pDecimalPlaces) { return pvTrunc(pValue, pDecimalPlaces, Long.class); } public static Integer trunc(Integer pValue, Integer pDecimalPlaces) { return pvTrunc(pValue, pDecimalPlaces, Integer.class); } public static BigDecimal trunc(Object pValue, Integer pDecimalPlaces) { return pvTrunc(pValue, pDecimalPlaces, Object.class); } public static Double round(Double pValue, Integer pDecimalPlaces) { return pvRound(pValue, pDecimalPlaces, Double.class); } public static Long round(Long pValue, Integer pDecimalPlaces) { return pvRound(pValue, pDecimalPlaces, Long.class); } public static Integer round(Integer pValue, Integer pDecimalPlaces) { return pvRound(pValue, pDecimalPlaces, Integer.class); } public static BigDecimal round(Object pValue, Integer pDecimalPlaces) { return pvRound(pValue, pDecimalPlaces, Object.class); } /** * Retorna valor inteiro * @param pValue Valor que se deseja a parte inteira * @return Retorna valor inteiro */ public static Double inte(Double pValue){ return trunc(pValue, 0); } /** * Retorna valor inteiro * @param pValue Valor que se deseja a parte inteira * @return Retorna valor inteiro */ public static Long inte(Long pValue){ return trunc(pValue, 0); } /** * Retorna valor inteiro * @param pValue Valor que se deseja a parte inteira * @return Retorna valor inteiro */ public static Integer inte(Integer pValue){ return trunc(pValue, 0); } /** * Retorna valor inteiro * @param pValue Valor que se deseja a parte inteira * @return Retorna valor inteiro */ public static BigDecimal inte(Object pValue){ return trunc(pValue, 0); } /** * Retorna valor negativo ou positivo conforme paremeto <b>pPositive<b/> independetemente do sinal do valor recebido. * @param pValue * @param pSign 1 = Positivo / -1 = Negativo * @return */ public static Double toPositive(Double pValue, Boolean pPositive){ return pvToPositive(pValue, pPositive, Double.class); } /** * Retorna valor negativo ou positivo conforme paremeto <b>pPositive<b/> independetemente do sinal do valor recebido. * @param pValue * @param pSign 1 = Positivo / -1 = Negativo * @return */ public static Long toPositive(Long pValue, Boolean pPositive){ return pvToPositive(pValue, pPositive, Long.class); } /** * Retorna valor negativo ou positivo conforme paremeto <b>pPositive<b/> independetemente do sinal do valor recebido. * @param pValue * @param pSign 1 = Positivo / -1 = Negativo * @return */ public static Integer toPositive(Integer pValue, Boolean pPositive){ return pvToPositive(pValue, pPositive, Integer.class); } /** * Retorna valor negativo ou positivo conforme paremeto <b>pPositive<b/> independetemente do sinal do valor recebido. * @param pValue * @param pSign 1 = Positivo / -1 = Negativo * @return */ public static BigDecimal toPositive(Object pValue, Boolean pPositive){ return pvToPositive(pValue, pPositive, Object.class); } public static boolean isNumber(String pTextoNumerico){ if (pTextoNumerico == null){ return false; } return pTextoNumerico.matches("([-+]?\\d*\\.*\\,*\\d+)([eE][+-]?[0-9]+)?$"); } public static boolean isInteger(Object pValue){ Integer xInteiro = toInteger(pValue); if (xInteiro != null){ if (xInteiro.toString().trim().equals(pValue.toString().trim())){ return true; } } return false; } public static String getOnlyNumber(String pTexto){ if (DBSObject.isEmpty(pTexto)){ return null; } String xA = ""; String xB = ""; for (int x=0;x<pTexto.length();x++){ xB = pTexto.substring(x, x+1); if (isNumber(xB)){ xA += xB; } } return DBSString.getNotEmpty(xA, "0"); } public static BigDecimal toNumber(String pString, Integer pDecimalPlaces){ if (DBSObject.isEmpty(pString) || DBSObject.isEmpty(pDecimalPlaces)){ return null; } BigDecimal xD; BigDecimal xE = exp(10D, pDecimalPlaces.doubleValue()); if (isNumber(pString)){ xD = toBigDecimal(pString); xD = divide(xD, xE); xD = round(xD, pDecimalPlaces); return xD; } else{ return null; } } public static BigDecimal toBigDecimal(Object pValue) { return toBigDecimal(pValue, 0); } public static BigDecimal toBigDecimal(Object pValue, Object pDefaultValue) { try{ if (DBSObject.isEmpty(pValue)){ if (pDefaultValue == null){ return null; }else{ pValue = pDefaultValue; } } BigDecimal xValue; if (pValue instanceof Number) { xValue = new BigDecimal(DBSString.getSubString(pValue.toString(), 1, 90), MathContext.UNLIMITED); if (xValue.compareTo(BigDecimal.ZERO) == 0){ xValue = BigDecimal.ZERO; } } else if (pValue instanceof String) { Number xN = pvStringToNumberFormat((String) pValue, LOCALE_PTBR); if (xN != null){ xValue = new BigDecimal(DBSString.getSubString(xN.toString(), 1, 90), MathContext.UNLIMITED); }else{ xValue = null; } } else { return null; } return pvBigDecimalStripTrailingZeros(xValue); }catch(Exception e){ wLogger.error(e); return null; } } /** * Converte para Long.<br/> * Se for nulo, retorna Zero.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * Se for nulo, retorna Zero.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @return Retorna o valor convertido ou o 0(zero), caso o valor informado seja nulo. */ public static Long toLong(Object pValue) { return toLong(pValue, 0L); } /** * Converte para Long.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @param pDefaultValue * @return Retorna o valor convertido ou o valor informado em pDefaultValue caso o valor a ser convertido seja nulo */ public static Long toLong(Object pValue, Long pDefaultValue) { if (DBSObject.isEmpty(pValue)) { return pDefaultValue; } if (pValue instanceof Integer) { return new Long((Integer) pValue); } else if (pValue instanceof BigDecimal) { return ((BigDecimal) pValue).longValue(); } else if (pValue instanceof Double) { return ((Double) pValue).longValue(); } else if (pValue instanceof Float) { return ((Float) pValue).longValue(); } else if (pValue instanceof Long) { return (Long) pValue; } else if (pValue instanceof Boolean) { if (!(Boolean) pValue) { return 0L; } else { return -1L; } } else if (pValue instanceof String) { Number xN = pvStringToNumberFormat((String) pValue, LOCALE_PTBR); if (xN != null){ return xN.longValue(); } } return null; } /** * Converte para Integer.<br/> * Se for nulo, retorna Zero.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @return Retorna o valor convertido ou o 0(zero), caso o valor informado seja nulo. */ public static Integer toInteger(Object pValue) { return toInteger(pValue, 0); } /** * Converte para Integer * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @param pDefaultValue * @return Retorna o valor convertido ou o valor informado em pDefaultValue caso o valor a ser convertido seja nulo */ public static Integer toInteger(Object pValue, Integer pDefaultValue) { if (DBSObject.isEmpty(pValue)) { return pDefaultValue; } if (pValue instanceof Integer) { return (Integer) pValue; } else if (pValue instanceof BigDecimal) { return ((BigDecimal) pValue).intValue(); } else if (pValue instanceof Double) { return ((Double) pValue).intValue(); } else if (pValue instanceof Float) { return ((Float) pValue).intValue(); } else if (pValue instanceof Long) { return ((Long) pValue).intValue(); } else if (pValue instanceof Boolean) { if (!(Boolean) pValue) { return 0; } else { return -1; } } else if (pValue instanceof String) { Number xN = pvStringToNumberFormat((String) pValue, LOCALE_PTBR); if (xN != null){ return xN.intValue(); } } return null; } /** * Converte para Double.<br/> * Se for nulo, retorna Zero.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @return Retorna o valor convertido ou o valor 0.0, caso o valor informado seja nulo */ public static Double toDouble(Object pValue) { return toDouble(pValue, 0D); } /** * Converte para Double.<br/> * Utiliza a localidade para identificar qual o sinal da casa decimal * caso o valor informado seja uma String. * @param pValue * @param pDefaultValue * @return Retorna o valor convertido ou o valor informado em pDefaultValue caso o valor a ser convertido seja nulo */ public static Double toDouble(Object pValue, Double pDefaultValue) { return toDouble(pValue, pDefaultValue, LOCALE_PTBR); } public static Double toDouble(Object pValue, Double pDefaultValue, Locale pLocale) { if (DBSObject.isEmpty(pValue) || pValue.equals("")) { return pDefaultValue; } if (pValue instanceof Double) { return (Double) pValue; } else if (pValue instanceof BigDecimal) { return ((BigDecimal) pValue).doubleValue(); } else if (pValue instanceof Integer) { return ((Integer)pValue).doubleValue(); } else if (pValue instanceof Long) { return ((Long)pValue).doubleValue(); } else if (pValue instanceof String) { Number xN = pvStringToNumberFormat((String) pValue, pLocale); if (xN != null){ return xN.doubleValue(); } } return null; } public static Double toDoubleNotZero(Object pDado){ return toDoubleNotZero(pDado, 1D); } public static Double toDoubleNotZero(Object pDado, Double pDefaultValue){ if (DBSObject.isEmpty(pDefaultValue)){ pDefaultValue = 1D; } Double xValue = toDouble(pDado, pDefaultValue); if(DBSObject.isEmpty(xValue) || xValue.equals(0D)){ xValue = pDefaultValue; } return xValue; } public static BigDecimal toBigDecimalNotZero(Object pDado){ return toBigDecimalNotZero(pDado, BigDecimal.ONE); } public static BigDecimal toBigDecimalNotZero(Object pDado, BigDecimal pDefaultValue){ if (DBSObject.isEmpty(pDefaultValue)){ pDefaultValue = BigDecimal.ONE; } BigDecimal xValue = toBigDecimal(pDado, pDefaultValue); if(DBSObject.isEmpty(xValue) || xValue.equals(BigDecimal.ZERO)){ xValue = pDefaultValue; } return pvBigDecimalStripTrailingZeros(xValue); } // PRIVATE /** * Rertorna valor absoluto * @param pValue * @return */ private static <T extends Number> T pvAbs(Object pValue, Class<?> pClass){ BigDecimal xValue = toBigDecimal(pValue); xValue = xValue.abs(); return pvConvertToClass(xValue, pClass); } /** * Rertorna valor truncado * @param pValue * @return */ private static <T extends Number> T pvTrunc(Object pValue, Integer pDecimalPlaces, Class<?> pClass){ BigDecimal xValue; if (pDecimalPlaces==null){ pDecimalPlaces = 0; } xValue = toBigDecimal(pValue).setScale(pDecimalPlaces, RoundingMode.FLOOR); xValue = toBigDecimal(xValue); return pvConvertToClass(xValue, pClass); } /** * Rertorna valor truncado * @param pValue * @return */ private static <T extends Number> T pvRound(Object pValue, Integer pDecimalPlaces, Class<?> pClass){ BigDecimal xValue; if (pDecimalPlaces==null){ pDecimalPlaces = 0; } xValue = toBigDecimal(pValue).setScale(pDecimalPlaces, RoundingMode.HALF_UP); xValue = toBigDecimal(xValue); return pvConvertToClass(xValue, pClass); } private static <T extends Number> T pvToPositive(Object pValue, Boolean pPositive, Class<?> pClass){ if (pClass==null || pValue== null){ return null; } BigDecimal xValue = toBigDecimal(pValue); if (pPositive != null){ if (pPositive){ xValue = abs(xValue); }else{ xValue = multiply(abs(xValue), -1); } } return pvConvertToClass(xValue, pClass); } /** * Converte para o valor recebido para o tipo informado * @param pValue * @param pClass * @return */ @SuppressWarnings("unchecked") private static <T extends Number> T pvConvertToClass(BigDecimal pValue, Class<?> pClass){ BigDecimal xValue = pvBigDecimalStripTrailingZeros(pValue); if (DBSObject.isEmpty(pValue)){ return null; } if (Double.class.isAssignableFrom(pClass)){ return (T) toDouble(xValue); }else if (Long.class.isAssignableFrom(pClass)){ return (T) toLong(xValue); }else if (Integer.class.isAssignableFrom(pClass)){ return (T) toInteger(xValue); }else{ return (T) xValue; } } private static BigDecimal pvBigDecimalStripTrailingZeros(BigDecimal pValue){ return new BigDecimal(pValue.stripTrailingZeros().toPlainString(), MathContext.UNLIMITED); } /** * Converte string para double, considerando a localidade BR(",") para o sinal decimal.<br/> * @param pValue * @return */ private static Number pvStringToNumberFormat(String pValue, Locale pLocale){ Boolean xPerc = (pValue !=null && pValue.indexOf("%") > 0); DecimalFormat xNF = (DecimalFormat) DecimalFormat.getInstance(pLocale); xNF.setParseBigDecimal(true); xNF.setMaximumFractionDigits(30); xNF.setRoundingMode(RoundingMode.HALF_UP); xNF.setDecimalSeparatorAlwaysShown(false); try { if (pValue!=null){ if (xPerc){ return (xNF.parse(pValue).doubleValue() / 100D); }else{ return xNF.parse(pValue); } }else{ return null; } } catch (ParseException e) { return null; } } }
package ca.phcri; import ij.IJ; import ij.ImagePlus; import ij.WindowManager; import ij.gui.DialogListener; import ij.gui.GenericDialog; import ij.gui.Overlay; import ij.gui.Roi; import ij.gui.ShapeRoi; import ij.measure.Calibration; import ij.plugin.PlugIn; import ij.text.TextPanel; import ij.text.TextWindow; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.geom.GeneralPath; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class CombinedGridsPlugin implements PlugIn, DialogListener { private final static String[] colors = { "Red", "Green", "Blue", "Magenta", "Cyan", "Yellow", "Orange", "Black", "White" }; private static String color = "Blue"; private final static int COMBINED = 0, DOUBLE_LATTICE = 1, LINES = 2, HLINES = 3, CROSSES = 4, POINTS = 5; private final static String[] types = { "Combined Point", "Double Lattice", "Lines", "Horizontal Lines", "Crosses", "Points" }; private static String type = types[COMBINED]; private static double areaPerPoint; private final static int ONE_TO_FOUR = 0, ONE_TO_NINE = 1, ONE_TO_SIXTEEN = 2, ONE_TO_TWENTYFIVE = 3, ONE_TO_THIRTYSIX = 4; private final static String[] ratioChoices = { "1:4", "1:9", "1:16", "1:25", "1:36" }; private static String gridRatio = ratioChoices[ONE_TO_FOUR]; private final static String[] radiobuttons = { "Random Offset", "Fixed Position", "Manual Input" }; private final static int RANDOM = 0, FIXED = 1, MANUAL = 2; private String radiochoice = radiobuttons[RANDOM]; private final static String[] applyChoices = { "One Grid for All Slices", "Different Grids for Each Slice", "One Grid for Current Slice"}; private final static int ONEforALL = 0, DIFFERENTforEACH = 1, CURRENT = 2; private static String applyTo = applyChoices[DIFFERENTforEACH]; private static Component[] components; // this is to select components in the dialog box private final static int[] ratioField = { 4, 5 }; private final static int[] combinedGridFields = { 14, 15, 16, 17 }; private final static int[] parameterFieldsOff = { 10, 11, 12, 13, 14, 15, 16, 17 }; private final static int[] xstartField = { 10, 11 }; private final static int[] ystartField = { 12, 13 }; private static boolean showGridSwitch = true; private Random random = new Random(System.currentTimeMillis()); private ImagePlus imp; private double tileWidth, tileHeight; private int width, height; private int xstart, ystart; private int xstartCoarse, ystartCoarse, coarseGridX, coarseGridY; private int linesV, linesH; private double pixelWidth = 1.0, pixelHeight = 1.0; private String units; private String err = ""; //private ArrayList<Roi> gridRoisList; //private ArrayList<String> gridParametersList; private Roi[] gridRoiArray; private String[] gridParameterArray; private int totalSlice; @Override public void run(String arg) { if (IJ.versionLessThan("1.47")) return; imp = IJ.getImage(); showDialog(); } void removeGrid(){ Overlay ol = imp.getOverlay(); if(ol != null){ Roi[] elements = ol.toArray(); for(Roi element : elements){ if(element.getName() != null && element.getName().startsWith("grid")){ ol.remove(element); } } } } void showGrid(Roi[] rois) { removeGrid(); if(rois != null) { Overlay ol = imp.getOverlay(); if(ol == null) ol = new Overlay(); for(Roi roi : rois){ ol.add(roi); } //just for debugging Roi[] olElements = ol.toArray(); for (Roi roi : olElements) IJ.log(type + " " + roi.getName() + ": " + roi.getTypeAsString() + " at slice " + roi.getPosition()); imp.setOverlay(ol); IJ.log("Grid Overlaid"); } } // methods to form grids GeneralPath drawPoints() { int one = 1; int two = 2; GeneralPath path = new GeneralPath(); for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - two, y - one); path.lineTo(x - two, y + one); path.moveTo(x + two, y - one); path.lineTo(x + two, y + one); path.moveTo(x - one, y - two); path.lineTo(x + one, y - two); path.moveTo(x - one, y + two); path.lineTo(x + one, y + two); } } return path; } GeneralPath drawCrosses() { GeneralPath path = new GeneralPath(); float arm = 5; for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - arm, y); path.lineTo(x + arm, y); path.moveTo(x, y - arm); path.lineTo(x, y + arm); } } return path; } GeneralPath drawCombined() { GeneralPath path = new GeneralPath(); float arm = 5; float pointSizeCoarse = 10; float armCoarse = pointSizeCoarse / 2; for (int h = 0; h < linesV; h++) { for (int v = 0; v < linesH; v++) { float x = (float) (xstart + h * tileWidth); float y = (float) (ystart + v * tileHeight); path.moveTo(x - arm, y); path.lineTo(x + arm, y); path.moveTo(x, y - arm); path.lineTo(x, y + arm); if ((h % coarseGridX == 0) && (v % coarseGridY == 0)) { float centerX = (float) (xstart + xstartCoarse * tileWidth + h * tileWidth); float centerY = (float) (ystart + ystartCoarse * tileHeight + v * tileHeight); // drawing a coarse point by lines path.moveTo(centerX - pointSizeCoarse, centerY - armCoarse); path.lineTo(centerX - pointSizeCoarse, centerY + armCoarse); path.moveTo(centerX + pointSizeCoarse, centerY - 0); path.lineTo(centerX + pointSizeCoarse, centerY + armCoarse); path.moveTo(centerX - armCoarse, centerY - pointSizeCoarse); path.lineTo(centerX + 0, centerY - pointSizeCoarse); path.moveTo(centerX - armCoarse, centerY + pointSizeCoarse); path.lineTo(centerX + armCoarse, centerY + pointSizeCoarse); } } } return path; } //Drawing curve in this method is the potential problem. GeneralPath drawDoubleLattice() { GeneralPath path = new GeneralPath(); float rad = 14; float radkappa = (float) (rad * 0.5522847498); /* for (int i = 0; i < linesV; i++) { float xoff = (float) (xstart + i * tileWidth); path.moveTo(xoff, 0f); path.lineTo(xoff, height); } for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } */ /* for (int h = 0; h < linesV; h++) { //linesV for vertical lines for (int v = 0; v < linesH; v++) { //linesH for horizontal lines */ IJ.log("drow DoubleLattice"); for (int h = 0; h < 1; h++) { //linesV for vertical lines for (int v = 0; v < 1; v++) { //linesH for horizontal lines if ((h % coarseGridX == 0) && (v % coarseGridY == 0)) { float centerX = (float) (xstart + xstartCoarse * tileWidth + h * tileWidth); float centerY = (float) (ystart + ystartCoarse * tileHeight + v * tileHeight); // drawing curve for coarse grid path.moveTo(centerX, centerY - rad); IJ.log("center " + centerX); IJ.log("centerY " + centerY); IJ.log("rad " + rad); IJ.log("radkappa " + radkappa +"\n"); path.curveTo(centerX - radkappa, centerY - rad, centerX - rad, centerY - radkappa, centerX - rad, centerY); //path.curveTo(centerX - rad, centerY + radkappa, centerX - radkappa, centerY + rad, centerX, centerY + rad); //path.curveTo(centerX + radkappa, centerY + rad, centerX + rad, centerY + radkappa, centerX + rad, centerY); } } } return path; } GeneralPath drawLines() { GeneralPath path = new GeneralPath(); for (int i = 0; i < linesV; i++) { float xoff = (float) (xstart + i * tileWidth); path.moveTo(xoff, 0f); path.lineTo(xoff, height); } for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } return path; } GeneralPath drawHorizontalLines() { GeneralPath path = new GeneralPath(); for (int i = 0; i < linesH; i++) { float yoff = (float) (ystart + i * tileHeight); path.moveTo(0f, yoff); path.lineTo(width, yoff); } return path; } // end of methods for drawing grids void showDialog() { width = imp.getWidth(); height = imp.getHeight(); Calibration cal = imp.getCalibration(); int places; if (cal.scaled()) { pixelWidth = cal.pixelWidth; pixelHeight = cal.pixelHeight; units = cal.getUnits(); places = 2; } else { pixelWidth = 1.0; pixelHeight = 1.0; units = "pixels"; places = 0; } if (areaPerPoint == 0.0) // default to 9x9 grid areaPerPoint = (width * cal.pixelWidth * height * cal.pixelHeight) / 81.0; totalSlice = imp.getStackSize(); // get values in a dialog box GenericDialog gd = new GenericDialog("Grid..."); gd.addChoice("Grid Type:", types, type); gd.addNumericField("Area per Point:", areaPerPoint, places, 6, units + "^2"); gd.addChoice("Ratio:", ratioChoices, gridRatio); gd.addChoice("Color:", colors, color); gd.addRadioButtonGroup("Grid Location", radiobuttons, 3, 1, radiochoice); gd.addNumericField("xstart:", 0, 0); gd.addNumericField("ystart:", 0, 0); gd.addNumericField("xstartCoarse:", 0, 0); gd.addNumericField("ystartCoarse:", 0, 0); gd.addCheckbox("Show a Grid Switch if none exists", showGridSwitch); if(imp.getStackSize() > 1) gd.addRadioButtonGroup("The way to apply grid(s) to a Stack", applyChoices, 3, 1, applyTo); // to switch enable/disable for parameter input boxes components = gd.getComponents(); enableFields(); gd.addDialogListener(this); gd.showDialog(); if (gd.wasCanceled()) showGrid(null); if (gd.wasOKed()) { if ("".equals(err)) { showGridParameters(); if (showGridSwitch && !gridSwitchExist()){ Grid_Switch gs = new Grid_Switch(); gs.gridSwitch(); } } else { IJ.error("Grid", err); showGrid(null); } } } // event control for the dialog box @Override public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) { type = gd.getNextChoice(); areaPerPoint = gd.getNextNumber(); gridRatio = gd.getNextChoice(); color = gd.getNextChoice(); radiochoice = gd.getNextRadioButton(); xstart = (int) gd.getNextNumber(); ystart = (int) gd.getNextNumber(); xstartCoarse = (int) gd.getNextNumber(); ystartCoarse = (int) gd.getNextNumber(); showGridSwitch = gd.getNextBoolean(); if(imp.getStackSize() > 1) applyTo = gd.getNextRadioButton(); err = ""; IJ.showStatus(err); gridParameterArray = new String[totalSlice]; gridRoiArray = new Roi[totalSlice]; //gridRoisListReset(); minAreaCheck(); enableFields(); setCoarseGrids(); calculateTile(); if(applyChoices[DIFFERENTforEACH].equals(applyTo)){ int totalSlices = imp.getStackSize(); for (int i = 1; i <= totalSlices; i++){ calculateFirstGrid(); if(gd.invalidNumber()) return true; if (!"".equals(err) || gd.invalidNumber()) { IJ.showStatus(err); return true; } ShapeRoi gridRoi = getGridRoi(); addGridOnArray(gridRoi, i); saveGridParameters(i); } } else { calculateFirstGrid(); if (!"".equals(err) || gd.invalidNumber()) { IJ.showStatus(err); return true; } ShapeRoi gridRoi = getGridRoi(); if(applyChoices[ONEforALL].equals(applyTo)){ int totalSlices = imp.getStackSize(); for(int i = 1; i <= totalSlices; i++){ addGridOnArray(gridRoi, i); saveGridParameters(i); } } if(applyChoices[CURRENT].equals(applyTo)){ int currentSlice = imp.getCurrentSlice(); addGridOnArray(gridRoi, currentSlice); saveGridParameters(currentSlice); } } showGrid(gridRoiArray); IJ.log("showGrid Done"); return true; } void addGridOnArray(ShapeRoi gridRoi, int sliceIndex){ ShapeRoi sliceGridRoi = (ShapeRoi) gridRoi.clone(); sliceGridRoi.setName("grid" + sliceIndex); sliceGridRoi.setPosition(sliceIndex); gridRoiArray[sliceIndex - 1] = sliceGridRoi; } // if areaPerPoint is not too small, show an error void minAreaCheck(){ double minArea = (width * height) / 50000.0; if (type.equals(types[CROSSES]) && minArea < 144.0) minArea = 144.0; // to avoid overlap of grid points. // ((5 + 1) * 2) ^2 = 12^2 = 144 else if (type.equals(types[COMBINED]) && minArea < 484.0) minArea = 484.0; // As pointSizeCoarse = 10, //(10 + 1) * 2)^2 = 22^2 = 484 else if (type.equals(types[DOUBLE_LATTICE]) && minArea < 900.0) minArea = 900.0; // As rad = 14, ((14 + 1) * 2) ^2 = 900 else if (minArea < 16) minArea = 16.0; if (Double.isNaN(areaPerPoint) || areaPerPoint / (pixelWidth * pixelHeight) < minArea) { err = "\"Area per Point\" too small. \n"; areaPerPoint = 0; } } void enableFields(){ if (type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE])) fieldEnabler(ratioField, true); else fieldEnabler(ratioField, false); if (radiochoice.equals(radiobuttons[MANUAL])) { fieldEnabler(ystartField, true); if (type.equals(types[HLINES])) fieldEnabler(xstartField, false); //disable xstartField because //Horizontal lines needs just ystart and does not need xstart else fieldEnabler(xstartField, true); if (type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE])) fieldEnabler(combinedGridFields, true); else fieldEnabler(combinedGridFields, false); } else fieldEnabler(parameterFieldsOff, false); } void fieldEnabler(int[] fields, boolean show){ for(int i : fields) components[i].setEnabled(show); } // enables gridRatio choice for Combined Points and Double Lattice void setCoarseGrids(){ if (gridRatio.equals(ratioChoices[ONE_TO_FOUR])) { coarseGridX = 2; coarseGridY = 2; } else if (gridRatio.equals(ratioChoices[ONE_TO_NINE])) { coarseGridX = 3; coarseGridY = 3; } else if (gridRatio.equals(ratioChoices[ONE_TO_SIXTEEN])) { coarseGridX = 4; coarseGridY = 4; } else if (gridRatio.equals(ratioChoices[ONE_TO_TWENTYFIVE])) { coarseGridX = 5; coarseGridY = 5; } else if (gridRatio.equals(ratioChoices[ONE_TO_THIRTYSIX])) { coarseGridX = 6; coarseGridY = 6; } } // calculation for tileWidth and tileLength void calculateTile() { double tileSize = Math.sqrt(areaPerPoint); tileWidth = tileSize / pixelWidth; tileHeight = tileSize / pixelHeight; } // decide the first point(s) depending on the way to place a grid void calculateFirstGrid(){ if (radiochoice.equals(radiobuttons[RANDOM])) { xstart = (int) (random.nextDouble() * tileWidth); ystart = (int) (random.nextDouble() * tileHeight); // 0 <= random.nextDouble() < 1 xstartCoarse = random.nextInt(coarseGridX); ystartCoarse = random.nextInt(coarseGridY); } else if (radiochoice.equals(radiobuttons[FIXED])) { xstart = (int) (tileWidth / 2.0 + 0.5); ystart = (int) (tileHeight / 2.0 + 0.5); xstartCoarse = 0; ystartCoarse = 0; } else if (radiochoice.equals(radiobuttons[MANUAL])) { if (type.equals(types[HLINES])) { xstart = 0; // just to prevent an error } // check if both xstart and ystart are within proper ranges if (areaPerPoint != 0 && (xstart >= tileWidth || ystart >= tileHeight)) { if (xstart >= tileWidth) err += "\"xstart\" "; if (ystart >= tileHeight) err += "\"ystart\" "; err += "too large. \n"; } // input for the Combined grids if (type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE])) { // check if both xstartCoarse and ystartCoarse are within proper ranges if (xstartCoarse >= coarseGridX || ystartCoarse >= coarseGridY) { if (xstartCoarse >= coarseGridX) err += "\"xstartCoarse\" "; if (ystartCoarse >= coarseGridY) err += "\"ystartCoarse\" "; err += "too large."; } } } // calculating number of vertical and horizontal lines in a selected image linesV = (int) ((width - xstart) / tileWidth) + 1; linesH = (int) ((height - ystart) / tileHeight) + 1; } ShapeRoi getGridRoi() { GeneralPath path; if (type.equals(types[LINES])) path = drawLines(); else if (type.equals(types[HLINES])) path = drawHorizontalLines(); else if (type.equals(types[CROSSES])) path = drawCrosses(); else if (type.equals(types[POINTS])) path = drawPoints(); else if (type.equals(types[COMBINED])) path = drawCombined(); else if (type.equals(types[DOUBLE_LATTICE])) path = drawDoubleLattice(); else path = null; ShapeRoi roi = new ShapeRoi(path); roi.setStrokeColor(getColor()); return roi; } Color getColor() { Color c = Color.black; if (color.equals(colors[0])) c = Color.red; else if (color.equals(colors[1])) c = Color.green; else if (color.equals(colors[2])) c = Color.blue; else if (color.equals(colors[3])) c = Color.magenta; else if (color.equals(colors[4])) c = Color.cyan; else if (color.equals(colors[5])) c = Color.yellow; else if (color.equals(colors[6])) c = Color.orange; else if (color.equals(colors[7])) c = Color.black; else if (color.equals(colors[8])) c = Color.white; return c; } // output grid parameters void saveGridParameters(int sliceNumber){ Integer xStartOutput = new Integer(xstart); Integer xStartCoarseOutput = new Integer(xstartCoarse); Integer yStartCoarseOutput = new Integer(ystartCoarse); String singleQuart = "'"; if (type.equals(types[HLINES])) xStartOutput = null; if (!(type.equals(types[COMBINED]) || type.equals(types[DOUBLE_LATTICE]))) { xStartCoarseOutput = null; yStartCoarseOutput = null; singleQuart = ""; gridRatio = null; } DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String gridParameters = df.format(date) + "\t" + imp.getTitle() + "\t" + sliceNumber + "\t" + type + "\t" + areaPerPoint + "\t" + units + "^2" + "\t" + singleQuart + gridRatio + "\t" + color + "\t" + radiochoice + "\t" + xStartOutput + "\t" + ystart + "\t" + xStartCoarseOutput + "\t" + yStartCoarseOutput; // singleQuart before gridRatio is to prevent conversion to date in // Excel. gridParameterArray[sliceNumber - 1] = gridParameters; } void showGridParameters(){ showHistory(gridParameterArray); } static void showHistory(String[] parameters) { String windowTitle = "Grid History"; //ShowParameterWindow.java uses String "Grid History" without //referring to this windowTitle variable, //so be careful to change the title this window. String fileName = "CombinedGridsHistory.txt"; TextWindow gridHistoryWindow = (TextWindow) WindowManager.getWindow(windowTitle); if (gridHistoryWindow == null) { //make a new empty TextWindow with String windowTitle with headings gridHistoryWindow = new TextWindow( windowTitle, "Date \t Image \t Slice \t Grid Type \t Area per Point \t Unit " + "\t Ratio \t Color \t Location Setting " + "\t xstart \t ystart \t xstartCoarse \t ystartCoarse", "", 1028, 250); //If a file whose name is String fileName exists in the plugin folder, //read it into the list. try { BufferedReader br = new BufferedReader( new FileReader(IJ.getDirectory("plugins") + fileName) ); boolean isHeadings = true; while (true) { String s = br.readLine(); if (s == null) break; if(isHeadings) { isHeadings = false; continue; } gridHistoryWindow.append(s); } br.close(); } catch (IOException e) {} } if(parameters != null){ for(String str : parameters) gridHistoryWindow.append(str); //auto save the parameters into a file whose name is String fileName TextPanel tp = gridHistoryWindow.getTextPanel(); tp.saveAs(IJ.getDirectory("plugins") + fileName); } } boolean gridSwitchExist(){ Frame[] frames = Frame.getFrames(); for (Frame frame : frames){ if("Grid Switch".equals(frame.getTitle()) && frame.isVisible()) return true; } return false; } }
package cat.nyaa.utils; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.logging.Level; public interface ISerializable { /** * For informative only */ @Target(ElementType.FIELD) public @interface Ephemeral { } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Serializable { String name() default ""; String[] alias() default {}; boolean manualSerialization() default false; } @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface StandaloneConfig { boolean manualSerialization() default false; } default void deserialize(ConfigurationSection config) { deserialize(config, this); } default void serialize(ConfigurationSection config) { serialize(config, this); } static void deserialize(ConfigurationSection config, Object obj) { Class<?> clz = obj.getClass(); for (Field f : clz.getDeclaredFields()) { // standalone config StandaloneConfig standaloneAnno = f.getAnnotation(StandaloneConfig.class); if (standaloneAnno != null && !standaloneAnno.manualSerialization()) { if (FileConfigure.class.isAssignableFrom(f.getType())) { FileConfigure standaloneCfg = null; f.setAccessible(true); try { standaloneCfg = (FileConfigure) f.get(obj); } catch (ReflectiveOperationException ex) { Bukkit.getLogger().log(Level.SEVERE, "Failed to deserialize object", ex); standaloneCfg = null; } if (standaloneCfg != null) { standaloneCfg.load(); continue; } } } // Normal fields Serializable anno = f.getAnnotation(Serializable.class); if (anno == null || anno.manualSerialization()) continue; f.setAccessible(true); String cfgName = anno.name().equals("") ? f.getName() : anno.name(); try { Object origValue = f.get(obj); Object newValue = null; boolean hasValue = false; for (String key : anno.alias()) { if (config.contains(key)) { newValue = config.get(key); hasValue = true; break; } } if (!hasValue && config.contains(f.getName())) { newValue = config.get(f.getName()); hasValue = true; } if (!hasValue && anno.name().length() >0 && config.contains(anno.name())) { newValue = config.get(anno.name()); hasValue = true; } if (!hasValue) { continue; } if (f.getType().isEnum()) { try { newValue = Enum.valueOf((Class<? extends Enum>) f.getType(), (String)newValue); } catch (Exception ex) { ex.printStackTrace(); continue; } } f.set(obj, newValue); } catch (ReflectiveOperationException ex) { Bukkit.getLogger().log(Level.SEVERE, "Failed to deserialize object", ex); } } } static void serialize(ConfigurationSection config, Object obj) { Class<?> clz = obj.getClass(); for (Field f : clz.getDeclaredFields()) { // standalone config StandaloneConfig standaloneAnno = f.getAnnotation(StandaloneConfig.class); if (standaloneAnno != null && !standaloneAnno.manualSerialization()) { if (FileConfigure.class.isAssignableFrom(f.getType())) { FileConfigure standaloneCfg = null; f.setAccessible(true); try { standaloneCfg = (FileConfigure) f.get(obj); } catch (ReflectiveOperationException ex) { Bukkit.getLogger().log(Level.SEVERE, "Failed to serialize object", ex); standaloneCfg = null; } if (standaloneCfg != null) { standaloneCfg.save(); continue; } } } // Normal fields Serializable anno = f.getAnnotation(Serializable.class); if (anno == null || anno.manualSerialization()) continue; f.setAccessible(true); String cfgName; if (anno.name().equals("")) { cfgName = f.getName(); } else { cfgName = anno.name(); config.set(f.getName(), null); } for (String key : anno.alias()) { config.set(key, null); } try { if (f.getType().isEnum()) { Enum e = (Enum) f.get(obj); config.set(cfgName, e.name()); } else { Object origValue = f.get(obj); config.set(cfgName, origValue); } } catch (ReflectiveOperationException ex) { Bukkit.getLogger().log(Level.SEVERE, "Failed to serialize object", ex); } } } }
package edu.psu.compbio.seqcode.projects.naomi.shapealign; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount; import edu.psu.compbio.seqcode.deepseq.experiments.ControlledExperiment; import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentCondition; import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager; import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig; import edu.psu.compbio.seqcode.deepseq.experiments.Sample; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Point; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.gse.utils.ArgParser; import edu.psu.compbio.seqcode.gse.utils.io.RegionFileUtilities; public class SmithWatermanAlignment { protected GenomeConfig gconfig; protected ExptConfig econfig; protected ExperimentManager manager; protected List<Point> points; protected List<Region> regions; protected int window; static final int DIAG = 1; static final int LEFT = 2; static final int UP = 4; static final float MINIMUM_VALUE = Float.MIN_VALUE; protected Map<Sample, Map<Region,float[][]>> countsArray = new HashMap<Sample,Map<Region,float[][]>>(); public SmithWatermanAlignment(GenomeConfig gcon, ExptConfig econ, ExperimentManager man){ gconfig = gcon; econfig = econ; manager = man; } // setters public void setPoints(List<Point> p){points = p;} public void setRegions(List<Region> reg){regions = reg;} public void setWidth(int w){window = w;} public void setCountsArray(Map<Sample, Map<Region,float[][]>> sampleCounts){countsArray = sampleCounts;} public float computeScore(float aVal, float bVal){ float score = (aVal + bVal)/2 - Math.abs(aVal - bVal); return score; } public void loadData(){ List<Region> region = new ArrayList<Region>(); for(Point p: points){ region.add(p.expand(window/2)); } //merge overlapping regions and set back to the original size List<Region> resizedRegions = new ArrayList<Region>(); for (Region reg : Region.mergeRegions(region)){ //mergeRegions is a static method resizedRegions.add(reg.resize(window-1)); } setRegions(resizedRegions); //get StrandedBaseCount list for each regions per sample Map<Sample, Map<Region,List<StrandedBaseCount>>> sampleCountsMap = new HashMap<Sample, Map<Region,List<StrandedBaseCount>>>(); Map<Sample, Map<Region,float[][]>> sampleCountsArray = new HashMap<Sample, Map<Region,float[][]>>(); for (ExperimentCondition condition : manager.getConditions()){ for (ControlledExperiment rep: condition.getReplicates()){ Map<Region,List<StrandedBaseCount>> regionCounts = new HashMap<Region,List<StrandedBaseCount>>(); for (Region reg : regions){ regionCounts.put(reg, rep.getSignal().getBases(reg)); } sampleCountsMap.put(rep.getSignal(),regionCounts); } } //StrandedBasedCount object contains positive and negative strand separately for (Sample sample : sampleCountsMap.keySet()){ Map<Region,float[][]> regionCounts = new HashMap<Region,float[][]>(); for (Region reg : sampleCountsMap.get(sample).keySet()){ float[][] sampleCounts = new float[window][2]; for (int i = 0;i < window;i++){ for (int s = 0; s<2; s++) sampleCounts[i][s] = 0; } for (StrandedBaseCount hits: sampleCountsMap.get(sample).get(reg)){ if (hits.getStrand()=='+'){ sampleCounts[hits.getCoordinate()-reg.getStart()][0] = hits.getCount(); }else{ sampleCounts[hits.getCoordinate()-reg.getStart()][1] = hits.getCount(); } } regionCounts.put(reg, sampleCounts); } sampleCountsArray.put(sample, regionCounts); } setCountsArray(sampleCountsArray); } public void excuteShapeAlign(){ for (Sample sample : countsArray.keySet()){ // for (int i = 0; i <regions.size();i++){ for (int i = 0; i <1 ; i++){ for (int j = i+1; j <regions.size();j++) smithWatermanAlgorithm(sample, regions.get(i), regions.get(j)); } } } public void smithWatermanAlgorithm(Sample sample, Region regA, Region regB){ //get counts float [][] regACounts = countsArray.get(sample).get(regA); float [][] regBCounts = countsArray.get(sample).get(regB); //normalize the arrays to set the max value 1 //should I be normalizing using max of either strand ? float maxA = MINIMUM_VALUE; float maxB = MINIMUM_VALUE; for (int i = 0; i <window ; i++){ for (int s = 0 ; s < 2 ; s++){ if (regACounts[i][s] > maxA){maxA = regACounts[i][s];} if (regBCounts[i][s] > maxB){maxB = regBCounts[i][s];} } } float [][] normRegACounts = new float [window][2]; float [][] normRegBCounts = new float [window][2]; float [][] normRegBRevCounts = new float[window][2]; for (int i = 0 ; i <window; i++){ for (int s = 0 ; s < 2 ; s++){ normRegACounts[i][s] = regACounts[i][s]/maxA; normRegBCounts[i][s] = regBCounts[i][s]/maxB; } } //reversing normRegBCounts for (int i = 0; i <window; i++){ for (int s = 0; s < 2 ;s++){ normRegBRevCounts[window-i-1][1-s] = normRegBCounts[i][s]; } } //test for (int i = 0 ; i <50; i++){ System.out.println(normRegACounts[i][0]+" : "+normRegBRevCounts[i][0]); } // align using two possible ways SmithWatermanAlignmentMatrix alignOne = new SmithWatermanAlignmentMatrix(normRegACounts,normRegBCounts); SmithWatermanAlignmentMatrix alignTwo = new SmithWatermanAlignmentMatrix(normRegACounts,normRegBRevCounts); alignOne.buildMatrix(); alignTwo.buildMatrix(); Stack<Integer> traceBack = new Stack<Integer>(); float[][] regBarray = new float[window][2]; int s_x_coord = 0; int s_y_coord = 0; int e_x_coord = 0; int e_y_coord = 0; if (alignOne.getMaxScore() > alignTwo.getMaxScore()){ regBarray = normRegBCounts; traceBack = alignOne.getTraceBack(); s_x_coord = alignOne.getStartX(); s_y_coord = alignOne.getStartY(); e_x_coord = alignOne.getEndX(); e_y_coord = alignOne.getEndY(); }else{ regBarray = normRegBRevCounts; traceBack = alignTwo.getTraceBack(); s_x_coord = alignTwo.getStartX(); s_y_coord = alignTwo.getStartY(); e_x_coord = alignTwo.getEndX(); e_y_coord = alignTwo.getEndY(); } System.out.println("alignment start coordinates "+ s_x_coord + " : " + s_y_coord); System.out.println("alignment end coordinates "+ e_x_coord + " : " + e_y_coord); float[][] alignedRegA = new float[e_x_coord-s_x_coord+1][2]; float[][] alignedRegB = new float[e_y_coord-s_y_coord+1][2]; int current_x = e_x_coord; int current_y = e_y_coord; for (int i = e_x_coord-s_x_coord; i >= 0 ; i Stack<Integer> traceBackTable = traceBack; for (int s = 0 ; s <2; s++) alignedRegA[i][s] = normRegACounts[current_x][s]; if (traceBackTable.pop() != null || (traceBackTable.pop() == DIAG || traceBackTable.pop() == LEFT)) current_x } for (int i = e_y_coord-s_y_coord; i >= 0 ; i Stack<Integer> traceBackTable = traceBack; for (int s = 0 ; s <2; s++) alignedRegB[i][s] = normRegACounts[current_y][s]; if (traceBackTable.pop() != null || (traceBackTable.pop() == DIAG || traceBackTable.pop() == UP)) current_y } System.out.println("before alignment reg A"); for (int i = 0; i < normRegACounts.length; i++){ System.out.println(normRegACounts[i][0]+" : "+normRegACounts[i][1]); } System.out.println("before alignment reg B"); for (int i = 0; i < regBarray.length; i++){ System.out.println(regBarray[i][0]+" : "+regBarray[i][1]); } System.out.println("aglined reg A"); for (int i = 0; i < alignedRegA.length; i++){ System.out.println(alignedRegA[i][0]+" : "+alignedRegA[i][1]); } System.out.println("aglined reg B"); for (int i = 0; i < alignedRegB.length; i++){ System.out.println(alignedRegB[i][0]+" : "+alignedRegB[i][1]); } } public static void main(String[] args){ GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); ExperimentManager manager = new ExperimentManager(econf); SmithWatermanAlignment profile = new SmithWatermanAlignment(gconf, econf, manager); ArgParser ap = new ArgParser(args); int win = Args.parseInteger(args, "win", 200); List<Point> points = RegionFileUtilities.loadPeaksFromPeakFile(gconf.getGenome(), ap.getKeyValue("peaks"), win); profile.setPoints(points); profile.setWidth(win); profile.loadData(); profile.excuteShapeAlign(); } }
package cc.ycn.common; import cc.ycn.common.bean.WxConfig; import cc.ycn.common.util.StringTool; import cc.ycn.weixin.aes.AesException; import cc.ycn.weixin.aes.WXBizMsgCrypt; import com.google.common.base.Joiner; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.StandardToStringStyle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * * * @author andy */ public class WeixinSignTool { private final static Logger log = LoggerFactory.getLogger(WeixinSignTool.class); private final static String LOG_TAG = "[WeixinSignTool]"; /** * * * @return boolean */ public static boolean checkSignature(WxConfig config, String signature, String timeStamp, String nonce) { if (config == null) return false; if (signature == null || signature.isEmpty()) return false; if (timeStamp == null || timeStamp.isEmpty()) return false; if (nonce == null || nonce.isEmpty()) return false; String sign = WeixinSignTool.createSignature(config.getToken(), timeStamp, nonce); return signature.equals(sign); } /** * * * @return boolean */ public static boolean checkMsgSignature(WxConfig config, String msgSignature, String timeStamp, String nonce, String msgEncrypt) { if (config == null) return false; if (msgSignature == null || msgSignature.isEmpty()) return false; if (timeStamp == null || timeStamp.isEmpty()) return false; if (nonce == null || nonce.isEmpty()) return false; if (msgEncrypt == null) msgEncrypt = ""; String sign = WeixinSignTool.createSignature(config.getToken(), timeStamp, nonce, msgEncrypt); return msgSignature.equals(sign); } /** * Url * * @param msgSignature String * @param timeStamp String * @param nonce String * @param echoStrEncrypt String echoStr * @return String echoStr * @throws cc.ycn.common.exception.WxErrorException */ public static String verifyUrl(WxConfig config, String msgSignature, String timeStamp, String nonce, String echoStrEncrypt) { if (config == null) return null; if (msgSignature == null || msgSignature.isEmpty()) return null; if (timeStamp == null || timeStamp.isEmpty()) return null; if (nonce == null || nonce.isEmpty()) return null; if (echoStrEncrypt == null || echoStrEncrypt.isEmpty()) return null; String echoStr = null; try { WXBizMsgCrypt msgCrypt = new WXBizMsgCrypt(config.getToken(), config.getAesKey(), config.getAppId(), config.getComponentAppId()); echoStr = msgCrypt.VerifyURL(msgSignature, timeStamp, nonce, echoStrEncrypt); } catch (Exception ignore) { } return echoStr; } /** * * * @param config WxConfig * @param text String * @return String * @throws AesException */ public static String encrypt(WxConfig config, String text) throws AesException { if (config == null || text == null || text.isEmpty()) return ""; WXBizMsgCrypt msgCrypt = new WXBizMsgCrypt(config.getToken(), config.getAesKey(), config.getAppId(), config.getComponentAppId()); return msgCrypt.encrypt(text); } /** * * * @param config WxConfig * @param text String * @return String * @throws AesException */ public static String decrypt(WxConfig config, String text) throws AesException { if (config == null || text == null || text.isEmpty()) return ""; WXBizMsgCrypt msgCrypt = new WXBizMsgCrypt(config.getToken(), config.getAesKey(), config.getAppId(), config.getComponentAppId()); return msgCrypt.decrypt(text); } /** * SHA1 * * @param params String[] * @return String */ public static String createSignature(String... params) { String packValue = packValue(Arrays.asList(params), ""); return StringTool.SHA1(packValue); } /** * JSSHA1 * * @param packValue String * @return String */ public static String createJSSignature(String packValue) { return StringTool.SHA1(packValue); } /** * SHA1 * * @param packValue String * @return String */ public static String createCardSignature(String packValue) { return StringTool.SHA1(packValue); } /** * MD5 * * @param config WxConfig * @param obj Object * @param excludeFields String[] * @return String */ public static String createPaySignature(WxConfig config, Object obj, String[] excludeFields) { if (config == null || obj == null) return ""; String packVal = packValue(obj, "&", excludeFields) + "&key=" + config.getPaySecret(); return StringTool.MD5(packVal).toUpperCase(); } /** * MD5 * * @param config WxConfig * @param map Map * @param excludeFields String[] * @return String */ public static String createPaySignature(WxConfig config, Map<String, String> map, String[] excludeFields) { if (config == null || map == null || map.isEmpty()) return ""; String packVal = packValue(map, "&", excludeFields) + "&key=" + config.getPaySecret(); return StringTool.MD5(packVal).toUpperCase(); } /** * MD5 * * @param config WxConfig * @param arr List * @param excludeFields String[] * @return String */ public static String createPaySignature(WxConfig config, List<String> arr, String[] excludeFields) { if (config == null || arr == null || arr.isEmpty()) return ""; String packVal = packValue(arr, "&", excludeFields) + "&key=" + config.getPaySecret(); return StringTool.MD5(packVal).toUpperCase(); } /** * * * @param obj Object * @param sep String * @return String */ public static String packValue(Object obj, String sep) { return packValue(obj, sep, null); } /** * * * @param obj Object * @param sep String * @param excludeFields String[] * @return String */ public static String packValue(Object obj, String sep, String[] excludeFields) { if (obj == null) return ""; StandardToStringStyle style = new StandardToStringStyle(); style.setUseIdentityHashCode(false); style.setUseClassName(false); style.setUseShortClassName(false); style.setUseFieldNames(true); style.setContentStart(""); style.setContentEnd(""); style.setFieldNameValueSeparator("="); style.setFieldSeparator(sep); style.setArrayStart("["); style.setArrayEnd("]"); style.setArraySeparator(","); style.setNullText("<null>"); ReflectionToStringBuilder builder = new ReflectionToStringBuilder(obj, style); if (excludeFields != null && excludeFields.length > 0) builder = builder.setExcludeFieldNames(excludeFields); String value = builder.toString(); String[] parts = value.split(sep); List<String> list = new ArrayList<String>(); for (String part : parts) { System.out.println(part); if (part == null || part.isEmpty() || part.contains("<null>") || (part.indexOf("=") == (part.length() - 1))) continue; list.add(part); } Collections.sort(list); String packVal = Joiner.on(sep).join(list); log.info("{} packVal={}", LOG_TAG, packVal); return packVal; } /** * * * @param map Map * @param sep String * @return String */ public static String packValue(Map<String, String> map, String sep) { return packValue(map, sep, null); } /** * * * @param map Map * @param sep String * @param excludeKeys String[] * @return String */ public static String packValue(Map<String, String> map, String sep, String[] excludeKeys) { if (map == null || map.isEmpty()) return ""; Set<String> excludeMap = new HashSet<String>(); if (excludeKeys != null && excludeKeys.length > 0) excludeMap.addAll(Arrays.asList(excludeKeys)); List<String> list = new ArrayList<String>(); for (String key : map.keySet()) { if (excludeMap.contains(key)) continue; String val = map.get(key); if (val == null || val.isEmpty()) continue; list.add(key + "=" + val); } Collections.sort(list); String packVal = Joiner.on(sep).join(list); log.info("{} packVal={}", LOG_TAG, packVal); return packVal; } /** * * * @param arr List * @param sep String * @return String */ public static String packValue(List<String> arr, String sep) { return packValue(arr, sep, null); } /** * * * @param arr List * @param sep String * @param excludes String[] * @return String */ public static String packValue(List<String> arr, String sep, String[] excludes) { if (arr == null || arr.isEmpty()) return ""; Set<String> excludeMap = new HashSet<String>(); if (excludes != null && excludes.length > 0) excludeMap.addAll(Arrays.asList(excludes)); List<String> list = new ArrayList<String>(); for (String item : arr) { if (item != null && !item.isEmpty()) { if (excludeMap.contains(item)) continue; list.add(item); } } Collections.sort(list); String packVal = Joiner.on(sep).join(list); log.info("{} packVal={}", LOG_TAG, packVal); return packVal; } }
package org.rstudio.studio.client.panmirror.command; import java.util.ArrayList; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.widget.ToolbarPopupMenu; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.client.ui.MenuItem; public class PanmirrorToolbarMenu extends ToolbarPopupMenu implements PanmirrorCommandUIObject { public PanmirrorToolbarMenu(PanmirrorToolbarCommands commands) { init(commands); } private PanmirrorToolbarMenu(PanmirrorToolbarMenu parent, PanmirrorToolbarCommands commands) { super(parent); init(commands); } private void init(PanmirrorToolbarCommands commands) { commands_ = commands; addStyleName(RES.styles().toolbarPopupMenu()); getElement().getStyle().setZIndex(1000); setAutoOpen(true); } @Override public void getDynamicPopupMenu (final ToolbarPopupMenu.DynamicPopupMenuCallback callback) { sync(true); callback.onPopupMenu(this); } public void addCommand(String id) { PanmirrorCommandMenuItem item = new PanmirrorCommandMenuItem(commands_.get(id)); addItem(item); uiObjects_.add(item); } public PanmirrorToolbarMenu addSubmenu(String text) { PanmirrorToolbarMenu submenu = new PanmirrorToolbarMenu(this, commands_); submenu.addMenuBarStyle(RES.styles().toolbarPopupMenu()); addItem(new MenuItem(menuText(text)), submenu); uiObjects_.add(submenu); return submenu; } @Override public void sync(boolean images) { uiObjects_.forEach(object -> object.sync(images)); } private static SafeHtml menuText(String text) { return SafeHtmlUtils.fromTrustedString(AppCommand.formatMenuLabel(null, text, null)); } private static final PanmirrorToolbarResources RES = PanmirrorToolbarResources.INSTANCE; private final ArrayList<PanmirrorCommandUIObject> uiObjects_ = new ArrayList<PanmirrorCommandUIObject>(); private PanmirrorToolbarCommands commands_; }
package com.adeo.fitnesse; import java.io.IOException; import java.net.MalformedURLException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; * !path /home/ec2-user/fitnesse/lib/* <br/> * <br/> * !|ActionFixture| <br/> * |start|com.adeo.fitnesse.JMXFixture| <br/> * |enter|setHostport|localhost:10102| <br/> * |enter|setOperationName|resetLilyState| <br/> * |enter|setObjectName|LilyLauncher:name=Launcher| <br/> * |check|callJMXOperation|true| <br/> * </code> * * TODO: code review * TODO: manage the returned Object from the JMX Operation call. * * @author cyrillakech <cyril.lakech@webadeo.net> * */ public class JMXFixture extends fit.Fixture { /** * the host and the port of the JVM to reach <br/> * <br/> * sample "localhost:10102" */ private String hostport = null; /** * the mbean object name to call <br/> * <br/> * sample "LilyLauncher:name=Launcher" */ private String objectName = null; /** * the operation name to call <br/> * <br/> * sample "resetLilyState" */ private String operationName = null; public boolean callJMXOperation() { if (hostport == null || objectName == null || operationName == null) { return false; } JMXServiceURL url = null; try { url = new JMXServiceURL("service:jmx:rmi://" + hostport + "/jndi/rmi://" + hostport + "/jmxrmi"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } JMXConnector connector = null; try { connector = JMXConnectorFactory.connect(url); } catch (IOException e) { e.printStackTrace(); return false; } if (connector == null) { return false; } try { connector.connect(); } catch (IOException e) { e.printStackTrace(); return false; } ObjectName lilyLauncher = null; try { lilyLauncher = new ObjectName(objectName); } catch (MalformedObjectNameException e) { e.printStackTrace(); return false; } catch (NullPointerException e) { e.printStackTrace(); return false; } try { connector.getMBeanServerConnection().invoke(lilyLauncher, operationName, new Object[0], new String[0]); } catch (InstanceNotFoundException e) { e.printStackTrace(); return false; } catch (MBeanException e) { e.printStackTrace(); return false; } catch (ReflectionException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } try { connector.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } public String getHostport() { return hostport; } public void setHostport(String hostport) { this.hostport = hostport; } public String getObjectName() { return objectName; } public void setObjectName(String objectName) { this.objectName = objectName; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } }
package fr.paris.lutece.portal.service.resource; import fr.paris.lutece.portal.service.spring.SpringContextService; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Class to notify listeners of actions performed on resources. Listeners keep * at least track of the number of actions performed over a given resource. */ public class ExtendableResourceActionHit { /** * Download action */ public static final String ACTION_DOWNLOAD = "download"; /** * Creation action */ public static final String ACTION_CREATION = "creation"; /** * Update action */ public static final String ACTION_UPDATE = "update"; /** * Archive action */ public static final String ACTION_ARCHIVE = "archive"; /** * Delete action */ public static final String ACTION_DELETE = "delete"; private static ExtendableResourceActionHit _instance; /** * Private constructor */ private ExtendableResourceActionHit( ) { } /** * Get the service instance * @return The instance of the service */ public static ExtendableResourceActionHit getInstance( ) { if ( _instance == null ) { synchronized ( ExtendableResourceActionHit.class ) { _instance = new ExtendableResourceActionHit( ); } } return _instance; } /** * Get the total number of hit associated to a given action name and * resource type * @param strActionName The name of the action to get the number of hit of * @param strExtendableResourceType The resource type to get the hit of * @return The number of hit, or 0 if this action has no hit for this * resource type */ public int getActionHit( String strActionName, String strExtendableResourceType ) { int nResult = 0; for ( IExtendableResourceActionHitListener listener : SpringContextService .getBeansOfType( IExtendableResourceActionHitListener.class ) ) { nResult += listener.getActionHit( strActionName, strExtendableResourceType ); } return nResult; } /** * Get the list of action names associated with a number of hit for a given * resource * @param strExtendableResourceId The id of the resource * @param strExtendableResourceType The type of the resource * @return A map containing associations between action names and hit number */ public Map<String, Integer> getResourceHit( String strExtendableResourceId, String strExtendableResourceType ) { Map<String, Integer> mapActionHit = new HashMap<String, Integer>( ); for ( IExtendableResourceActionHitListener listener : SpringContextService .getBeansOfType( IExtendableResourceActionHitListener.class ) ) { for ( Entry<String, Integer> entry : listener.getResourceHit( strExtendableResourceId, strExtendableResourceType ).entrySet( ) ) { if ( mapActionHit.containsKey( entry.getKey( ) ) ) { mapActionHit.put( entry.getKey( ), mapActionHit.get( entry.getKey( ) ) + entry.getValue( ) ); } else { mapActionHit.put( entry.getKey( ), entry.getValue( ) ); } } } return mapActionHit; } /** * Get the number of hit associated with a resource and an action name * @param strExtendableResourceId The id of the resource * @param strExtendableResourceType The type of the resource * @param strActionName The name of the action * @return The number of hit, or 0 if the resource has no hit for this * action */ public int getResourceActionHit( String strExtendableResourceId, String strExtendableResourceType, String strActionName ) { int nResult = 0; for ( IExtendableResourceActionHitListener listener : SpringContextService .getBeansOfType( IExtendableResourceActionHitListener.class ) ) { nResult += listener .getResourceActionHit( strExtendableResourceId, strExtendableResourceType, strActionName ); } return nResult; } /** * Notify every listeners that an action has been performed on a resource * @param strExtendableResourceId The id of the resource the action was * performed on * @param strExtendableResourceType The type of the resource the action was * performed on * @param strActionName The name of the action that was performed on the * resource. Action names can be any strings, but * the class {@link ExtendableResourceActionHit} exposes standard * action names. */ public void notifyActionOnResource( String strExtendableResourceId, String strExtendableResourceType, String strActionName ) { for ( IExtendableResourceActionHitListener listener : SpringContextService .getBeansOfType( IExtendableResourceActionHitListener.class ) ) { listener.notifyActionOnResource( strExtendableResourceId, strExtendableResourceType, strActionName ); } } }
package com.fishercoder.solutions; /** * 5. Longest Palindromic Substring * * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example: Input: "babad" Output: "bab" Note: "aba" is also a valid answer. Example: Input: "cbbd" Output: "bb" */ public class _5 { private int low, maxLen; public String longestPalindrome(String s) { int len = s.length(); if (len < 2) { return s; } for (int i = 0; i < len - 1; i++) { extendPalindrome(s, i, i); // assume odd length, try to extend Palindrome as possible extendPalindrome(s, i, i + 1); // assume even length. } return s.substring(low, low + maxLen); } private void extendPalindrome(String s, int left, int right) { while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { left right++; } if (maxLen < right - left - 1) { low = left + 1; maxLen = right - left - 1; } } }
package com.glitchcog.fontificator.gui.controls.panel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.border.TitledBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileFilter; import org.apache.log4j.Logger; import com.glitchcog.fontificator.config.ConfigFont; import com.glitchcog.fontificator.config.FontType; import com.glitchcog.fontificator.config.FontificatorProperties; import com.glitchcog.fontificator.config.loadreport.LoadConfigReport; import com.glitchcog.fontificator.gui.chat.ChatWindow; import com.glitchcog.fontificator.gui.component.CharacterPicker; import com.glitchcog.fontificator.gui.component.LabeledInput; import com.glitchcog.fontificator.gui.component.LabeledSlider; import com.glitchcog.fontificator.gui.component.combomenu.ComboMenuBar; import com.glitchcog.fontificator.gui.controls.ControlWindow; import com.glitchcog.fontificator.gui.controls.panel.model.DropdownBorder; import com.glitchcog.fontificator.gui.controls.panel.model.DropdownFont; import com.glitchcog.fontificator.gui.controls.panel.model.DropdownLabel; /** * Control Panel containing all the Font and Border options * * @author Matt Yanos */ public class ControlPanelFont extends ControlPanelBase { private static final Logger logger = Logger.getLogger(ControlPanelFont.class); private static final long serialVersionUID = 1L; /** * Text of the selection option in the font and border preset dropdown menus to prompt the user to specify her own file */ private final static DropdownLabel CUSTOM_KEY = new DropdownLabel(null, "Custom..."); private static final Map<DropdownLabel, DropdownFont> PRESET_FONT_FILE_MAP = new LinkedHashMap<DropdownLabel, DropdownFont>() { private static final long serialVersionUID = 1L; { put(CUSTOM_KEY, null); put(new DropdownLabel("7th Dragon", "7th Dragon Name"), new DropdownFont("7d_name_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Bahamut Lagoon", "Bahamut Lagoon"), new DropdownFont("bah_lag_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Chrono", "Chrono Cross"), new DropdownFont("cc_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Chrono", "Chrono Trigger"), new DropdownFont("ct_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Clash at Demonhead", "Clash at Demonhead"), new DropdownFont("cad_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Crystalis", "Crystalis"), new DropdownFont("crystalis_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior"), new DropdownFont("dw1_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior II"), new DropdownFont("dw2_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Quest I.II (SFC)"), new DropdownFont("dq1_2_sfc_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior III"), new DropdownFont("dw3_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior III (GBC) Dialog"), new DropdownFont("dw3gbc_dialog_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior III (GBC) Fight"), new DropdownFont("dw3gbc_fight_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Quest III (SFC)"), new DropdownFont("dq3_sfc_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior IV"), new DropdownFont("dw4_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("EarthBound", "EarthBound Zero Bold"), new DropdownFont("eb0_bold_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("EarthBound", "EarthBound"), new DropdownFont("eb_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("EarthBound", "EarthBound Mr. Saturn"), new DropdownFont("eb_saturn_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("EarthBound", "Mother 3"), new DropdownFont("m3_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Faxanadu", "Faxanadu Dialog"), new DropdownFont("faxanadu_dialog_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Faxanadu", "Faxanadu HUD"), new DropdownFont("faxanadu_hud_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy"), new DropdownFont("ff1_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy Dawn of Souls"), new DropdownFont("ffdos_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy IV"), new DropdownFont("ff4_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy VI"), new DropdownFont("ff6_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy VI (Battle)"), new DropdownFont("ff6_battle_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy VII"), new DropdownFont("ff7_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy Tactics Advance (Dialog)"), new DropdownFont("ffta_dialog_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Final Fantasy", "Final Fantasy Tactics Advance (Menu)"), new DropdownFont("ffta_menu_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Freedom Planet", "Freedom Planet"), new DropdownFont("freep_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Ghosts and Goblins", "Ghosts n Goblins"), new DropdownFont("gng_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Golden Sun", "Golden Sun"), new DropdownFont("gsun_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Golden Sun", "Golden Sun (Battle)"), new DropdownFont("gsun_battle_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Harvest Moon", "Friends of Mineral Town"), new DropdownFont("hm_fmt_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Harvest Moon", "Friends of Mineral Town Inverted"), new DropdownFont("hm_fmt_i_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Kunio-kun", "River City Ransom"), new DropdownFont("rcr_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Lost Vikings", "The Lost Vikings"), new DropdownFont("lostvik_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario Bros."), new DropdownFont("smb1_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario Bros. 2"), new DropdownFont("smb2_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario Bros. 3"), new DropdownFont("smb3_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario Bros. 3 HUD"), new DropdownFont("smb3_hud_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario Bros. 3 HUD (Mixed Case)"), new DropdownFont("smb3_hud_lowercase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario World"), new DropdownFont("smw_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario World 2: Yoshi's Island"), new DropdownFont("yi_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Dr. Mario"), new DropdownFont("drmario_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Mario is Missing"), new DropdownFont("mmiss_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mario", "Super Mario RPG: Dark"), new DropdownFont("smrpg_dark_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Mario", "Super Mario RPG: Light"), new DropdownFont("smrpg_light_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Mario", "Paper Mario: The Thousand Year Door"), new DropdownFont("pmttyd_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Mega Man", "Mega Man 9"), new DropdownFont("mm9_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mega Man", "Mega Man X"), new DropdownFont("mmx_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Mega Man", "Mega Man Battle Network"), new DropdownFont("mmbn1_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metal Gear", "Metal Gear"), new DropdownFont("mg_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Metroid"), new DropdownFont("metroid_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Metroid II"), new DropdownFont("metroid2_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Metroid II (Credits)"), new DropdownFont("metroid2_credits_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Super Metroid"), new DropdownFont("smetroid_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Super Metroid (Mixed Case)"), new DropdownFont("smetroid_mixedcase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Metroid", "Metroid Zero Mission"), new DropdownFont("metroid_zm_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Metroid", "Metroid Zero Mission Outline"), new DropdownFont("metroid_zm_outline_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Phantasy Star", "Phantasy Star"), new DropdownFont("ps1_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Phantasy Star", "Phantasy Star 2"), new DropdownFont("ps2_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Pokemon", "Pokemon Red/Blue"), new DropdownFont("pkmnrb_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Pokemon", "Pokemon Fire Red/Leaf Green"), new DropdownFont("pkmnfrlg_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Secret of Evermore", "Secret of Evermore"), new DropdownFont("soe_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Shantae", "Shantae"), new DropdownFont("shantae_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Simpsons", "Bart vs. the Space Mutants"), new DropdownFont("bart_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Solstice", "Solstice"), new DropdownFont("sol_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Sonic", "Sega System"), new DropdownFont("sega_sys_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Sonic", "Sonic Team"), new DropdownFont("sonic_team_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Star Ocean", "Star Ocean"), new DropdownFont("staroc_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Suikoden", "Suikoden"), new DropdownFont("suiko_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Tales", "Tales of Phantasia HUD (SFC, Mixed Case)"), new DropdownFont("tophan_hud_sfc_mixedcase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Tales", "Tales of Phantasia HUD (SFC, Upper Case)"), new DropdownFont("tophan_hud_sfc_uppercase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Tales", "Tales of Symphonia"), new DropdownFont("tos_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Tetris", "Tetris (GB)"), new DropdownFont("tetris_gb_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Tetris", "Tetris (NES)"), new DropdownFont("tetris_nes_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Wild Arms", "Wild Arms"), new DropdownFont("wildarms_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "The Legend of Zelda"), new DropdownFont("loz_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "The Legend of Zelda (Mixed Case)"), new DropdownFont("loz_lowercase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "Zelda II: The Adventures of Link"), new DropdownFont("zelda2_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "Zelda II (Mixed Case)"), new DropdownFont("zelda2_lowercase_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "Link's Awakening"), new DropdownFont("loz_la_font.png", FontType.FIXED_WIDTH)); put(new DropdownLabel("Zelda", "The Legend of Zelda: A Link to the Past"), new DropdownFont("lttp_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Zelda", "The Legend of Zelda: Ocarina of Time"), new DropdownFont("loz_oot_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Zelda", "The Legend of Zelda: The Wind Waker"), new DropdownFont("loz_ww_font.png", FontType.VARIABLE_WIDTH)); put(new DropdownLabel("Zero Wing", "Zero Wing"), new DropdownFont("zw_font.png", FontType.FIXED_WIDTH)); } }; /** * A reverse lookup through the map to get the actual name of a game for a font * * @param font * filename * @return game name */ public static String getFontGameName(String filename) { for (Entry<DropdownLabel, DropdownFont> e : PRESET_FONT_FILE_MAP.entrySet()) { if (CUSTOM_KEY.equals(e.getKey())) { continue; } final String fontFilename = e.getValue().getFontFilename(); if (fontFilename.equals(filename)) { return e.getKey().getLabel(); } } return "Unknown"; } private static final Map<DropdownLabel, DropdownBorder> PRESET_BORDER_FILE_MAP = new LinkedHashMap<DropdownLabel, DropdownBorder>() { private static final long serialVersionUID = 1L; { put(CUSTOM_KEY, null); put(new DropdownLabel("7th Dragon", "7th Dragon (Left)"), new DropdownBorder("7d_left_border.png")); put(new DropdownLabel("7th Dragon", "7th Dragon (Right)"), new DropdownBorder("7d_right_border.png")); put(new DropdownLabel("Chrono", "Chrono Cross"), new DropdownBorder("cc_border.png")); put(new DropdownLabel("Chrono", "Chrono Trigger"), new DropdownBorder("ct_border.png")); put(new DropdownLabel("Clash at Demonhead", "Clash at Demonhead"), new DropdownBorder("cad_border.png")); put(new DropdownLabel("Clash at Demonhead", "Clash at Demonhead Hermit"), new DropdownBorder("cad_hermit_border.png")); put(new DropdownLabel("Clash at Demonhead", "Clash at Demonhead Shop"), new DropdownBorder("cad_shop_border.png")); put(new DropdownLabel("Clash at Demonhead", "Clash at Demonhead Suzie"), new DropdownBorder("cad_suzie_border.png")); put(new DropdownLabel("Cyrstalis", "Crystalis"), new DropdownBorder("crystalis_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior"), new DropdownBorder("dw1_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior II"), new DropdownBorder("dw2_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Quest I.II (SFC)"), new DropdownBorder("dq1_2_sfc_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior III"), new DropdownBorder("dw3_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior III (GBC)"), new DropdownBorder("dw3gbc_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Quest III (SFC)"), new DropdownBorder("dq3_sfc_border.png")); put(new DropdownLabel("Dragon Warrior", "Dragon Warrior IV"), new DropdownBorder("dw4_border.png")); put(new DropdownLabel("EarthBound", "EarthBound Zero"), new DropdownBorder("eb0_border.png")); put(new DropdownLabel("EarthBound", "EarthBound Plain"), new DropdownBorder("eb_plain.png")); put(new DropdownLabel("EarthBound", "EarthBound Mint"), new DropdownBorder("eb_mint.png")); put(new DropdownLabel("EarthBound", "EarthBound Strawberry"), new DropdownBorder("eb_strawberry.png")); put(new DropdownLabel("EarthBound", "EarthBound Banana"), new DropdownBorder("eb_banana.png")); put(new DropdownLabel("EarthBound", "EarthBound Peanut"), new DropdownBorder("eb_peanut.png")); put(new DropdownLabel("EarthBound", "Mother 3"), new DropdownBorder("m3_border.png")); put(new DropdownLabel("Faxanadu", "Faxanadu"), new DropdownBorder("faxanadu_border.png")); put(new DropdownLabel("Final Fantasy", "Final Fantasy"), new DropdownBorder("ff1_border.png")); put(new DropdownLabel("Final Fantasy", "Final Fantasy IV"), new DropdownBorder("ff4_border.png")); put(new DropdownLabel("Final Fantasy", "Final Fantasy VI"), new DropdownBorder("ff6_border.png")); put(new DropdownLabel("Final Fantasy", "Final Fantasy VII"), new DropdownBorder("ff7_border.png")); put(new DropdownLabel("Freedom Planet", "Freedom Planet"), new DropdownBorder("freep_border.png")); put(new DropdownLabel("Golden Sun", "Golden Sun"), new DropdownBorder("gsun_border.png")); put(new DropdownLabel("Harvest Moon", "Friends of Mineral Town"), new DropdownBorder("hm_fmt_border.png")); put(new DropdownLabel("Harvest Moon", "Friends of Mineral Town Transparent"), new DropdownBorder("hm_fmt_t_border.png")); put(new DropdownLabel("Kunio-kun", "River City Ransom"), new DropdownBorder("rcr_border.png")); put(new DropdownLabel("Lost Vikings", "The Lost Vikings"), new DropdownBorder("lostvik_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Brick"), new DropdownBorder("smb1_brick_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Cloud"), new DropdownBorder("smb1_cloud_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Rock"), new DropdownBorder("smb1_rock_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Seabed"), new DropdownBorder("smb1_seabed_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Stone"), new DropdownBorder("smb1_stone_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. Empty Block"), new DropdownBorder("smb1_used_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. 2 Pause"), new DropdownBorder("smb2_pause_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. 3 HUD"), new DropdownBorder("smb3_hud_border.png")); put(new DropdownLabel("Mario (NES)", "Super Mario Bros. 3 Letter"), new DropdownBorder("smb3_letter_border.png")); put(new DropdownLabel("Mario (NES)", "Dr. Mario"), new DropdownBorder("drmario_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Block"), new DropdownBorder("smw_block_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Bonus"), new DropdownBorder("smw_bonus_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Gold"), new DropdownBorder("smw_gold_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Ground"), new DropdownBorder("smw_ground_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Mesh"), new DropdownBorder("smw_mesh_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Pipe"), new DropdownBorder("smw_pipe_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Rock"), new DropdownBorder("smw_rock_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World Yoshi's House"), new DropdownBorder("smw_yoshi_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario World 2: Yoshi's Island"), new DropdownBorder("yi_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario RPG"), new DropdownBorder("smrpg_border.png")); put(new DropdownLabel("Mario (SNES)", "Super Mario RPG Pipes"), new DropdownBorder("smrpg_pipe_border.png")); put(new DropdownLabel("Mega Man", "Mega Man 9 Stage Select"), new DropdownBorder("mm9_stage_border.png")); put(new DropdownLabel("Mega Man", "Mega Man 9 Menu"), new DropdownBorder("mm9_menu_border.png")); put(new DropdownLabel("Mega Man", "Mega Man 9 Menu Popup"), new DropdownBorder("mm9_popup_border.png")); put(new DropdownLabel("Mega Man", "Mega Man X"), new DropdownBorder("mmx_border.png")); put(new DropdownLabel("Metroid", "Metroid"), new DropdownBorder("metroid_border.png")); put(new DropdownLabel("Metroid", "Metroid II"), new DropdownBorder("metroid2_border.png")); put(new DropdownLabel("Metroid", "Metroid Pipes"), new DropdownBorder("metroid_pipe_border.png")); put(new DropdownLabel("Metroid", "Metroid Mother Brain Glass"), new DropdownBorder("metroid_glass_border.png")); put(new DropdownLabel("Metroid", "Super Metroid Mother Inventory"), new DropdownBorder("smetroid_inventory_border.png")); put(new DropdownLabel("Metroid", "Super Metroid Broken Glass"), new DropdownBorder("smetroid_glass_broke_border.png")); put(new DropdownLabel("Metroid", "Super Metroid Glass"), new DropdownBorder("smetroid_glass_border.png")); put(new DropdownLabel("Metroid", "Metroid Zero Mission"), new DropdownBorder("metroid_zm_border.png")); put(new DropdownLabel("Phantasy Star", "Phantasy Star"), new DropdownBorder("ps1_border.png")); put(new DropdownLabel("Phantasy Star", "Phantasy Star 2"), new DropdownBorder("ps2_border.png")); put(new DropdownLabel("Pokemon", "Pokemon Red/Blue"), new DropdownBorder("pkmnrb_border.png")); put(new DropdownLabel("Pokemon", "Pokemon Fire Red/Leaf Green"), new DropdownBorder("pkmnfrlg_border.png")); put(new DropdownLabel("Secret of Evermore", "Secret of Evermore"), new DropdownBorder("soe_border.png")); put(new DropdownLabel("Shantae", "Shantae"), new DropdownBorder("shantae_border.png")); put(new DropdownLabel("Star Ocean", "Star Ocean"), new DropdownBorder("staroc_border.png")); put(new DropdownLabel("Suikoden", "Suikoden"), new DropdownBorder("suiko_border.png")); put(new DropdownLabel("Tales", "Tales of Phantasia (SFC)"), new DropdownBorder("tophan_sfc_border.png")); put(new DropdownLabel("Tales", "Tales of Symphonia B"), new DropdownBorder("tos_b_border.png")); put(new DropdownLabel("Tales", "Tales of Symphonia C"), new DropdownBorder("tos_c_border.png")); put(new DropdownLabel("Tetris", "Tetris Next (GB)"), new DropdownBorder("tetris_gb_border.png")); put(new DropdownLabel("Tetris", "Tetris (NES)"), new DropdownBorder("tetris_nes_border.png")); put(new DropdownLabel("Tetris", "Tetris Next (NES)"), new DropdownBorder("tetris_nes_next_border.png")); put(new DropdownLabel("Wild Arms", "Wild Arms"), new DropdownBorder("wildarms_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda Bush"), new DropdownBorder("loz_bush_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda Rock"), new DropdownBorder("loz_rock_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda Dungeon"), new DropdownBorder("loz_dungeon_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda Story"), new DropdownBorder("loz_story_border.png")); put(new DropdownLabel("Zelda", "Zelda II: The Adventures of Link"), new DropdownBorder("zelda2_border.png")); put(new DropdownLabel("Zelda", "Link's Awakening Room"), new DropdownBorder("loz_la_room_border.png")); put(new DropdownLabel("Zelda", "Link's Awakening Name"), new DropdownBorder("loz_la_name_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda: A Link to the Past"), new DropdownBorder("lttp_border.png")); put(new DropdownLabel("Zelda", "The Legend of Zelda: The Wind Waker"), new DropdownBorder("loz_ww_border.png")); } }; /** * A reverse lookup through the map to get the actual name of a game for a border * * @param border * filename * @return game name */ public static String getBorderGameName(String filename) { for (Entry<DropdownLabel, DropdownBorder> e : PRESET_BORDER_FILE_MAP.entrySet()) { if (CUSTOM_KEY.equals(e.getKey())) { continue; } final String borderFilename = e.getValue().getBorderFilename(); if (borderFilename.equals(filename)) { return e.getKey().getLabel(); } } return "Unknown"; } private LabeledInput fontFilenameInput; private ComboMenuBar fontPresetDropdown; private JCheckBox fontTypeCheckbox; private LabeledInput borderFilenameInput; private ComboMenuBar borderPresetDropdown; private LabeledInput gridWidthInput; private LabeledInput gridHeightInput; private JFileChooser fontPngPicker; private JFileChooser borderPngPicker; private LabeledSlider fontScaleSlider; private LabeledSlider borderScaleSlider; private LabeledSlider borderInsetXSlider; private LabeledSlider borderInsetYSlider; private LabeledInput characterKeyInput; private LabeledSlider spaceWidthSlider; private LabeledSlider lineSpacingSlider; private LabeledSlider charSpacingSlider; private JButton unknownCharPopupButton; private CharacterPicker charPicker; private JLabel unknownCharLabel; private JCheckBox extendedCharBox; private ConfigFont config; private ChangeListener sliderListener; private ActionListener fontTypeListener; /** * Construct a font control panel * * @param fProps * @param chatWindow * @param logBox */ public ControlPanelFont(FontificatorProperties fProps, ChatWindow chatWindow, LogBox logBox) { super("Font/Border", fProps, chatWindow, logBox); fontTypeCheckbox.addActionListener(fontTypeListener); fontPngPicker = new JFileChooser(); borderPngPicker = new JFileChooser(); FileFilter pngFilter = new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || (f.getName().toLowerCase().endsWith(".png")); } @Override public String getDescription() { return "PNG Image (*.png)"; } }; fontPngPicker.setFileFilter(pngFilter); borderPngPicker.setFileFilter(pngFilter); } @Override protected void build() { sliderListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (fontScaleSlider.getSlider().equals(source)) { config.setFontScale(fontScaleSlider.getValue()); } else if (borderScaleSlider.getSlider().equals(source)) { config.setBorderScale(borderScaleSlider.getValue()); } else if (borderInsetXSlider.getSlider().equals(source)) { config.setBorderInsetX(borderInsetXSlider.getValue()); } else if (borderInsetYSlider.getSlider().equals(source)) { config.setBorderInsetY(borderInsetYSlider.getValue()); } else if (spaceWidthSlider.getSlider().equals(source)) { config.setSpaceWidth(spaceWidthSlider.getValue()); } else if (lineSpacingSlider.getSlider().equals(source)) { config.setLineSpacing(lineSpacingSlider.getValue()); } else if (charSpacingSlider.getSlider().equals(source)) { config.setCharSpacing(charSpacingSlider.getValue()); } chat.repaint(); } }; ActionListener fontAl = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); DropdownLabel key = new DropdownLabel(source.getText()); if (CUSTOM_KEY.equals(key)) { int selectionResult = fontPngPicker.showDialog(ControlWindow.me, "Select Font PNG"); if (selectionResult == JFileChooser.APPROVE_OPTION) { fontFilenameInput.setText(fontPngPicker.getSelectedFile().getAbsolutePath()); fontPresetDropdown.setSelectedText(fontPngPicker.getSelectedFile().getName()); } } else { fontFilenameInput.setText(PRESET_FONT_FILE_MAP.get(key).getFontFilename()); fontTypeCheckbox.setSelected(FontType.VARIABLE_WIDTH.equals(PRESET_FONT_FILE_MAP.get(key).getDefaultType())); spaceWidthSlider.setEnabled(fontTypeCheckbox.isSelected()); } updateFontOrBorder(true); } }; ActionListener borderAl = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem) e.getSource(); DropdownLabel key = new DropdownLabel(source.getText()); if (CUSTOM_KEY.equals(key)) { int selectionResult = borderPngPicker.showDialog(ControlWindow.me, "Select Border PNG"); if (selectionResult == JFileChooser.APPROVE_OPTION) { borderFilenameInput.setText(borderPngPicker.getSelectedFile().getAbsolutePath()); borderPresetDropdown.setSelectedText(borderPngPicker.getSelectedFile().getName()); } } else { borderFilenameInput.setText(PRESET_BORDER_FILE_MAP.get(key).getBorderFilename()); } updateFontOrBorder(false); } }; fontTypeListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { config.setFontType(fontTypeCheckbox.isSelected() ? FontType.VARIABLE_WIDTH : FontType.FIXED_WIDTH); spaceWidthSlider.setEnabled(fontTypeCheckbox.isSelected()); updateFontOrBorder(true); } }; extendedCharBox = new JCheckBox("Display Extended Characters"); extendedCharBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final boolean ecbSelected = extendedCharBox.isSelected(); config.setExtendedCharEnabled(ecbSelected); unknownCharPopupButton.setEnabled(!ecbSelected); unknownCharLabel.setEnabled(!ecbSelected); chat.repaint(); } }); unknownCharLabel = new JLabel(""); charPicker = new CharacterPicker(ControlWindow.me, fProps.getFontConfig(), unknownCharLabel, chat); Map<String, List<String>> fontMenuMap = getMenuMapFromPresets(PRESET_FONT_FILE_MAP.keySet()); fontMenuMap.put(CUSTOM_KEY.getLabel(), null); Map<String, List<String>> borderMenuMap = getMenuMapFromPresets(PRESET_BORDER_FILE_MAP.keySet()); borderMenuMap.put(CUSTOM_KEY.getLabel(), null); fontTypeCheckbox = new JCheckBox("Variable Width Characters"); fontFilenameInput = new LabeledInput("Font Filename", 32); fontPresetDropdown = new ComboMenuBar(fontMenuMap, fontAl); borderFilenameInput = new LabeledInput("Border Filename", 32); borderPresetDropdown = new ComboMenuBar(borderMenuMap, borderAl); gridWidthInput = new LabeledInput("Grid Width", 4); gridHeightInput = new LabeledInput("Grid Height", 4); fontScaleSlider = new LabeledSlider("Font Scale", "x", ConfigFont.MIN_FONT_SCALE, ConfigFont.MAX_FONT_SCALE); borderScaleSlider = new LabeledSlider("Border Scale", "x", ConfigFont.MIN_BORDER_SCALE, ConfigFont.MAX_BORDER_SCALE); borderInsetXSlider = new LabeledSlider("X", "pixels", ConfigFont.MIN_BORDER_INSET, ConfigFont.MAX_BORDER_INSET); borderInsetYSlider = new LabeledSlider("Y", "pixels", ConfigFont.MIN_BORDER_INSET, ConfigFont.MAX_BORDER_INSET); characterKeyInput = new LabeledInput("Character Key", 32); spaceWidthSlider = new LabeledSlider("Space Width", "%", ConfigFont.MIN_SPACE_WIDTH, ConfigFont.MAX_SPACE_WIDTH); lineSpacingSlider = new LabeledSlider("Line Spacing", "pixels", ConfigFont.MIN_LINE_SPACING, ConfigFont.MAX_LINE_SPACING); charSpacingSlider = new LabeledSlider("Char Spacing", "pixels", ConfigFont.MIN_CHAR_SPACING, ConfigFont.MAX_LINE_SPACING); unknownCharPopupButton = new JButton("Select Missing Character"); unknownCharPopupButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { charPicker.setVisible(true); } }); fontFilenameInput.setEnabled(false); borderFilenameInput.setEnabled(false); fontScaleSlider.addChangeListener(sliderListener); borderScaleSlider.addChangeListener(sliderListener); borderInsetXSlider.addChangeListener(sliderListener); borderInsetYSlider.addChangeListener(sliderListener); spaceWidthSlider.addChangeListener(sliderListener); lineSpacingSlider.addChangeListener(sliderListener); charSpacingSlider.addChangeListener(sliderListener); JPanel fontPanel = new JPanel(new GridBagLayout()); JPanel borderPanel = new JPanel(new GridBagLayout()); JPanel unknownPanel = new JPanel(new GridBagLayout()); fontPanel.setBorder(new TitledBorder(baseBorder, "Font")); borderPanel.setBorder(new TitledBorder(baseBorder, "Border")); unknownPanel.setBorder(new TitledBorder(baseBorder, "Extended and Unicode Characters")); GridBagConstraints fontGbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, DEFAULT_INSETS, 0, 0); GridBagConstraints borderGbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, DEFAULT_INSETS, 0, 0); GridBagConstraints unknownGbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, DEFAULT_INSETS, 0, 0); // Fields are still used and stored in properties files when saved, but the values are either fixed or meant to // be filled by other components // add(fontFilenameInput); // add(borderFilenameInput); // add(gridWidthInput); // add(gridHeightInput); // add(characterKeyInput); fontPanel.add(fontPresetDropdown, fontGbc); fontGbc.gridx++; // This slider being on the same row as the preset dropdown keeps the combo menu bar from collapsing to no // height in the layout fontPanel.add(fontScaleSlider, fontGbc); fontGbc.gridwidth = 2; fontGbc.gridx = 0; fontGbc.gridy++; fontPanel.add(lineSpacingSlider, fontGbc); fontGbc.gridy++; fontPanel.add(charSpacingSlider, fontGbc); fontGbc.gridy++; JPanel variableWidthPanel = new JPanel(new GridBagLayout()); GridBagConstraints vwpGbc = getGbc(); vwpGbc.anchor = GridBagConstraints.EAST; vwpGbc.weightx = 0.0; vwpGbc.fill = GridBagConstraints.NONE; variableWidthPanel.add(fontTypeCheckbox, vwpGbc); vwpGbc.anchor = GridBagConstraints.WEST; vwpGbc.weightx = 1.0; vwpGbc.fill = GridBagConstraints.HORIZONTAL; vwpGbc.gridx++; variableWidthPanel.add(spaceWidthSlider, vwpGbc); fontPanel.add(variableWidthPanel, fontGbc); fontGbc.gridy++; borderPanel.add(borderPresetDropdown, borderGbc); borderGbc.gridx++; // This slider being on the same row as the preset dropdown keeps the combo menu bar from collapsing to no // height in the layout borderPanel.add(borderScaleSlider, borderGbc); borderGbc.gridwidth = 2; borderGbc.gridx = 0; borderGbc.gridy++; borderGbc.anchor = GridBagConstraints.CENTER; borderPanel.add(new JLabel("Font Insets Off Border"), borderGbc); borderGbc.gridy++; borderPanel.add(borderInsetXSlider, borderGbc); borderGbc.gridy++; borderPanel.add(borderInsetYSlider, borderGbc); borderGbc.gridy++; unknownPanel.add(extendedCharBox, unknownGbc); unknownGbc.gridx++; unknownPanel.add(unknownCharPopupButton, unknownGbc); unknownGbc.gridx++; unknownPanel.add(unknownCharLabel, unknownGbc); unknownGbc.gridx++; JPanel everything = new JPanel(new GridBagLayout()); GridBagConstraints eGbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, DEFAULT_INSETS, 10, 10); everything.add(fontPanel, eGbc); eGbc.gridy++; everything.add(borderPanel, eGbc); eGbc.gridy++; everything.add(unknownPanel, eGbc); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.CENTER; gbc.weightx = 1.0; gbc.weighty = 0.0; add(everything, gbc); // Filler panel gbc.gridy++; gbc.weighty = 1.0; gbc.anchor = GridBagConstraints.SOUTH; add(new JPanel(), gbc); } /** * Turns a list of keys with a single pipe deliminating the parent menu from the menu item into a map that can be a parameter to create a ComboMenuBar * * @param keys * @return */ private Map<String, List<String>> getMenuMapFromPresets(Collection<DropdownLabel> keys) { Map<String, List<String>> menuMap = new LinkedHashMap<String, List<String>>(); for (DropdownLabel key : keys) { final String menu = key.getGroup(); final String item = key.getLabel(); List<String> items = menuMap.get(menu); if (items == null) { items = new ArrayList<String>(); menuMap.put(menu, items); } items.add(item); } return menuMap; } private boolean updateFontOrBorder(boolean isFont) { LoadConfigReport report = new LoadConfigReport(); if (isFont) { config.validateFontFile(report, fontFilenameInput.getText()); config.validateStrings(report, gridWidthInput.getText(), gridHeightInput.getText(), characterKeyInput.getText(), Character.toString(charPicker.getSelectedChar())); } else { config.validateBorderFile(report, borderFilenameInput.getText()); } if (report.isErrorFree()) { try { fillConfigFromInput(); if (isFont) { chat.reloadFontFromConfig(); } else { chat.reloadBorderFromConfig(); } chat.repaint(); return true; } catch (Exception ex) { logger.error(ex.toString(), ex); ChatWindow.popup.handleProblem("Unable to load " + (isFont ? "font" : "border") + " image", ex); } } else { ChatWindow.popup.handleProblem(report); } return false; } @Override protected void fillInputFromProperties(FontificatorProperties fProps) { this.config = fProps.getFontConfig(); fillInputFromConfig(); } @Override protected void fillInputFromConfig() { borderFilenameInput.setText(config.getBorderFilename()); fontFilenameInput.setText(config.getFontFilename()); gridWidthInput.setText(Integer.toString(config.getGridWidth())); gridHeightInput.setText(Integer.toString(config.getGridHeight())); fontScaleSlider.setValue(config.getFontScale()); borderScaleSlider.setValue(config.getBorderScale()); borderInsetXSlider.setValue(config.getBorderInsetX()); borderInsetYSlider.setValue(config.getBorderInsetY()); characterKeyInput.setText(config.getCharacterKey()); extendedCharBox.setSelected(config.isExtendedCharEnabled()); charPicker.setSelectedChar(config.getUnknownChar()); spaceWidthSlider.setValue(config.getSpaceWidth()); lineSpacingSlider.setValue(config.getLineSpacing()); charSpacingSlider.setValue(config.getCharSpacing()); fontTypeCheckbox.setSelected(FontType.VARIABLE_WIDTH.equals(config.getFontType())); spaceWidthSlider.setEnabled(fontTypeCheckbox.isSelected()); boolean found; found = false; for (Map.Entry<DropdownLabel, DropdownFont> entry : PRESET_FONT_FILE_MAP.entrySet()) { if (entry.getValue() != null && config.getFontFilename().equals(entry.getValue().getFontFilename())) { found = true; fontPresetDropdown.setSelectedText(entry.getKey().getLabel()); } } if (!found) { String filename = new File(fontFilenameInput.getText()).getName(); fontPresetDropdown.setSelectedText(filename); } found = false; for (Map.Entry<DropdownLabel, DropdownBorder> entry : PRESET_BORDER_FILE_MAP.entrySet()) { if (entry.getValue() != null && config.getBorderFilename().equals(entry.getValue().getBorderFilename())) { found = true; borderPresetDropdown.setSelectedText(entry.getKey().getLabel()); } } if (!found) { String filename = new File(borderFilenameInput.getText()).getName(); borderPresetDropdown.setSelectedText(filename); } // Although the font was already updated from the listener attached the the fontTypeDropdown, it should be done // here to make it official. If the font and border aren't updated, they could be out of sync with the input // filled from config on preset loads, and it shouldn't be the responsibility of actionlisteners attached to UI // components to update the display updateFontOrBorder(true); // Also, the border must be updated here too. updateFontOrBorder(false); } @Override protected LoadConfigReport validateInput() { LoadConfigReport report = new LoadConfigReport(); config.validateFontFile(report, fontFilenameInput.getText()); config.validateBorderFile(report, borderFilenameInput.getText()); final String widthStr = gridWidthInput.getText(); final String heightStr = gridHeightInput.getText(); final String charKey = characterKeyInput.getText(); final String unknownStr = Character.toString(charPicker.getSelectedChar()); config.validateStrings(report, widthStr, heightStr, charKey, unknownStr); return report; } @Override protected void fillConfigFromInput() throws Exception { config.setBorderFilename(borderFilenameInput.getText()); config.setFontFilename(fontFilenameInput.getText()); config.setFontType(fontTypeCheckbox.isSelected() ? FontType.VARIABLE_WIDTH : FontType.FIXED_WIDTH); config.setGridWidth(Integer.parseInt(gridWidthInput.getText())); config.setGridHeight(Integer.parseInt(gridHeightInput.getText())); config.setFontScale(fontScaleSlider.getValue()); config.setBorderScale(borderScaleSlider.getValue()); config.setBorderInsetX(borderInsetXSlider.getValue()); config.setBorderInsetY(borderInsetYSlider.getValue()); config.setCharacterKey(characterKeyInput.getText()); config.setExtendedCharEnabled(extendedCharBox.isSelected()); config.setUnknownChar(charPicker.getSelectedChar()); config.setSpaceWidth(spaceWidthSlider.getValue()); config.setLineSpacing(lineSpacingSlider.getValue()); config.setCharSpacing(charSpacingSlider.getValue()); } }
package com.gengo.client; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import com.gengo.client.enums.HttpMethod; import com.gengo.client.enums.Rating; import com.gengo.client.enums.RejectReason; import com.gengo.client.exceptions.GengoException; import com.gengo.client.payloads.FileJob; import com.gengo.client.payloads.Payload; import com.gengo.client.payloads.TranslationJob; import com.gengo.client.payloads.Payloads; public class GengoClient extends JsonHttpApi { private static final String STANDARD_BASE_URL = "http://api.gengo.com/v2/"; private static final String SANDBOX_BASE_URL = "http://api.sandbox.gengo.com/v2/"; /** Strings used to represent TRUE and FALSE in requests */ public static final String MYGENGO_TRUE = "1"; public static final String MYGENGO_FALSE = "0"; private String baseUrl = STANDARD_BASE_URL; /** * Initialize the client. * @param publicKey your Gengo.com public API key * @param privateKey your Gengo.com private API key */ public GengoClient(String publicKey, String privateKey) { this(publicKey, privateKey, false); } /** * Initialize the client with the option to use the sandbox. * @param publicKey your Gengo.com public API key * @param privateKey your Gengo.com private API key * @param useSandbox true to use the sandbox, false to use the live service */ public GengoClient(String publicKey, String privateKey, boolean useSandbox) { super(publicKey, privateKey); setUseSandbox(useSandbox); } /** * @return true iff the client is using the sandbox */ public boolean getUseSandbox() { return SANDBOX_BASE_URL.equals(baseUrl); } /** * Set the client to use the sandbox or the live service. * @param use true iff the client should use the sandbox */ public void setUseSandbox(boolean use) { baseUrl = use ? SANDBOX_BASE_URL : STANDARD_BASE_URL; } /** * Set a custom base URL. For development testing purposes only. * @param baseUrl a custom API base URL */ public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } /** * Get account statistics. * @return the response from the server * @throws GengoException */ public JSONObject getAccountStats() throws GengoException { String url = baseUrl + "account/stats"; return call(url, HttpMethod.GET); } /** * Get account balance. * @return the response from the server * @throws GengoException */ public JSONObject getAccountBalance() throws GengoException { String url = baseUrl + "account/balance"; return call(url, HttpMethod.GET); } /** * Get preferred translators in array by langs and tier * @return the response from the server * @throws GengoException */ public JSONObject getAccountPreferredTranslators() throws GengoException { String url = baseUrl + "account/preferred_translators"; return call(url, HttpMethod.GET); } /** * Submit multiple jobs for translation. * @param jobs TranslationJob payload objects * @param processAsGroup true iff the jobs should be processed as a group * @return the response from the server * @throws GengoException */ public JSONObject postTranslationJobs(List<TranslationJob> jobs, boolean processAsGroup) throws GengoException { try { String url = baseUrl + "translate/jobs"; JSONObject data = new JSONObject(); /* We can safely cast our list of jobs into a list of the payload base type */ @SuppressWarnings({ "rawtypes", "unchecked" }) List<Payload> p = (List)jobs; data.put("jobs", (new Payloads(p)).toJSONArray()); data.put("as_group", processAsGroup ? MYGENGO_TRUE : MYGENGO_FALSE); JSONObject rsp = call(url, HttpMethod.POST, data); return rsp; } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Request revisions for a job. * @param id The job ID * @param comments Comments for the translator * @return the response from the server * @throws GengoException */ public JSONObject reviseTranslationJob(int id, String comments) throws GengoException { try { String url = baseUrl + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "revise"); data.put("comment", comments); return call(url, HttpMethod.PUT, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Approve a translation. * @param id The job ID * @param ratingTime Rating of the translation time/speed * @param ratingQuality Rating of the translation quality * @param ratingResponse Rating of the translator responsiveness * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @param feedbackIsPublic Whether the src/tgt text & feedback can be shared publicly * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating ratingTime, Rating ratingQuality, Rating ratingResponse, String commentsForTranslator, String commentsForGengo, boolean feedbackIsPublic) throws GengoException { try { String url = baseUrl + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "approve"); if (commentsForTranslator != null) { data.put("for_translator", commentsForTranslator); } if (commentsForGengo != null) { data.put("for_gengo", commentsForGengo); } if (ratingTime != null) { data.put("rating_time", ratingTime.toString()); } if (ratingQuality != null) { data.put("rating_quality", ratingQuality.toString()); } if (ratingResponse != null) { data.put("rating_response", ratingResponse.toString()); } data.put("public", feedbackIsPublic ? MYGENGO_TRUE : MYGENGO_FALSE); return call(url, HttpMethod.PUT, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Approve a translation. * * @deprecated {@link GengoClient#approveTranslationJob(int, Rating, Rating, Rating, String, String, boolean)} * * @param id The job ID * @param rating Rating of the translation * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @param feedbackIsPublic Whether the src/tgt text & feedback can be shared publicly * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating rating, String commentsForTranslator, String commentsForGengo, boolean feedbackIsPublic) throws GengoException { return approveTranslationJob(id, rating, rating, rating, commentsForTranslator, commentsForGengo, feedbackIsPublic); } /** * Approve a translation. The feedback will be private. * @param id The job ID * @param ratingTime Rating of the translation time/speed * @param ratingQuality Rating of the translation quality * @param ratingResponse Rating of the translator responsiveness * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating ratingTime, Rating ratingQuality, Rating ratingResponse, String commentsForTranslator, String commentsForGengo) throws GengoException { return approveTranslationJob(id, ratingTime, ratingQuality, ratingResponse, commentsForTranslator, commentsForGengo, false); } /** * Approve a translation. The feedback will be private. * * @deprecated {@link GengoClient#approveTranslationJob(int, Rating, Rating, Rating, String, String)} * * @param id The job ID * @param rating Rating of the translation * @param feedbackForTranslator Feedback for the translator * @param feedbackForGengo Feedback for Gengo * @return Response from the server * @throws GengoException */ public JSONObject approveTranslationJob(int id, Rating rating, String commentsForTranslator, String commentsForGengo) throws GengoException { return approveTranslationJob(id, rating, rating, rating, commentsForTranslator, commentsForGengo, false); } /** * Reject a translation. * @param id the job ID * @param reason reason for rejection * @param comments comments for Gengo * @param captcha the captcha image text * @param requeue true iff the job should be passed on to another translator * @return the response from the server * @throws GengoException */ public JSONObject rejectTranslationJob(int id, RejectReason reason, String comments, String captcha, boolean requeue) throws GengoException { try { String url = baseUrl + "translate/job/" + id; JSONObject data = new JSONObject(); data.put("action", "reject"); data.put("reason", reason.toString().toLowerCase()); data.put("comment", comments); data.put("captcha", captcha); data.put("follow_up", requeue ? "requeue" : "cancel"); return call(url, HttpMethod.PUT, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Get a translation job * @param id the job id * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJob(int id) throws GengoException { String url = baseUrl + "translate/job/" + id; return call(url, HttpMethod.GET); } /** * Get all translation jobs * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobs() throws GengoException { String url = baseUrl + "translate/jobs/"; return call(url, HttpMethod.GET); } /** * Get selected translation jobs * @param ids a list of job ids to retrieve * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobs(List<Integer> ids) throws GengoException { String url = baseUrl + "translate/jobs/"; url += join(ids, ","); return call(url, HttpMethod.GET); } /** * Post a comment for a translation job * @param id the ID of the job to comment on * @param comment the comment * @return the response from the server * @throws GengoException */ public JSONObject postTranslationJobComment(int id, String comment) throws GengoException { try { String url = baseUrl + "translate/job/" + id + "/comment"; JSONObject data = new JSONObject(); data.put("body", comment); return call(url, HttpMethod.POST, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Get comments for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobComments(int id) throws GengoException { String url = baseUrl + "translate/job/" + id + "/comments/"; return call(url, HttpMethod.GET); } /** * Get feedback for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobFeedback(int id) throws GengoException { String url = baseUrl + "translate/job/" + id + "/feedback"; return call(url, HttpMethod.GET); } /** * Get all revisions for a translation job * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobRevisions(int id) throws GengoException { String url = baseUrl + "translate/job/" + id + "/revisions"; return call(url, HttpMethod.GET); } /** * Get a specific revision for a translation job * @param id the job ID * @param revisionId the ID of the revision to retrieve * @return the response from the server * @throws GengoException */ public JSONObject getTranslationJobRevision(int id, int revisionId) throws GengoException { String url = baseUrl + "translate/job/" + id + "/revision/" + revisionId; return call(url, HttpMethod.GET); } /** * Cancel a translation job. It can only be deleted if it has not been started by a translator. * @param id the job ID * @return the response from the server * @throws GengoException */ public JSONObject deleteTranslationJob(int id) throws GengoException { String url = baseUrl + "translate/job/" + id; return call(url, HttpMethod.DELETE); } /** * Cancel translation jobs. They can only be deleted if they have not been started by a translator. * @param ids a list of job IDs to delete * @return the response from the server * @throws GengoException */ public JSONObject deleteTranslationJobs(List<Integer> ids) throws GengoException { try { String url = baseUrl + "translate/jobs/"; JSONObject data = new JSONObject(); data.put("job_ids", ids); return call(url, HttpMethod.DELETE, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Get a list of supported languages and their language codes. * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguages() throws GengoException { String url = baseUrl + "translate/service/languages"; return call(url, HttpMethod.GET); } /** * Get a list of supported language pairs, tiers, and credit prices. * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguagePairs() throws GengoException { String url = baseUrl + "translate/service/language_pairs"; return call(url, HttpMethod.GET); } /** * Get a list of supported language pairs, tiers and credit prices for a specific source language. * @param sourceLanguageCode the language code for the source language * @return the response from the server * @throws GengoException */ public JSONObject getServiceLanguagePairs(String sourceLanguageCode) throws GengoException { try { String url = baseUrl + "translate/service/language_pairs"; JSONObject data = new JSONObject(); data.put("lc_src", sourceLanguageCode); return call(url, HttpMethod.GET, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Get a quote for translation jobs. * @param jobs Translation job objects to be quoted for * @return the response from the server * @throws GengoException */ public JSONObject determineTranslationCost(Payloads jobs) throws GengoException { try { String url = baseUrl + "translate/service/quote/"; JSONObject data = new JSONObject(); data.put("jobs", jobs.toJSONArray()); return call(url, HttpMethod.POST, data); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Get translation jobs which were previously submitted together by their order id. * * @param orderId * @return the response from the server * @throws GengoException */ public JSONObject getOrderJobs(int orderId) throws GengoException { String url = baseUrl + "translate/order/"; url += orderId; return call(url, HttpMethod.GET); } /** * Get a quote for file jobs. * @param jobs Translation job objects to be quoted * @param filePaths map of file keys to filesystem paths * @return the response from the server * @throws GengoException */ public JSONObject determineTranslationCostFiles(List<FileJob> jobs, Map<String, String> filePaths) throws GengoException { try { JSONObject theJobs = new JSONObject(); for (int i = 0; i < jobs.size(); i++) { theJobs.put(String.format("job_%s", i), jobs.get(i).toJSONObject()); } String url = baseUrl + "translate/service/quote/file"; JSONObject data = new JSONObject(); data.put("jobs", theJobs); return httpPostFileUpload(url, data, filePaths); } catch (JSONException x) { throw new GengoException(x.getMessage(), x); } } /** * Utility function. */ private String join(Iterable<? extends Object> pColl, String separator) { Iterator<? extends Object> oIter; if (pColl == null || (!(oIter = pColl.iterator()).hasNext())) { return ""; } StringBuffer oBuilder = new StringBuffer(String.valueOf(oIter.next())); while (oIter.hasNext()) { oBuilder.append(separator).append(oIter.next()); } return oBuilder.toString(); } }
package com.hp.autonomy.iod.client.api.search; import com.hp.autonomy.iod.client.util.MultiMap; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.commons.lang.StringUtils; import java.util.List; import java.util.Map; /** * Helper class for building up optional parameters for the Get Content API. The default value for all parameters * is null. Null parameters will not be sent to IDOL OnDemand */ @Setter @Accessors(chain = true) public class GetContentRequestBuilder { /** * @param highlightExpression Value for the highlight_expression parameter */ private String highlightExpression; /** * @param startTag Value for the start_tag parameter */ private String startTag; /** * @param endTag Value for the end_tag parameter */ private String endTag; /** * @param printFields Value for the print_fields parameter. This list will be joined with commas before being sent * to the server */ private List<String> printFields; /** * @param print Value for the print parameter */ private Print print; /** * @return A map of query parameters suitable for use with {@link QueryTextIndexService}. get is NOT supported on * the resulting map */ public Map<String, Object> build() { final Map<String, Object> map = new MultiMap<>(); map.put("highlight_expression", highlightExpression); map.put("start_tag", startTag); map.put("end_tag", endTag); map.put("print", print); map.put("print_fields", StringUtils.join(printFields, ',')); return map; } }
package com.github.fjdbc.query; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import com.github.fjdbc.ConnectionProvider; import com.github.fjdbc.FjdbcException; import com.github.fjdbc.PreparedStatementBinder; import com.github.fjdbc.util.FjdbcUtil; import com.github.fjdbc.util.IntSequence; public class Query<T> { private final String sql; private final PreparedStatementBinder binder; private final ResultSetExtractor<T> extractor; private ConnectionProvider cnxProvider; private Integer fetchSize; public Query(ConnectionProvider provider, String sql, PreparedStatementBinder binder, ResultSetExtractor<T> extractor) { assert provider != null; assert sql != null; assert extractor != null; this.cnxProvider = provider; this.sql = sql; this.binder = binder; this.extractor = extractor; } public Query(ConnectionProvider connectionProvider, String sql, ResultSetExtractor<T> extractor) { this(connectionProvider, sql, null, extractor); } public void setFetchSize(int fetchSize) { this.fetchSize = fetchSize; } private boolean isPrepared() { return binder != null; } public void forEach(Consumer<? super T> callback) { Statement st = null; try { final Connection cnx = cnxProvider.borrow(); st = isPrepared() ? cnx.prepareStatement(sql) : cnx.createStatement(); if (isPrepared()) binder.bind((PreparedStatement) st, new IntSequence(1)); if (fetchSize != null) st.setFetchSize(fetchSize); final ResultSet rs = isPrepared() ? ((PreparedStatement) st).executeQuery() : st.executeQuery(sql); extractor.extractAll(rs, callback); } catch (final SQLException e) { throw new FjdbcException(e); } finally { FjdbcUtil.close(st); cnxProvider.giveBack(); } } /** * Convenience method */ public List<T> toList() { final List<T> res = new ArrayList<>(); forEach(res::add); return res; } public T toSingleResult() { final List<T> res = new ArrayList<>(1); forEach(res::add); assert res.size() <= 1; return res.size() == 1 ? res.get(0) : null; } public String getSql() { return sql; } }