repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
truedem/ExpenseTracker | app/src/main/java/pk/fastaccountant/expensetracker/presenter/IPresenterOperations.java | 494 | package pk.fastaccountant.expensetracker.presenter;
import android.os.Bundle;
import android.view.View;
import pk.fastaccountant.expensetracker.ui.IViewOperationsRequired;
/**
* Created by PK on 16.06.2016.
*/
public interface IPresenterOperations {
void bindParent(IViewOperationsRequired parent);
void unbindParent();
void onButtonClick();
void onPause();
void onDestroy();
void onSaveInstanceState();
void onRestoreInstanceState();
void onStart();
}
| apache-2.0 |
wisechengyi/pants | tests/java/org/pantsbuild/tools/junit/lib/ConsoleRunnerTestBase.java | 4871 | // Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
package org.pantsbuild.tools.junit.lib;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.pantsbuild.junit.annotations.TestSerial;
import org.pantsbuild.tools.junit.impl.Concurrency;
import org.pantsbuild.tools.junit.impl.ConsoleRunnerImpl;
@TestSerial
@RunWith(Parameterized.class)
public abstract class ConsoleRunnerTestBase {
private static final String DEFAULT_CONCURRENCY_FLAG = "-default-concurrency";
private static final String DEFAULT_PARALLEL_FLAG = "-default-parallel";
private static final String USE_EXPERIMENTAL_RUNNER_FLAG = "-use-experimental-runner";
private static final String PARALLEL_THREADS_FLAG = "-parallel-threads";
private static final String DEFAULT_TEST_PACKGE = "org.pantsbuild.tools.junit.lib.";
protected TestParameters parameters;
protected enum TestParameters {
LEGACY_SERIAL(false, null),
LEGACY_PARALLEL_CLASSES(false, Concurrency.PARALLEL_CLASSES),
LEGACY_PARALLEL_METHODS(false, Concurrency.PARALLEL_METHODS),
EXPERIMENTAL_SERIAL(true, Concurrency.SERIAL),
EXPERIMENTAL_PARALLEL_CLASSES(true, Concurrency.PARALLEL_CLASSES),
EXPERIMENTAL_PARALLEL_METHODS(true, Concurrency.PARALLEL_METHODS),
EXPERIMENTAL_PARALLEL_CLASSES_AND_METHODS(true, Concurrency.PARALLEL_CLASSES_AND_METHODS);
public final boolean useExperimentalRunner;
public final Concurrency defaultConcurrency;
TestParameters(boolean useExperimentalRunner, Concurrency defaultConcurrency) {
this.useExperimentalRunner = useExperimentalRunner;
this.defaultConcurrency = defaultConcurrency;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (useExperimentalRunner) {
sb.append(USE_EXPERIMENTAL_RUNNER_FLAG);
sb.append(" ");
}
if (defaultConcurrency != null) {
sb.append(DEFAULT_CONCURRENCY_FLAG);
sb.append(" ");
sb.append(defaultConcurrency.name());
}
return sb.toString();
}
}
@Parameters(name = "{0}")
public static TestParameters[] data() {
return TestParameters.values();
}
/**
* The Parameterized test runner will invoke this test with each value in the
* {@link TestParameters} enum.
*
* @param parameters A combination of extra parameters to test with.
*/
public ConsoleRunnerTestBase(TestParameters parameters) {
this.parameters = parameters;
}
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
@Before
public void setUp() {
ConsoleRunnerImpl.setCallSystemExitOnFinish(false);
ConsoleRunnerImpl.addTestListener(null);
TestRegistry.reset();
}
@After
public void tearDown() {
ConsoleRunnerImpl.setCallSystemExitOnFinish(true);
ConsoleRunnerImpl.addTestListener(null);
}
/**
* Invokes ConsoleRunner.main() and tacks on optional parameters specified by the parameterized
* test runner.
*/
protected void invokeConsoleRunner(String argsString) {
prepareConsoleRunner(argsString).run();
}
/**
* As invokeConsoleRunner, but returns a ConsoleRunnerImpl ready for calling run() on.
*/
protected ConsoleRunnerImpl prepareConsoleRunner(String argsString) {
List<String> testArgs = new ArrayList<String>();
for (String arg : Splitter.on(" ").split(argsString)) {
// Prepend the package name to tests to allow shorthand command line invocation
if (arg.contains("Test") && !arg.contains(DEFAULT_TEST_PACKGE)) {
arg = DEFAULT_TEST_PACKGE + arg;
}
testArgs.add(arg);
}
// Tack on extra parameters from the Parameterized runner
if (!testArgs.contains(DEFAULT_CONCURRENCY_FLAG) && parameters.defaultConcurrency != null) {
if (!testArgs.contains(DEFAULT_CONCURRENCY_FLAG)
&& !testArgs.contains(DEFAULT_PARALLEL_FLAG)) {
testArgs.add(DEFAULT_CONCURRENCY_FLAG);
testArgs.add(parameters.defaultConcurrency.name());
}
if (!testArgs.contains(PARALLEL_THREADS_FLAG)) {
testArgs.add(PARALLEL_THREADS_FLAG);
testArgs.add("8");
}
}
if (!testArgs.contains(USE_EXPERIMENTAL_RUNNER_FLAG) && parameters.useExperimentalRunner) {
testArgs.add(USE_EXPERIMENTAL_RUNNER_FLAG);
}
System.out.println("Invoking ConsoleRunnerImpl.mainImpl(\""
+ Joiner.on(' ').join(testArgs) + "\")");
return ConsoleRunnerImpl.mainImpl(testArgs.toArray(new String[testArgs.size()]));
}
}
| apache-2.0 |
haakom/EnergiWeb-remake | energiweb/src/no/noen/lms/Terminal.java | 5217 | package no.noen.lms;
import java.io.Serializable;
import org.komsa.domain.*;
/**
* LMS terminal.
*/
public class Terminal extends Entity implements Serializable {
/* Attribute names */
public static final String F_TYPE = "type";
public static final String F_TYPEID = "typeId";
public static final String F_MAX_PORTNR = "maxPortNr";
public static final String F_BUILDINGID = "buildingId";
public static final String F_BUILDINGNAME = "buildingName";
public static final String F_CUSTOMERID = "customerId";
public static final String F_CUSTOMERNAME = "customerName";
public static final String F_NAME = "name";
public static final String F_ADDRESS = "address";
public static final String F_REFID = "refId";
public static final String F_IPADDR = "ipAddr";
public static final String F_USERNAME = "username";
public static final String F_PASSWORD = "password";
public static final String F_GSMNR = "gsmNr";
public static final String F_MAINTAINSTART = "mpStart";
public static final String F_MAINTAINEND = "mpEnd";
public static final String F_MAINTAINREG = "mpReg";
/** Constructor. */
public Terminal() {
super("lms", "Terminal");
Cell[] defaultCells = {
new Cell(F_TYPE, new StringDomain()),
new Cell(F_TYPEID, new IDDomain()),
new Cell(F_MAX_PORTNR, new IntegerDomain()),
new Cell(F_BUILDINGID, new IDDomain()),
new Cell(F_BUILDINGNAME, new StringDomain()),
new Cell(F_CUSTOMERID, new IDDomain()),
new Cell(F_CUSTOMERNAME, new StringDomain()),
new Cell(F_NAME, new StringDomain()),
new Cell(F_ADDRESS, new StringDomain()),
new Cell(F_REFID, new StringDomain()),
new Cell(F_IPADDR, new StringDomain()),
new Cell(F_USERNAME, new StringDomain()),
new Cell(F_PASSWORD, new StringDomain()),
new Cell(F_GSMNR, new StringDomain()),
new Cell(F_MAINTAINSTART, new TimestampDomain(null)),
new Cell(F_MAINTAINEND, new TimestampDomain(null)),
new Cell(F_MAINTAINREG, new OnOffDomain())
};
for (int i = 0; i < defaultCells.length; i++)
addCell(defaultCells[i]);
}
/** @return Terminal name as string. */
public final String getName() {
return get(F_NAME);
}
/** Set terminal name. */
public final void setName(String name) {
set(F_NAME, name);
}
/** @return IP-address for terminal. */
public final String getIPAddr() {
return get(F_IPADDR);
}
/** @return Terminal type as string. */
public final String getType() {
return get(F_TYPE);
}
/** @return Type ID as long integer. */
public final long getTypeId() {
return getLong(F_TYPEID);
}
/** @return max port nr allowed for terminal (type). */
public final int getMaxPortNr() {
return getInt(F_MAX_PORTNR);
}
/** @return Building ID as long integer. */
public final long getBuildingId() {
return getLong(F_BUILDINGID);
}
/** @return Building name. */
public final String getBuildingName() {
return get(F_BUILDINGNAME);
}
/** @return Customer ID as long integer. */
public final long getCustomerId() {
return getLong(F_CUSTOMERID);
}
/** @return Customer name. */
public final String getCustomerName() {
return get(F_CUSTOMERNAME);
}
/** @return Mainteinance start time. */
public final java.util.Date getMaintenanceStart() {
return (java.util.Date)getObj(F_MAINTAINSTART);
}
/** @return Mainteinance end time. */
public final java.util.Date getMaintenanceEnd() {
return (java.util.Date)getObj(F_MAINTAINEND);
}
/** @return true if terminal is on mainteinance. */
public final boolean isOnMaintenance() {
boolean fVal = false;
java.util.Date startTime = getMaintenanceStart();
java.util.Date endTime = getMaintenanceEnd();
if (startTime != null && endTime != null) {
java.util.Date now = new java.util.Date();
fVal = now.after(startTime) && now.before(endTime);
}
return fVal;
}
/** @return true if hour-data is saved when in a mainteinance-period. */
public final boolean isRegActive() {
return getShort(F_MAINTAINREG) == 1;
}
/**
* @param dateFrm Date format
* @return Mainteinance periode, if defined, as string.
*/
public final String getMaintenancePeriodStr(String dateFrm, String strSep) {
StringBuilder buf = new StringBuilder();
java.util.Date startTime = getMaintenanceStart();
java.util.Date endTime = getMaintenanceEnd();
if (startTime != null && endTime != null) {
String sep = (strSep != null) ? strSep : " - ";
java.util.Locale loc = new java.util.Locale("no", "NO", "");
java.text.DateFormat df = new java.text.SimpleDateFormat(dateFrm, loc);
buf.append(df.format(startTime)).append(sep).append(df.format(endTime));
}
return buf.toString();
}
}
| apache-2.0 |
phrocker/accumulo | core/src/main/java/org/apache/accumulo/core/file/FileSKVIterator.java | 1373 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.accumulo.core.file;
import java.io.DataInputStream;
import java.io.IOException;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.iterators.system.InterruptibleIterator;
public interface FileSKVIterator extends InterruptibleIterator {
public Key getFirstKey() throws IOException;
public Key getLastKey() throws IOException;
public DataInputStream getMetaStore(String name) throws IOException, NoSuchMetaStoreException;
public void closeDeepCopies() throws IOException;
public void close() throws IOException;
}
| apache-2.0 |
freeVM/freeVM | enhanced/archive/classlib/java6/modules/swing/src/main/java/common/javax/swing/plaf/metal/MetalButtonUI.java | 3238 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexander T. Simbirtsev
* @version $Revision$
*/
package javax.swing.plaf.metal;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicButtonUI;
import org.apache.harmony.x.swing.ButtonCommons;
public class MetalButtonUI extends BasicButtonUI {
protected Color disabledTextColor;
protected Color focusColor;
protected Color selectColor;
private static MetalButtonUI commonMetalButtonUI;
public static ComponentUI createUI(final JComponent component) {
if (commonMetalButtonUI == null) {
commonMetalButtonUI = new MetalButtonUI();
}
return commonMetalButtonUI;
}
public void installDefaults(final AbstractButton button) {
super.installDefaults(button);
}
public void uninstallDefaults(final AbstractButton button) {
super.uninstallDefaults(button);
}
protected Color getDisabledTextColor() {
disabledTextColor = UIManager.getColor(getPropertyPrefix() + "disabledText");
return disabledTextColor;
}
protected Color getFocusColor() {
focusColor = UIManager.getColor(getPropertyPrefix() + "focus");
return focusColor;
}
protected Color getSelectColor() {
selectColor = UIManager.getColor(getPropertyPrefix() + "select");
return selectColor;
}
protected void paintButtonPressed(final Graphics g, final AbstractButton button) {
if (button.getModel().isArmed() && button.isContentAreaFilled()) {
ButtonCommons.paintPressed(g, button, getSelectColor());
}
}
protected void paintFocus(final Graphics g, final AbstractButton b, final Rectangle viewRect, final Rectangle textRect, final Rectangle iconRect) {
ButtonCommons.paintFocus(g, ButtonCommons.getFocusRect(viewRect, textRect, iconRect), getFocusColor());
}
protected void paintText(final Graphics g, final JComponent c, final Rectangle textRect, final String text) {
final Color color = c.isEnabled() ? c.getForeground() : getDisabledTextColor();
final int offset = getTextShiftOffset();
textRect.translate(offset, offset);
ButtonCommons.paintText(g, (AbstractButton)c, textRect, text, color);
}
}
| apache-2.0 |
unstablemark/jsondiff | src/main/java/com/unstablemark/jsondiff/service/DiffServiceBean.java | 1182 | package com.unstablemark.jsondiff.service;
import com.unstablemark.jsondiff.domain.JsonData;
import com.unstablemark.jsondiff.repository.DiffRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class DiffServiceBean implements DiffService {
private final DiffRepository diffRepository;
@Autowired
public DiffServiceBean(DiffRepository diffRepository) {
this.diffRepository = diffRepository;
}
@Override
public UUID creatingJsonContainer() {
return diffRepository.creatingJsonContainer();
}
@Override
public JsonData updatingLeftJsonData(JsonData jsonData) {
return diffRepository.updatingLeftJsonData(jsonData);
}
@Override
public JsonData updatingRightJsonData(JsonData jsonData) {
return diffRepository.updatingRightJsonData(jsonData);
}
@Override
public JsonData getLeftJsonData(UUID id) {
return diffRepository.getLeftJsonData(id);
}
@Override
public JsonData getRightJsonData(UUID id) {
return diffRepository.getRightJsonData(id);
}
}
| apache-2.0 |
jenmalloy/enmasse | systemtests/src/main/java/io/enmasse/systemtest/manager/SharedResourceManager.java | 5945 | /*
* Copyright 2019, EnMasse authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.enmasse.systemtest.manager;
import io.enmasse.address.model.AddressSpace;
import io.enmasse.address.model.AddressSpaceBuilder;
import io.enmasse.systemtest.UserCredentials;
import io.enmasse.systemtest.amqp.AmqpClientFactory;
import io.enmasse.systemtest.logs.CustomLogger;
import io.enmasse.systemtest.mqtt.MqttClientFactory;
import io.enmasse.systemtest.platform.Kubernetes;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import java.util.HashMap;
import java.util.Map;
public class SharedResourceManager extends ResourceManager {
private static final Logger LOGGER = CustomLogger.getLogger();
private static SharedResourceManager instance;
private static Map<String, Integer> spaceCountMap = new HashMap<>();
protected AmqpClientFactory amqpClientFactory = null;
protected MqttClientFactory mqttClientFactory = null;
private AddressSpace sharedAddressSpace = null;
private static final String DEFAULT_ADDRESS_TEMPLATE = "-shared-";
private UserCredentials defaultCredentials = environment.getSharedDefaultCredentials();
private UserCredentials managementCredentials = environment.getSharedManagementCredentials();
public static synchronized SharedResourceManager getInstance() {
if (instance == null) {
instance = new SharedResourceManager();
}
return instance;
}
@Override
public AddressSpace getSharedAddressSpace() {
return sharedAddressSpace;
}
@Override
public void tearDown(ExtensionContext context) throws Exception {
if (context.getExecutionException().isPresent()) { //test failed
if (environment.skipCleanup()) {
LOGGER.warn("No address space is deleted, SKIP_CLEANUP is set");
} else {
LOGGER.info(String.format("test failed: %s.%s",
context.getRequiredTestClass().getName(),
context.getRequiredTestMethod().getName()));
LOGGER.info("shared address space '{}' will be removed", sharedAddressSpace);
try {
if (sharedAddressSpace != null) {
super.deleteAddressSpace(sharedAddressSpace);
}
} catch (Exception ex) {
LOGGER.warn("Failed to delete shared address space (ignored)", ex);
} finally {
spaceCountMap.compute(defaultAddSpaceIdentifier, (k, count) -> count == null ? null : count + 1);
}
}
} else { //succeed
try {
if (environment.skipCleanup()) {
LOGGER.warn("No address space is deleted, SKIP_CLEANUP is set");
} else {
LOGGER.info("Shared address space will be deleted!");
super.deleteAddressSpace(sharedAddressSpace);
}
} catch (Exception e) {
LOGGER.warn("Failed to delete addresses from shared address space (ignored)", e);
}
}
closeClientFactories(amqpClientFactory, mqttClientFactory);
amqpClientFactory = null;
mqttClientFactory = null;
sharedAddressSpace = null;
}
void initFactories(AddressSpace addressSpace) {
amqpClientFactory = new AmqpClientFactory(sharedAddressSpace, defaultCredentials);
mqttClientFactory = new MqttClientFactory(sharedAddressSpace, defaultCredentials);
}
@Override
public void setup() throws Exception {
LOGGER.info("Shared setup");
if (spaceCountMap == null) {
spaceCountMap = new HashMap<>();
}
spaceCountMap.putIfAbsent(defaultAddSpaceIdentifier, 0);
sharedAddressSpace = new AddressSpaceBuilder()
.withNewMetadata()
.withName(defaultAddSpaceIdentifier + DEFAULT_ADDRESS_TEMPLATE + spaceCountMap.get(defaultAddSpaceIdentifier))
.withNamespace(Kubernetes.getInstance().getInfraNamespace())
.endMetadata()
.withNewSpec()
.withType(addressSpaceType)
.withPlan(addressSpacePlan)
.withNewAuthenticationService()
.withName("standard-authservice")
.endAuthenticationService()
.endSpec()
.build();
createSharedAddressSpace(sharedAddressSpace);
createOrUpdateUser(sharedAddressSpace, managementCredentials);
createOrUpdateUser(sharedAddressSpace, defaultCredentials);
initFactories(sharedAddressSpace);
}
public void createSharedAddressSpace(AddressSpace addressSpace) throws Exception {
super.createAddressSpace(addressSpace);
sharedAddressSpace = addressSpace;
}
@Override
public void createAddressSpace(AddressSpace addressSpace) throws Exception {
super.createAddressSpace(addressSpace);
}
public void tearDownShared() throws Exception {
LOGGER.info("Deleting addresses");
deleteAddresses(sharedAddressSpace);
LOGGER.info("Closing clients");
closeClientFactories(amqpClientFactory, mqttClientFactory);
initFactories(sharedAddressSpace);
}
@Override
public AmqpClientFactory getAmqpClientFactory() {
return amqpClientFactory;
}
@Override
public void setAmqpClientFactory(AmqpClientFactory amqpClientFactory) {
this.amqpClientFactory = amqpClientFactory;
}
@Override
public MqttClientFactory getMqttClientFactory() {
return mqttClientFactory;
}
@Override
public void setMqttClientFactory(MqttClientFactory mqttClientFactory) {
this.mqttClientFactory = mqttClientFactory;
}
}
| apache-2.0 |
braxisltd/Gallery | src/main/java/com/braxisltd/gallery/Domain/About.java | 926 | package com.braxisltd.gallery.Domain;
import com.braxisltd.gallery.application.ApplicationConfig;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
public class About {
private static final String ABOUT_FILE = "about.txt";
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private ApplicationConfig config;
private List<String> paragraphs;
public About(ApplicationConfig config) {
this.config = config;
}
public List<String> getParagraphs() {
if (paragraphs == null) {
throw new IllegalStateException("Must first call load().");
}
return paragraphs;
}
public About load() throws IOException {
paragraphs = Files.readLines(new File(config.getDirectoryRoot(), ABOUT_FILE), DEFAULT_CHARSET);
return this;
}
}
| apache-2.0 |
aevum/libgdx-cpp | src/gdx-cpp/backends/android/android_support/src/com/badlogic/gdx/audio/AudioDevice.java | 2399 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.audio;
import com.badlogic.gdx.utils.Disposable;
/** Encapsulates an audio device in 44.1khz mono or stereo mode. Use the {@link #writeSamples(float[], int, int)} and
* {@link #writeSamples(short[], int, int)} methods to write float or 16-bit signed short PCM data directly to the audio device.
* Stereo samples are interleaved in the order left channel sample, right channel sample. The {@link #dispose()} method must be
* called when this AudioDevice is no longer needed.
*
* @author badlogicgames@gmail.com */
public interface AudioDevice extends Disposable {
/** @return whether this AudioDevice is in mono or stereo mode. */
public boolean isMono ();
/** Writes the array of 16-bit signed PCM samples to the audio device and blocks until they have been processed.
*
* @param samples The samples.
* @param offset The offset into the samples array
* @param numSamples the number of samples to write to the device */
public void writeSamples (short[] samples, int offset, int numSamples);
/** Writes the array of float PCM samples to the audio device and blocks until they have been processed.
*
* @param samples The samples.
* @param offset The offset into the samples array
* @param numSamples the number of samples to write to the device */
public void writeSamples (float[] samples, int offset, int numSamples);
/** @return the latency in samples. */
public int getLatency ();
/** Frees all resources associated with this AudioDevice. Needs to be called when the device is no longer needed. */
public void dispose ();
}
| apache-2.0 |
wireframe/wicketstuff-scriptaculous | src/java/org/wicketstuff/scriptaculous/inplaceeditor/AjaxEditInPlaceLabel.java | 6458 | package org.wicketstuff.scriptaculous.inplaceeditor;
import java.util.HashMap;
import java.util.Map;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AbstractAjaxBehavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.AbstractTextComponent;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.target.basic.StringRequestTarget;
import org.wicketstuff.scriptaculous.JavascriptBuilder;
import org.wicketstuff.scriptaculous.ScriptaculousAjaxBehavior;
import org.wicketstuff.scriptaculous.JavascriptBuilder.AjaxCallbackJavascriptFunction;
import org.wicketstuff.scriptaculous.effect.Effect;
/**
* Label that uses AJAX for editing "in place" instead of using conventional forms.
* There are several extension points within this class to allow for subclasses
* to customize the behavior of this component.
*
* @see http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor
*
* @author <a href="mailto:wireframe6464@users.sourceforge.net">Ryan Sonnek</a>
*/
public class AjaxEditInPlaceLabel extends AbstractTextComponent
{
private static final long serialVersionUID = 1L;
private AbstractAjaxBehavior callbackBehavior = new AjaxEditInPlaceOnSaveBehavior();
private AbstractAjaxBehavior onCompleteBehavior = new AjaxEditInPlaceOnCompleteBehavior();
private Map options = new HashMap();
private boolean enterEditMode = false;
private AbstractAjaxBehavior loadBehavior;
public AjaxEditInPlaceLabel(String wicketId, IModel model)
{
super(wicketId);
setModel(model);
setOutputMarkupId(true);
setEscapeModelStrings(false);
add(callbackBehavior);
add(onCompleteBehavior);
}
public String getInputName()
{
return "value";
}
/**
* configure use of okButton for InPlaceEditor.
*
* @param value
*/
public void setOkButton(boolean value)
{
addOption("okButton", Boolean.valueOf(value));
}
public void setCancelLink(boolean value)
{
addOption("cancelLink", Boolean.valueOf(value));
}
public void setExternalControl(WebMarkupContainer control)
{
addOption("externalControl", control.getMarkupId());
}
public void setSubmitOnBlur(boolean value)
{
addOption("submitOnBlur", Boolean.valueOf(value));
}
public void setRows(int rows)
{
addOption("rows", new Integer(rows));
}
public void setCols(int cols)
{
addOption("cols", new Integer(cols));
}
public void setSize(int size)
{
addOption("size", new Integer(size));
}
/**
* extension point for customizing what text is loaded for editing.
* Usually used in conjunction with <code>getDisplayValue()</code> to override
* what text is displayed in text area versus the label.
* <pre>
* setLoadBehavior(new AbstractAjaxBehavior() {
* public void onRequest() {
* RequestCycle.get().setRequestTarget(new StringRequestTarget(getValue()));
* }
* });
* </pre>
* @see #getDisplayValue()
*/
public void setLoadBehavior(AbstractAjaxBehavior loadBehavior)
{
this.loadBehavior = loadBehavior;
add(loadBehavior);
}
/**
* extension point to allow for manipulation of what value is displayed.
* Overriding this method allows for the component to display different text
* than what is edited. This may be useful when the display text is
* formatted differently than the editable text (ex: textile). The default
* behavior is to return the same value as the <code>getValue()</code>
* method.
*
* @see #getValue();
* @see #setLoadBehavior(AbstractAjaxBehavior)
* @see AjaxEditInPlaceOnSaveBehavior#onRequest()
*/
protected String getDisplayValue()
{
return getValue();
}
/**
* Sets the label to be in <i>edit mode</i> the next time the page is rendered.
* Needs to be called again when refreshing the component.
*/
public void enterEditMode()
{
enterEditMode = true;
}
/**
* extension point to override default onComplete behavior.
* allows for customizing behavior once the edited value has been saved.
* default implementation is to do nothing.
* @see AjaxEditInPlaceOnCompleteBehavior#onRequest()
*/
protected void onComplete(final AjaxRequestTarget target)
{
}
/**
* protected method to allow for subclasses to access adding additional options.
*/
protected final void addOption(String key, Object value)
{
options.put(key, value);
}
/**
* Handle the container's body.
*
* @param markupStream
* The markup stream
* @param openTag
* The open tag for the body
* @see wicket.Component#onComponentTagBody(MarkupStream, ComponentTag)
*/
protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag)
{
replaceComponentTagBody(markupStream, openTag, getDisplayValue());
}
protected void onRender(MarkupStream markupStream)
{
super.onRender(markupStream);
addOption("onComplete", new AjaxCallbackJavascriptFunction(onCompleteBehavior));
if (null != loadBehavior) {
addOption("loadTextURL", loadBehavior.getCallbackUrl());
}
JavascriptBuilder builder = new JavascriptBuilder();
builder.addLine("new Ajax.InPlaceEditor('" + getMarkupId() + "', ");
builder.addLine(" '" + callbackBehavior.getCallbackUrl() + "', ");
builder.addOptions(options);
builder.addLine(")");
if (enterEditMode)
{
builder.addLine(".enterEditMode()");
enterEditMode = false;
}
builder.addLine(";");
getResponse().write(builder.buildScriptTagString());
}
private class AjaxEditInPlaceOnCompleteBehavior extends ScriptaculousAjaxBehavior
{
private static final long serialVersionUID = 1L;
@Override
protected void respond(AjaxRequestTarget target) {
target.appendJavascript(new Effect.Highlight(AjaxEditInPlaceLabel.this).toJavascript());
onComplete(target);
}
}
private class AjaxEditInPlaceOnSaveBehavior extends ScriptaculousAjaxBehavior
{
private static final long serialVersionUID = 1L;
@Override
protected void respond(AjaxRequestTarget target) {
FormComponent formComponent = (FormComponent)getComponent();
formComponent.validate();
if (formComponent.isValid())
{
formComponent.updateModel();
}
RequestCycle.get().setRequestTarget(new StringRequestTarget(getDisplayValue()));
}
}
}
| apache-2.0 |
yungoo/apple-qos | apple-qos-server/apple-qos-server-statistics/src/main/java/com/appleframework/qos/server/statistics/mybatis2/dialect/db/SybaseDialect.java | 1665 | /*
* Copyright © 2012-2013 mumu@yfyang. All Rights Reserved.
*/
package com.appleframework.qos.server.statistics.mybatis2.dialect.db;
import com.appleframework.qos.server.statistics.mybatis2.dialect.Dialect;
/**
* Sybase数据库分页方言实现。
* 还未实现
*
* @author poplar.yfyang
* @version 1.0 2010-10-10 下午12:31
* @since JDK 1.5
*/
public class SybaseDialect implements Dialect {
public boolean supportsLimit() {
return false;
}
@Override
public String getLimitString(String sql, int offset, int limit) {
return null;
}
/**
* 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
* <pre>
* 如mysql
* dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
* select * from user limit :offset,:limit
* </pre>
*
* @param sql 实际SQL语句
* @param offset 分页开始纪录条数
* @param offsetPlaceholder 分页开始纪录条数-占位符号
* @param limit 分页每页显示纪录条数
* @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql
*/
public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException("paged queries not supported");
}
@Override
public String getCountString(String querySqlString) {
String sql = SQLServer2005Dialect.getNonOrderByPart(querySqlString);
return "select count(1) from (" + sql + ") as tmp_count";
}
}
| apache-2.0 |
stuffer2325/Makagiga | src/org/makagiga/commons/swing/MProgressIcon.java | 4846 | // Copyright 2009 Konrad Twardowski
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.makagiga.commons.swing;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.ImageObserver;
import java.lang.ref.WeakReference;
import java.util.Objects;
import javax.swing.Icon;
/**
* @since 3.4, 4.0 (org.makagiga.commons.swing package)
*/
public class MProgressIcon implements Icon {
// private
private boolean stringPainted = true;
private Color barForegroundColor = Color.RED;
private Color textColor = Color.WHITE;
private float alpha = 0.5f;
private final Icon impl;
private int arcAngle;
private int maximum;
private int percent;
private int value;
private final WeakReference<ImageObserver> observerRef;
// public
public MProgressIcon(final ImageObserver observer, final Icon impl) {
if (observer == null)
throw new IllegalArgumentException("Null observer");
observerRef = new WeakReference<>(observer);
this.impl = impl;
}
public float getAlpha() { return alpha; }
public void setAlpha(final float alpha) {
if (Float.compare(alpha, this.alpha) != 0) {
this.alpha = alpha;
repaint();
}
}
public Color getBarForeground() { return barForegroundColor; }
public void setBarForeground(final Color barForegroundColor) {
Objects.requireNonNull(barForegroundColor, "barForegroundColor");
if (!barForegroundColor.equals(this.barForegroundColor)) {
this.barForegroundColor = barForegroundColor;
repaint();
}
}
public int getMaximum() { return maximum; }
public void setMaximum(final int maximum) {
if (maximum != this.maximum) {
this.maximum = maximum;
if (recalc())
repaint();
}
}
public Color getTextColor() { return textColor; }
public void setTextColor(final Color textColor) {
Objects.requireNonNull(textColor, "textColor");
if (!textColor.equals(this.textColor)) {
this.textColor = textColor;
repaint();
}
}
public int getValue() { return value; }
public void setValue(final int value) {
int newValue = Math.min(maximum, value);
if (newValue != this.value) {
this.value = newValue;
if (recalc())
repaint();
}
}
public boolean isStringPainted() { return stringPainted; }
public void setStringPainted(final boolean stringPainted) {
if (stringPainted != this.stringPainted) {
this.stringPainted = stringPainted;
repaint();
}
}
// Icon
@Override
public int getIconWidth() {
return (impl == null) ? 32 : impl.getIconWidth();
}
@Override
public int getIconHeight() {
return (impl == null) ? 32 : impl.getIconHeight();
}
@Override
public void paintIcon(final Component c, final Graphics graphics, final int x, final int y) {
if (impl != null)
impl.paintIcon(c, graphics, x, y);
Graphics2D g = (Graphics2D)graphics.create();
g.setComposite(AlphaComposite.SrcOver.derive(alpha));
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = getIconWidth();
int h = getIconHeight();
g.setColor(barForegroundColor);
g.fillArc(x, y, w, h, -270, arcAngle);
if (stringPainted) {
g.setColor(textColor);
g.setFont(new Font(Font.DIALOG, Font.BOLD, Math.max(12, h / 4)));
FontMetrics fm = g.getFontMetrics();
String text = percent + "%";
g.drawString(
text,
x + w / 2 - fm.stringWidth(text) / 2,
y + h / 2 - fm.getHeight() / 2 + fm.getAscent()
);
}
g.dispose();
}
// private
private boolean recalc() {
int newPercent = (int)((float)(value * 100) / (float)maximum);
int newArcAngle = -(int)((float)newPercent * 3.6f);
if ((newArcAngle != arcAngle) || (newPercent != percent)) {
arcAngle = newArcAngle;
percent = newPercent;
return true; // repaint
}
return false; // skip repaint
}
private void repaint() {
ImageObserver observer = observerRef.get();
if (observer instanceof Component) {
Component.class.cast(observer).repaint();
}
/*
else if ((observer != null) && (impl instanceof ImageIcon)) {
Image i = ImageIcon.class.cast(impl).getImage();
if (i != null) {
observer.imageUpdate(i, ImageObserver.ALLBITS, 0, 0, getIconWidth(), getIconHeight());
}
}
*/
}
}
| apache-2.0 |
reportportal/commons-dao | src/main/java/com/epam/ta/reportportal/commons/querygen/Queryable.java | 1692 | /*
* Copyright 2019 EPAM Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.ta.reportportal.commons.querygen;
import com.epam.ta.reportportal.commons.querygen.query.QuerySupplier;
import org.jooq.Condition;
import java.util.List;
import java.util.Map;
/**
* Can be used to generate SQL queries with help of JOOQ
*
* @author <a href="mailto:andrei_varabyeu@epam.com">Andrei Varabyeu</a>
* @author <a href="mailto:pavel_bortnik@epam.com">Pavel Bortnik</a>
*/
public interface Queryable {
/**
* Builds a query with lazy joins
*
* @return {@link QuerySupplier}
*/
QuerySupplier toQuery();
/**
* Build a map where key is {@link ConditionType} and value is a composite {@link Condition}
* that should be applied either in {@link ConditionType#HAVING} or {@link ConditionType#WHERE} clause
*
* @return Resulted map
*/
Map<ConditionType, Condition> toCondition();
/**
* @return {@link FilterTarget}
*/
FilterTarget getTarget();
/**
* @return Set of {@link FilterCondition}
*/
List<ConvertibleCondition> getFilterConditions();
boolean replaceSearchCriteria(FilterCondition oldCondition, FilterCondition newCondition);
} | apache-2.0 |
ehensin/ehensin-pt | src/main/java/com/ehensin/pt/db/BaseDAO.java | 4535 | /* @()DataImportBaseHandler.java
*
* (c) COPYRIGHT 1998-2010 Newcosoft INC. All rights reserved.
* Newcosoft CONFIDENTIAL PROPRIETARY
* Newcosoft Advanced Technology and Software Operations
*
* REVISION HISTORY:
* Author Date Brief Description
* ----------------- ---------- ---------------------------------------
* hhbzzd 上午10:49:10 init version
*
*/
package com.ehensin.pt.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <pre>
* CLASS:
* Describe class, extends and implements relationships to other classes.
*
* RESPONSIBILITIES:
* High level list of things that the class does
* -)
*
* COLABORATORS:
* List of descriptions of relationships with other classes, i.e. uses, contains, creates, calls...
* -) class relationship
* -) class relationship
*
* USAGE:
* Description of typical usage of class. Include code samples.
*
*
**/
public abstract class BaseDAO {
private final Logger log = LoggerFactory.getLogger(BaseDAO.class);
public Object fetch(String sql, Object[] args) throws SQLException {
PreparedStatement pstmt = null;
Connection con = ConnectionFactory.getInstance().getConnection();
try {
if (sql == null || sql.isEmpty())
return null;
//log.debug("sql:" + sql);
pstmt = con.prepareStatement(sql);
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof String) {
pstmt.setString(i + 1, (String) args[i]);
} else if (args[i] instanceof Integer) {
pstmt.setInt(i + 1, (Integer) args[i]);
} else if (args[i] instanceof Long) {
pstmt.setLong(i + 1, (Long) args[i]);
} else if (args[i] instanceof Timestamp) {
pstmt.setTimestamp(i + 1, (Timestamp) args[i]);
} else {
pstmt.setObject(i + 1, args[i]);
}
}
}
ResultSet set = pstmt.executeQuery();
return this.build(set);
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw e;
} finally {
ConnectionFactory.getInstance().close(con, pstmt);
}
}
public void update(String sql, Object p) throws SQLException {
PreparedStatement pstmt = null;
Connection con = ConnectionFactory.getInstance().getConnection();
try {
log.debug("sql:" + sql);
pstmt = con.prepareStatement(sql);
prepareStatment(pstmt, p);
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
log.error(e.getMessage(), e);
try {
con.rollback();
} catch (SQLException e2) {
log.error(e2.getMessage(), e2);
}
throw e;
} finally {
ConnectionFactory.getInstance().close(con, pstmt);
}
}
public void update(String sql, List<Object> p) throws SQLException {
PreparedStatement pstmt = null;
Connection con = ConnectionFactory.getInstance().getConnection();
try {
log.debug("sql:" + sql);
pstmt = con.prepareStatement(sql);
if (p != null)
for (int i = 0; i < p.size(); i++) {
pstmt.setObject(i + 1, p.get(i));
}
pstmt.executeUpdate();
con.commit();
} catch (SQLException e) {
log.error(e.getMessage(), e);
try {
con.rollback();
} catch (SQLException e2) {
log.error(e2.getMessage(), e2);
}
throw e;
} finally {
ConnectionFactory.getInstance().close(con, pstmt);
}
}
public void batchUpdate(String sql, java.util.List<List<Object>> list)
throws SQLException {
PreparedStatement pstmt = null;
Connection con = ConnectionFactory.getInstance().getConnection();
try {
pstmt = con.prepareStatement(sql);
if (list != null)
for (List<Object> objs : list) {
for (int i = 0; i < objs.size(); i++) {
pstmt.setObject(i + 1, objs.get(i));
}
pstmt.addBatch();
}
pstmt.executeBatch();
con.commit();
} catch (Exception e) {
log.error(e.getMessage(), e);
try {
con.rollback();
} catch (SQLException e2) {
log.error(e2.getMessage(), e2);
}
} finally {
ConnectionFactory.getInstance().close(con, pstmt);
}
}
/**
* 子类需要实现该接口以便能够将返回的数据集转化成合适的业务对象
* */
protected abstract Object build(ResultSet set) throws SQLException;
/**
* 子类需要实现该接口用来提供SQL语句的参数
* */
protected abstract void prepareStatment(PreparedStatement pstmt,
Object parameter);
}
| apache-2.0 |
tiarebalbi/spring-data-dynamodb | src/main/java/org/socialsignin/spring/data/dynamodb/repository/util/EntityInformationProxyPostProcessor.java | 2091 | /**
* Copyright © 2018 spring-data-dynamodb (https://github.com/boostchicken/spring-data-dynamodb)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.socialsignin.spring.data.dynamodb.repository.util;
import org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBEntityInformation;
import org.socialsignin.spring.data.dynamodb.repository.support.SimpleDynamoDBCrudRepository;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.support.RepositoryProxyPostProcessor;
public abstract class EntityInformationProxyPostProcessor<T, ID> implements RepositoryProxyPostProcessor {
protected abstract void registeredEntity(DynamoDBEntityInformation<T, ID> entityInformation);
@Override
public final void postProcess(ProxyFactory factory, RepositoryInformation repositoryInformation) {
try {
TargetSource targetSource = factory.getTargetSource();
// assert
// targetSource.getTargetClass().equals(SimpleDynamoDBCrudRepository.class);
@SuppressWarnings("unchecked")
SimpleDynamoDBCrudRepository<T, ID> target = SimpleDynamoDBCrudRepository.class
.cast(targetSource.getTarget());
assert target != null;
DynamoDBEntityInformation<T, ID> entityInformation = target.getEntityInformation();
registeredEntity(entityInformation);
} catch (Exception e) {
throw new RuntimeException("Could not extract SimpleDynamoDBCrudRepository from " + factory, e);
}
}
}
| apache-2.0 |
dweiss/forbidden-apis | src/test/java/de/thetaphi/forbiddenapis/CheckerSetupTest.java | 5069 | /*
* (C) Copyright Uwe Schindler (Generics Policeman) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.thetaphi.forbiddenapis;
import static de.thetaphi.forbiddenapis.Checker.Option.*;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import static org.junit.Assume.assumeNoException;
import java.util.Collections;
import java.util.EnumSet;
import org.junit.Before;
import org.junit.Test;
import org.objectweb.asm.commons.Method;
public final class CheckerSetupTest {
protected Checker checker;
protected Signatures forbiddenSignatures;
@Before
public void setUp() {
checker = new Checker(StdIoLogger.INSTANCE, ClassLoader.getSystemClassLoader(), FAIL_ON_MISSING_CLASSES, FAIL_ON_VIOLATION, FAIL_ON_UNRESOLVABLE_SIGNATURES);
assumeTrue("This test only works with a supported JDK (see docs)", checker.isSupportedJDK);
assertEquals(EnumSet.of(FAIL_ON_MISSING_CLASSES, FAIL_ON_VIOLATION, FAIL_ON_UNRESOLVABLE_SIGNATURES), checker.options);
forbiddenSignatures = checker.forbiddenSignatures;
}
@Test
public void testEmpty() {
assertEquals(Collections.emptyMap(), forbiddenSignatures.signatures);
assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns);
assertTrue(checker.hasNoSignatures());
}
@Test
public void testClassSignature() throws Exception {
checker.parseSignaturesString("java.lang.Object @ Foobar");
assertEquals(Collections.singletonMap(Signatures.getKey("java/lang/Object"), "java.lang.Object [Foobar]"), forbiddenSignatures.signatures);
assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns);
}
@Test
public void testClassPatternSignature() throws Exception {
checker.parseSignaturesString("java.lang.** @ Foobar");
assertEquals(Collections.emptyMap(), forbiddenSignatures.signatures);
assertEquals(Collections.singleton(new ClassPatternRule("java.lang.**", "Foobar")),
forbiddenSignatures.classPatterns);
}
@Test
public void testFieldSignature() throws Exception {
checker.parseSignaturesString("java.lang.String#CASE_INSENSITIVE_ORDER @ Foobar");
assertEquals(Collections.singletonMap(Signatures.getKey("java/lang/String", "CASE_INSENSITIVE_ORDER"), "java.lang.String#CASE_INSENSITIVE_ORDER [Foobar]"),
forbiddenSignatures.signatures);
assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns);
}
@Test
public void testMethodSignature() throws Exception {
checker.parseSignaturesString("java.lang.Object#toString() @ Foobar");
assertEquals(Collections.singletonMap(Signatures.getKey("java/lang/Object", new Method("toString", "()Ljava/lang/String;")), "java.lang.Object#toString() [Foobar]"),
forbiddenSignatures.signatures);
assertEquals(Collections.emptySet(), forbiddenSignatures.classPatterns);
}
@Test
public void testEmptyCtor() throws Exception {
Checker chk = new Checker(StdIoLogger.INSTANCE, ClassLoader.getSystemClassLoader());
assertEquals(EnumSet.noneOf(Checker.Option.class), chk.options);
}
@Test
public void testRuntimeClassSignatures() throws Exception {
String internalName = "java/lang/String";
ClassSignature cs = checker.lookupRelatedClass(internalName, internalName);
assertTrue(cs.isRuntimeClass);
assertTrue(cs.signaturePolymorphicMethods.isEmpty());
}
@Test
public void testSignaturePolymorphic() throws Exception {
try {
String internalName = "java/lang/invoke/MethodHandle";
ClassSignature cs = checker.lookupRelatedClass(internalName, internalName);
assertTrue(cs.signaturePolymorphicMethods.contains("invoke"));
assertTrue(cs.signaturePolymorphicMethods.contains("invokeExact"));
// System.out.println(cs.signaturePolymorphicMethods);
} catch (RelatedClassLoadingException we) {
assertTrue(we.getCause() instanceof ClassNotFoundException);
assumeNoException("This test only works with Java 7+", we);
}
}
@Test
public void testJava9ModuleSystemFallback() {
final Class<?> moduleClass;
try {
moduleClass = Class.forName("java.lang.Module");
} catch (ClassNotFoundException cfe) {
assumeNoException("This test only works with Java 9+", cfe);
return;
}
assertNotNull(checker.method_Class_getModule);
assertSame(moduleClass, checker.method_Class_getModule.getReturnType());
assertNotNull(checker.method_Module_getName);
assertSame(moduleClass, checker.method_Module_getName.getDeclaringClass());
}
}
| apache-2.0 |
akihito104/UdonRoad | app/src/main/java/com/freshdigitable/udonroad/media/ThumbnailContainer.java | 4398 | /*
* Copyright (c) 2016. Matsuda, Akihit (akihito104)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshdigitable.udonroad.media;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.freshdigitable.udonroad.R;
import twitter4j.MediaEntity;
/**
* MediaContainer is view group contains image thumbnails.
*
* Created by akihit on 2016/07/10.
*/
public class ThumbnailContainer extends LinearLayout {
private final int grid;
private final int maxThumbCount;
private int thumbWidth;
private int thumbCount;
public ThumbnailContainer(Context context) {
this(context, null);
}
public ThumbnailContainer(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ThumbnailContainer(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
grid = getResources().getDimensionPixelSize(R.dimen.grid_margin);
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.ThumbnailContainer, defStyleAttr, 0);
try {
maxThumbCount = a.getInt(R.styleable.ThumbnailContainer_thumbCount, 0);
} finally {
a.recycle();
}
if (isInEditMode()) {
setThumbCount(maxThumbCount);
}
}
public int getThumbCount() {
return thumbCount;
}
public int getThumbWidth() {
return Math.max(thumbWidth, 0);
}
public void bindMediaEntities(MediaEntity[] mediaEntities) {
final int mediaCount = mediaEntities.length;
bindMediaEntities(mediaCount);
}
public void bindMediaEntities(int mediaCount) {
final int thumbCount = Math.min(maxThumbCount, mediaCount);
if (thumbCount < 1) {
setThumbCount(0);
setVisibility(GONE);
return;
}
setThumbCount(thumbCount);
thumbWidth = calcThumbWidth();
setVisibility(VISIBLE);
for (int i = 0; i < thumbCount; i++) {
final int num = i;
final View mediaView = getChildAt(i);
mediaView.setVisibility(VISIBLE);
mediaView.setOnClickListener(view -> {
if (mediaClickListener == null) {
return;
}
mediaClickListener.onMediaClicked(view, num);
});
}
}
private int calcThumbWidth() {
return calcThumbWidth(getWidth());
}
private int calcThumbWidth(int containerWidth) {
final int w = thumbCount > 0 ? (containerWidth - grid * (thumbCount - 1)) / thumbCount : -1;
return w > 0 ? w : getLayoutParams().width;
}
private void setThumbCount(int count) {
this.thumbCount = count;
final int size = getChildCount();
if (count < size) {
for (int i = size - 1; i >= count; i--) {
final View v = getChildAt(i);
v.setVisibility(GONE);
}
return;
}
for (int i = 0; i < count - size; i++) {
final ThumbnailView thumbnailView = new ThumbnailView(getContext());
final LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1);
if (size + i >= 1) {
lp.leftMargin = grid;
}
addView(thumbnailView, -1, lp);
}
}
public void reset() {
setVisibility(GONE);
for (int i = 0; i < thumbCount; i++) {
final ImageView mi = (ImageView) getChildAt(i);
mi.setOnClickListener(null);
mi.setVisibility(GONE);
}
thumbCount = 0;
}
private OnMediaClickListener mediaClickListener;
public void setOnMediaClickListener(OnMediaClickListener mediaClickListener) {
this.mediaClickListener = mediaClickListener;
}
public interface OnMediaClickListener {
void onMediaClicked(View view, int index);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
thumbWidth = calcThumbWidth(w);
}
}
| apache-2.0 |
InfoSec812/vertx-web | vertx-template-engines/vertx-web-templ-jte/src/main/java/io/vertx/ext/web/templ/jte/impl/VertxDirectoryCodeResolver.java | 2422 | /*
* Copyright 2014 Red Hat, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.web.templ.jte.impl;
import gg.jte.CodeResolver;
import io.vertx.core.Vertx;
import io.vertx.ext.web.common.WebEnvironment;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* @author <a href="mailto:andy@mazebert.com">Andreas Hager</a>
*/
public class VertxDirectoryCodeResolver implements CodeResolver {
private final Vertx vertx;
private final Path templateRootDirectory;
private final ConcurrentMap<String, Long> modificationTimes;
public VertxDirectoryCodeResolver(Vertx vertx, String templateRootDirectory) {
this.vertx = vertx;
this.templateRootDirectory = Paths.get(templateRootDirectory);
if (WebEnvironment.development()) {
modificationTimes = new ConcurrentHashMap<>();
} else {
modificationTimes = null;
}
}
public String resolve(String name) {
name = templateRootDirectory.resolve(name).toString();
String templateCode = vertx.fileSystem().readFileBlocking(name).toString();
if (templateCode == null) {
return null;
}
if (modificationTimes != null) {
modificationTimes.put(name, this.getLastModified(name));
}
return templateCode;
}
public boolean hasChanged(String name) {
if (modificationTimes == null) {
return false;
}
name = templateRootDirectory.resolve(name).toString();
Long lastResolveTime = this.modificationTimes.get(name);
if (lastResolveTime == null) {
return true;
} else {
long lastModified = this.getLastModified(name);
return lastModified != lastResolveTime;
}
}
private long getLastModified(String name) {
return vertx.fileSystem().propsBlocking(name).lastModifiedTime();
}
public void clear() {
if (modificationTimes != null) {
modificationTimes.clear();
}
}
}
| apache-2.0 |
nkasvosve/beyondj | beyondj-high-availability/beyondj-high-availability-hazelcast/src/main/java/com/lenox/beyondj/ha/management/HazelcastServiceManagementRequestListener.java | 3506 | package com.lenox.beyondj.ha.management;
import com.beyondj.gateway.model.HttpProxyRuleBase;
import com.hazelcast.core.*;
import com.hazelcast.map.listener.*;
import com.lenox.beyond.launch.DeploymentManagement;
import com.lenox.beyondj.ha.HazelcastHolder;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
/**
* @author nickk
*/
public class HazelcastServiceManagementRequestListener
implements EntryAddedListener<String, DeploymentManagement>,
EntryRemovedListener<String, DeploymentManagement>,
EntryUpdatedListener<String, DeploymentManagement>,
EntryEvictedListener<String, DeploymentManagement>,
MapEvictedListener,
MapClearedListener {
private HazelcastInstance hazelcastInstance;
private Set<ServiceManagementCallback> callBacks = new HashSet<>();
public HazelcastServiceManagementRequestListener(String configFile) throws Exception {
Validate.notBlank(configFile, "configFile must not be blank");
hazelcastInstance = HazelcastHolder.INSTANCE.getHazelcastInstance(configFile);
if (hazelcastInstance == null) {
throw new IllegalStateException("Could not create hazelcast instance");
}
}
public String getLocalEndpoint() {
return hazelcastInstance.getLocalEndpoint().getSocketAddress().toString();
}
public void addServiceDiscoveryCallback(ServiceManagementCallback callback) {
callBacks.add(callback);
}
@PostConstruct
public void listen() {
if (hazelcastInstance != null) {
IMap map = hazelcastInstance.getMap(HazelcastServiceManagementDelegate.SERVICE_MANAGEMENT_REQUEST);
map.addEntryListener(this, true);
if (LOG.isDebugEnabled())
LOG.debug("Now listening on: " + HazelcastServiceManagementDelegate.SERVICE_MANAGEMENT_REQUEST);
} else {
throw new IllegalStateException("Could not create hazelcast instance to listen through");
}
}
private static Logger LOG = LoggerFactory.getLogger(HazelcastServiceManagementRequestListener.class);
@Override
public void entryAdded(EntryEvent<String, DeploymentManagement> entryEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.entryAdded(entryEvent);
}
}
@Override
public void entryEvicted(EntryEvent<String, DeploymentManagement> entryEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.entryEvicted(entryEvent);
}
}
@Override
public void entryRemoved(EntryEvent<String, DeploymentManagement> entryEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.entryRemoved(entryEvent);
}
}
@Override
public void entryUpdated(EntryEvent<String, DeploymentManagement> entryEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.entryUpdated(entryEvent);
}
}
@Override
public void mapCleared(MapEvent mapEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.mapCleared(mapEvent);
}
}
@Override
public void mapEvicted(MapEvent mapEvent) {
for (ServiceManagementCallback callback : callBacks) {
callback.mapEvicted(mapEvent);
}
}
}
| apache-2.0 |
consulo/consulo-java | java-analysis-impl/src/main/java/com/intellij/codeInspection/dataFlow/instructions/PushValueInstruction.java | 1672 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.dataFlow.instructions;
import com.intellij.codeInspection.dataFlow.DfaMemoryState;
import com.intellij.codeInspection.dataFlow.types.DfType;
import com.intellij.codeInspection.dataFlow.value.DfaValue;
import com.intellij.codeInspection.dataFlow.value.DfaValueFactory;
import com.intellij.psi.PsiExpression;
import javax.annotation.Nonnull;
/**
* An instruction that pushes the value of given DfType to the stack
*/
public class PushValueInstruction extends EvalInstruction
{
private final
@Nonnull
DfType myValue;
public PushValueInstruction(@Nonnull DfType value, PsiExpression place)
{
super(place, 0);
myValue = value;
}
public PushValueInstruction(@Nonnull DfType value)
{
this(value, null);
}
public
@Nonnull
DfType getValue()
{
return myValue;
}
@Override
public
@Nonnull
DfaValue eval(@Nonnull DfaValueFactory factory, @Nonnull DfaMemoryState state, @Nonnull DfaValue... arguments)
{
return factory.fromDfType(myValue);
}
public String toString()
{
return "PUSH_VAL " + myValue;
}
}
| apache-2.0 |
zempty/threex | src/main/java/com/zhu2chu/all/bus/h2/H2ServerHandler.java | 1413 | package com.zhu2chu.all.bus.h2;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
/**
* 2017年5月1日 18:02:51 此方法主要用于判断是否有权限访问h2控制台。真正响应页面的还是WebServlet。
*
* @author ThreeX
* @link http://www.zhu2chu.com
*
*/
public class H2ServerHandler extends Handler {
private static final Log log = Log.getLog(H2ServerHandler.class);
private boolean isPermitted = true;
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
String uri = request.getRequestURI();
// 如果uri以/console开头,统一为进入数据库后台的控制台。
if (uri.startsWith("/console")) {
boolean enableWS = PropKit.getBoolean("enableWebServer", false);
if (enableWS) {
if (isPermitted) {
isHandled[0] = false; // jfinal未处理,留给容器处理。
return;
} else {
HandlerKit.renderError404(request, response, isHandled);
return;
}
}
}
next.handle(target, request, response, isHandled);
}
}
| apache-2.0 |
MohamedRamzy/HappyMoments | app/src/main/java/com/example/android/sunshine/app/DetailActivity.java | 3262 | package com.example.android.sunshine.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.android.sunshine.app.entity.Moment;
public class DetailActivity extends ActionBarActivity {
private final String LOG_TAG = DetailActivity.class.getSimpleName();
private final String HAPPYMOMENTS_APP_HASHTAG = "#HappyMoments";
private Moment moment;
private ShareActionProvider mShareActionProvider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(getString(R.string.app_name));
Intent intent = getIntent();
if(intent != null && intent.getParcelableExtra("moment") != null){
moment = intent.getParcelableExtra("moment");
View detailView = findViewById(R.id.detail_view);
ViewHolder holder = new ViewHolder(detailView);
detailView.setTag(holder);
holder.momentIcon.setImageResource(R.drawable.heart_logo);
holder.momentText.setText(moment.getMoment());
holder.momentDate.setText(moment.getDay());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.detail, menu);
MenuItem shareItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
String shareString = "";
if(moment != null){
shareString += moment.getMoment()+" - "+moment.getDay() + "\n " + HAPPYMOMENTS_APP_HASHTAG;
}else{
shareString = HAPPYMOMENTS_APP_HASHTAG;
}
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
mShareActionProvider.setShareIntent(shareIntent);
// Log.v(LOG_TAG, shareString);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
/* Private View Holder Class*/
private class ViewHolder{
ImageView momentIcon;
TextView momentText;
TextView momentDate;
public ViewHolder(View convertView) {
this.momentIcon = (ImageView) convertView.findViewById(R.id.imageView);
this.momentText = (TextView) convertView.findViewById(R.id.main_moment_textview);
this.momentDate = (TextView) convertView.findViewById(R.id.moment_date_textView);
}
}
}
| apache-2.0 |
fpompermaier/onvif | onvif-ws-client/src/main/java/org/onvif/ver10/search/wsdl/FindMetadata.java | 5859 |
package org.onvif.ver10.search.wsdl;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.cxf.xjc.runtime.JAXBToStringStyle;
import org.onvif.ver10.schema.MetadataFilter;
import org.onvif.ver10.schema.SearchScope;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="StartPoint" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="EndPoint" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="Scope" type="{http://www.onvif.org/ver10/schema}SearchScope"/>
* <element name="MetadataFilter" type="{http://www.onvif.org/ver10/schema}MetadataFilter"/>
* <element name="MaxMatches" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="KeepAliveTime" type="{http://www.w3.org/2001/XMLSchema}duration"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"startPoint",
"endPoint",
"scope",
"metadataFilter",
"maxMatches",
"keepAliveTime"
})
@XmlRootElement(name = "FindMetadata")
public class FindMetadata {
@XmlElement(name = "StartPoint", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar startPoint;
@XmlElement(name = "EndPoint")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar endPoint;
@XmlElement(name = "Scope", required = true)
protected SearchScope scope;
@XmlElement(name = "MetadataFilter", required = true)
protected MetadataFilter metadataFilter;
@XmlElement(name = "MaxMatches")
protected Integer maxMatches;
@XmlElement(name = "KeepAliveTime", required = true)
protected Duration keepAliveTime;
/**
* Gets the value of the startPoint property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartPoint() {
return startPoint;
}
/**
* Sets the value of the startPoint property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartPoint(XMLGregorianCalendar value) {
this.startPoint = value;
}
/**
* Gets the value of the endPoint property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEndPoint() {
return endPoint;
}
/**
* Sets the value of the endPoint property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEndPoint(XMLGregorianCalendar value) {
this.endPoint = value;
}
/**
* Gets the value of the scope property.
*
* @return
* possible object is
* {@link SearchScope }
*
*/
public SearchScope getScope() {
return scope;
}
/**
* Sets the value of the scope property.
*
* @param value
* allowed object is
* {@link SearchScope }
*
*/
public void setScope(SearchScope value) {
this.scope = value;
}
/**
* Gets the value of the metadataFilter property.
*
* @return
* possible object is
* {@link MetadataFilter }
*
*/
public MetadataFilter getMetadataFilter() {
return metadataFilter;
}
/**
* Sets the value of the metadataFilter property.
*
* @param value
* allowed object is
* {@link MetadataFilter }
*
*/
public void setMetadataFilter(MetadataFilter value) {
this.metadataFilter = value;
}
/**
* Gets the value of the maxMatches property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getMaxMatches() {
return maxMatches;
}
/**
* Sets the value of the maxMatches property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setMaxMatches(Integer value) {
this.maxMatches = value;
}
/**
* Gets the value of the keepAliveTime property.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getKeepAliveTime() {
return keepAliveTime;
}
/**
* Sets the value of the keepAliveTime property.
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setKeepAliveTime(Duration value) {
this.keepAliveTime = value;
}
/**
* Generates a String representation of the contents of this type.
* This is an extension method, produced by the 'ts' xjc plugin
*
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE);
}
}
| apache-2.0 |
sghill/gocd | server/src/com/thoughtworks/go/server/service/AgentService.java | 18088 | /*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.service;
import com.thoughtworks.go.config.AgentConfig;
import com.thoughtworks.go.config.Agents;
import com.thoughtworks.go.domain.AgentInstance;
import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.listener.AgentChangeListener;
import com.thoughtworks.go.presentation.TriStateSelection;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.security.Registration;
import com.thoughtworks.go.server.domain.Agent;
import com.thoughtworks.go.server.domain.AgentInstances;
import com.thoughtworks.go.server.domain.ElasticAgentMetadata;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.persistence.AgentDao;
import com.thoughtworks.go.server.service.result.HttpOperationResult;
import com.thoughtworks.go.server.service.result.LocalizedOperationResult;
import com.thoughtworks.go.server.service.result.OperationResult;
import com.thoughtworks.go.server.ui.AgentViewModel;
import com.thoughtworks.go.server.ui.AgentsViewModel;
import com.thoughtworks.go.server.util.UuidGenerator;
import com.thoughtworks.go.serverhealth.HealthStateScope;
import com.thoughtworks.go.serverhealth.HealthStateType;
import com.thoughtworks.go.serverhealth.ServerHealthService;
import com.thoughtworks.go.serverhealth.ServerHealthState;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TimeProvider;
import com.thoughtworks.go.util.TriState;
import com.thoughtworks.go.utils.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import java.util.*;
import static java.lang.String.format;
@Service
public class AgentService {
private final SystemEnvironment systemEnvironment;
private final AgentConfigService agentConfigService;
private final SecurityService securityService;
private final EnvironmentConfigService environmentConfigService;
private final UuidGenerator uuidGenerator;
private final ServerHealthService serverHealthService;
private final AgentDao agentDao;
private AgentInstances agentInstances;
private static final Logger LOGGER = LoggerFactory.getLogger(AgentService.class);
@Autowired
public AgentService(AgentConfigService agentConfigService, SystemEnvironment systemEnvironment, final EnvironmentConfigService environmentConfigService,
SecurityService securityService, AgentDao agentDao, UuidGenerator uuidGenerator, ServerHealthService serverHealthService,
final EmailSender emailSender, TimeProvider timeProvider) {
this(agentConfigService, systemEnvironment, null, environmentConfigService, securityService, agentDao, uuidGenerator, serverHealthService);
this.agentInstances = new AgentInstances(new AgentRuntimeStatus.ChangeListener() {
public void statusUpdateRequested(AgentRuntimeInfo runtimeInfo, AgentRuntimeStatus newStatus) {
}
}, timeProvider);
}
AgentService(AgentConfigService agentConfigService, SystemEnvironment systemEnvironment, AgentInstances agentInstances,
EnvironmentConfigService environmentConfigService, SecurityService securityService, AgentDao agentDao, UuidGenerator uuidGenerator,
ServerHealthService serverHealthService) {
this.systemEnvironment = systemEnvironment;
this.agentConfigService = agentConfigService;
this.environmentConfigService = environmentConfigService;
this.securityService = securityService;
this.agentInstances = agentInstances;
this.agentDao = agentDao;
this.uuidGenerator = uuidGenerator;
this.serverHealthService = serverHealthService;
}
public void initialize() {
this.sync(this.agentConfigService.agents());
agentConfigService.register(new AgentChangeListener(this));
}
public void sync(Agents agents) {
agentInstances.sync(agents);
}
public List<String> getUniqueAgentNames() {
return new ArrayList<>(agentInstances.getAllHostNames());
}
public List<String> getUniqueIPAddresses() {
return new ArrayList<>(agentInstances.getAllIpAddresses());
}
public List<String> getUniqueAgentOperatingSystems() {
return new ArrayList<>(agentInstances.getAllOperatingSystems());
}
AgentInstances agents() {
return agentInstances;
}
public Map<AgentInstance, Collection<String>> agentEnvironmentMap() {
Map<AgentInstance, Collection<String>> allAgents = new LinkedHashMap<>();
for (AgentInstance agentInstance : agentInstances.allAgents()) {
allAgents.put(agentInstance, environmentConfigService.environmentsFor(agentInstance.getUuid()));
}
return allAgents;
}
public AgentsViewModel registeredAgents() {
return toAgentViewModels(agentInstances.findRegisteredAgents());
}
private AgentsViewModel toAgentViewModels(AgentInstances instances) {
AgentsViewModel agents = new AgentsViewModel();
for (AgentInstance instance : instances) {
agents.add(toAgentViewModel(instance));
}
return agents;
}
private AgentViewModel toAgentViewModel(AgentInstance instance) {
return new AgentViewModel(instance, environmentConfigService.environmentsFor(instance.getUuid()));
}
public AgentInstances findRegisteredAgents() {
return agentInstances.findRegisteredAgents();
}
private boolean isUnknownAgent(AgentInstance agentInstance, OperationResult operationResult) {
if (agentInstance.isNullAgent()) {
String agentNotFoundMessage = String.format("Agent '%s' not found", agentInstance.getUuid());
operationResult.notFound("Agent not found.", agentNotFoundMessage, HealthStateType.general(HealthStateScope.GLOBAL));
return true;
}
return false;
}
private boolean hasOperatePermission(Username username, OperationResult operationResult) {
if (!securityService.hasOperatePermissionForAgents(username)) {
String message = "Unauthorized to operate on agent";
operationResult.unauthorized(message, message, HealthStateType.general(HealthStateScope.GLOBAL));
return false;
}
return true;
}
public AgentInstance updateAgentAttributes(Username username, HttpOperationResult result, String uuid, String newHostname, String resources, String environments, TriState enable) {
if (!hasOperatePermission(username, result)) {
return null;
}
AgentInstance agentInstance = findAgent(uuid);
if (isUnknownAgent(agentInstance, result)) {
return null;
}
AgentConfig agentConfig = agentConfigService.updateAgentAttributes(uuid, username, newHostname, resources, environments, enable, agentInstances, result);
if (agentConfig != null) {
return AgentInstance.createFromConfig(agentConfig, systemEnvironment);
}
return null;
}
public void bulkUpdateAgentAttributes(Username username, LocalizedOperationResult result, List<String> uuids, List<String> resourcesToAdd, List<String> resourcesToRemove, List<String> environmentsToAdd, List<String> environmentsToRemove, TriState enable) {
agentConfigService.bulkUpdateAgentAttributes(agentInstances, username, result, uuids, resourcesToAdd, resourcesToRemove, environmentsToAdd, environmentsToRemove, enable);
}
public void enableAgents(Username username, OperationResult operationResult, List<String> uuids) {
if (!hasOperatePermission(username, operationResult)) {
return;
}
List<AgentInstance> agents = new ArrayList<>();
if (!populateAgentInstancesForUUIDs(operationResult, uuids, agents)) {
return;
}
try {
agentConfigService.enableAgents(username, agents.toArray((new AgentInstance[0])));
operationResult.ok(String.format("Enabled %s agent(s)", uuids.size()));
} catch (Exception e) {
operationResult.internalServerError("Enabling agents failed:" + e.getMessage(), HealthStateType.general(HealthStateScope.GLOBAL));
}
}
public void disableAgents(Username username, OperationResult operationResult, List<String> uuids) {
if (!hasOperatePermission(username, operationResult)) {
return;
}
List<AgentInstance> agents = new ArrayList<>();
if (!populateAgentInstancesForUUIDs(operationResult, uuids, agents)) {
return;
}
try {
agentConfigService.disableAgents(username, agents.toArray(new AgentInstance[0]));
operationResult.ok(String.format("Disabled %s agent(s)", uuids.size()));
} catch (Exception e) {
operationResult.internalServerError("Disabling agents failed:" + e.getMessage(), HealthStateType.general(HealthStateScope.GLOBAL));
}
}
private boolean populateAgentInstancesForUUIDs(OperationResult operationResult, List<String> uuids, List<AgentInstance> agents) {
for (String uuid : uuids) {
AgentInstance agentInstance = findAgentAndRefreshStatus(uuid);
if (isUnknownAgent(agentInstance, operationResult)) {
return false;
}
agents.add(agentInstance);
}
return true;
}
public void deleteAgents(Username username, HttpOperationResult operationResult, List<String> uuids) {
if (!hasOperatePermission(username, operationResult)) {
return;
}
List<AgentInstance> agents = new ArrayList<>();
if (!populateAgentInstancesForUUIDs(operationResult, uuids, agents)) {
return;
}
for (AgentInstance agentInstance : agents) {
if (!agentInstance.canBeDeleted()) {
operationResult.notAcceptable(String.format("Failed to delete %s agent(s), as agent(s) might not be disabled or are still building.", agents.size()),
HealthStateType.general(HealthStateScope.GLOBAL));
return;
}
}
try {
agentConfigService.deleteAgents(username, agents.toArray(new AgentInstance[0]));
operationResult.ok(String.format("Deleted %s agent(s).", agents.size()));
} catch (Exception e) {
operationResult.internalServerError("Deleting agents failed:" + e.getMessage(), HealthStateType.general(HealthStateScope.GLOBAL));
}
}
public void modifyResources(Username username, HttpOperationResult operationResult, List<String> uuids, List<TriStateSelection> selections) {
if (!hasOperatePermission(username, operationResult)) {
return;
}
List<AgentInstance> agents = new ArrayList<>();
if (!populateAgentInstancesForUUIDs(operationResult, uuids, agents)) {
return;
}
try {
agentConfigService.modifyResources(agents.toArray(new AgentInstance[0]), selections, username);
operationResult.ok(String.format("Resource(s) modified on %s agent(s)", uuids.size()));
} catch (Exception e) {
operationResult.notAcceptable("Could not modify resources:" + e.getMessage(), HealthStateType.general(HealthStateScope.GLOBAL));
}
}
public void modifyEnvironments(Username username, HttpOperationResult operationResult, List<String> uuids, List<TriStateSelection> selections) {
if (!hasOperatePermission(username, operationResult)) {
return;
}
List<AgentInstance> agents = new ArrayList<>();
if (!populateAgentInstancesForUUIDs(operationResult, uuids, agents)) {
return;
}
try {
environmentConfigService.modifyEnvironments(agents, selections);
operationResult.ok(String.format("Environment(s) modified on %s agent(s)", uuids.size()));
} catch (Exception e) {
operationResult.notAcceptable("Could not modify environments:" + e.getMessage(), HealthStateType.general(HealthStateScope.GLOBAL));
}
}
public void updateRuntimeInfo(AgentRuntimeInfo info) {
if (!info.hasCookie()) {
LOGGER.warn("Agent [{}] has no cookie set", info.agentInfoDebugString());
throw new AgentNoCookieSetException(format("Agent [%s] has no cookie set", info.agentInfoDebugString()));
}
if (info.hasDuplicateCookie(agentDao.cookieFor(info.getIdentifier()))) {
LOGGER.warn("Found agent [{}] with duplicate uuid. Please check the agent installation.", info.agentInfoDebugString());
serverHealthService.update(
ServerHealthState.warning(format("[%s] has duplicate unique identifier which conflicts with [%s]", info.agentInfoForDisplay(), findAgentAndRefreshStatus(info.getUUId()).agentInfoForDisplay()),
"Please check the agent installation. Click <a href='https://docs.gocd.org/current/faq/agent_guid_issue.html' target='_blank'>here</a> for more info.",
HealthStateType.duplicateAgent(HealthStateScope.forAgent(info.getCookie())), Timeout.THIRTY_SECONDS));
throw new AgentWithDuplicateUUIDException(format("Agent [%s] has invalid cookie", info.agentInfoDebugString()));
}
AgentInstance agentInstance = findAgentAndRefreshStatus(info.getUUId());
if (agentInstance.isIpChangeRequired(info.getIpAdress())) {
AgentConfig agentConfig = agentInstance.agentConfig();
Username userName = agentUsername(info.getUUId(), info.getIpAdress(), agentConfig.getHostNameForDisplay());
LOGGER.warn("Agent with UUID [{}] changed IP Address from [{}] to [{}]", info.getUUId(), agentConfig.getIpAddress(), info.getIpAdress());
agentConfigService.updateAgentIpByUuid(agentConfig.getUuid(), info.getIpAdress(), userName);
}
agentInstances.updateAgentRuntimeInfo(info);
}
public Username agentUsername(String uuId, String ipAddress, String hostNameForDisplay) {
return new Username(String.format("agent_%s_%s_%s", uuId, ipAddress, hostNameForDisplay));
}
public Registration requestRegistration(Username username, AgentRuntimeInfo agentRuntimeInfo) {
LOGGER.debug("Agent is requesting registration {}", agentRuntimeInfo);
AgentInstance agentInstance = agentInstances.register(agentRuntimeInfo);
Registration registration = agentInstance.assignCertification();
if (agentInstance.isRegistered()) {
agentConfigService.saveOrUpdateAgent(agentInstance, username);
LOGGER.debug("New Agent approved {}", agentRuntimeInfo);
}
return registration;
}
@Deprecated
public void approve(String uuid) {
AgentInstance agentInstance = findAgentAndRefreshStatus(uuid);
agentConfigService.approvePendingAgent(agentInstance);
}
public void notifyJobCancelledEvent(String agentId) {
agentInstances.updateAgentAboutCancelledBuild(agentId, true);
}
public AgentInstance findAgentAndRefreshStatus(String uuid) {
return agentInstances.findAgentAndRefreshStatus(uuid);
}
public AgentInstance findAgent(String uuid) {
return agentInstances.findAgent(uuid);
}
public void clearAll() {
agentInstances.clearAll();
}
/**
* called from spring timer
*/
public void refresh() {
agentInstances.refresh();
}
public void building(String uuid, AgentBuildingInfo agentBuildingInfo) {
agentInstances.building(uuid, agentBuildingInfo);
}
public String assignCookie(AgentIdentifier identifier) {
String cookie = uuidGenerator.randomUuid();
agentDao.associateCookie(identifier, cookie);
return cookie;
}
public Agent findAgentObjectByUuid(String uuid) {
Agent agent;
AgentConfig agentFromConfig = agentConfigService.agents().getAgentByUuid(uuid);
if (agentFromConfig != null && !agentFromConfig.isNull()) {
agent = Agent.fromConfig(agentFromConfig);
} else {
agent = agentDao.agentByUuid(uuid);
}
return agent;
}
public AgentsViewModel filter(List<String> uuids) {
AgentsViewModel viewModels = new AgentsViewModel();
for (AgentInstance agentInstance : agentInstances.filter(uuids)) {
viewModels.add(new AgentViewModel(agentInstance));
}
return viewModels;
}
public AgentViewModel findAgentViewModel(String uuid) {
return toAgentViewModel(findAgentAndRefreshStatus(uuid));
}
public LinkedMultiValueMap<String, ElasticAgentMetadata> allElasticAgents() {
return agentInstances.allElasticAgentsGroupedByPluginId();
}
public AgentInstance findElasticAgent(String elasticAgentId, String elasticPluginId) {
return agentInstances.findElasticAgent(elasticAgentId, elasticPluginId);
}
public AgentInstances findEnabledAgents() {
return agentInstances.findEnabledAgents();
}
public AgentInstances findDisabledAgents() {
return agentInstances.findDisabledAgents();
}
}
| apache-2.0 |
rey5137/VirtualPianoAuto | src/virtualpianoauto/Window.java | 475 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package virtualpianoauto;
import com.sun.jna.platform.win32.WinDef;
/**
*
* @author Rey
*/
public class Window {
public WinDef.HWND hWnd;
public String title;
public Window(WinDef.HWND hWnd, String title){
this.hWnd = hWnd;
this.title = title;
}
}
| apache-2.0 |
efsavage/ajah | ajah-rfcmail/src/main/java/com/ajah/rfcmail/util/MessageUtils.java | 5694 | /*
* Copyright 2011 Eric F. Savage, code@efsavage.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ajah.rfcmail.util;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.ajah.rfcmail.fetch.AjahMimeMessage;
import com.ajah.util.StringUtils;
import com.ajah.util.net.AjahMimeType;
/**
* Utilties for dealing with email messages.
*
* @author <a href="http://efsavage.com">Eric F. Savage</a>, <a
* href="mailto:code@efsavage.com">code@efsavage.com</a>.
*
*/
public class MessageUtils {
private static final Logger log = Logger.getLogger(MessageUtils.class.getName());
/**
* Gets the content of a message as text and removes extra whitespace.
*
* @see #getContentAsText(AjahMimeMessage)
* @param message
* @return The content of a message as text with extra whitespace removed.
* @throws IOException
* @throws MessagingException
*/
public static String getContentAsCleanText(final AjahMimeMessage message) throws MessagingException, IOException {
return removeExtraWhitespace(getContentAsText(message));
}
/**
* Extracts as much text as possible from a message.
*
* @param msg
* The message to extract text from.
* @return The text that was extracted from a message.
* @throws MessagingException
* If the message could not be understood.
* @throws IOException
* If the body of the message could not be read.
*/
public static String getContentAsText(final AjahMimeMessage msg) throws MessagingException, IOException {
if (msg.getAjahMimeType() == AjahMimeType.TEXT_PLAIN) {
// Nothing to do here
return (String) msg.getContent();
} else if (msg.getAjahMimeType() == AjahMimeType.TEXT_HTML && msg.getContent() instanceof String) {
try {
return getHTMLAsText((String) msg.getContent());
} catch (final IllegalArgumentException e) {
throw new MessagingException((String) msg.getContent(), e);
}
}
throw new MessagingException(msg.getAjahMimeType() + " has a " + msg.getContent().getClass().getName());
}
/**
* Extracts as much text as possible from a message part.
*
* @param bodyPart
* The message part to extract text from.
* @return The text that was extracted from a message part.
* @throws MessagingException
* If the message part could not be understood.
* @throws IOException
* If the message part could not be read.
*/
public static String getContentAsText(final BodyPart bodyPart) throws MessagingException, IOException {
final AjahMimeType ajahMimeType = AjahMimeType.get(bodyPart.getContentType());
switch (ajahMimeType) {
case TEXT_PLAIN:
return (String) bodyPart.getContent();
case TEXT_HTML:
return getHTMLAsText((String) bodyPart.getContent());
default:
throw new MessagingException("Can't process " + bodyPart.getContentType());
}
}
/**
* Returns the specified header, if it exists. If more than one matching
* header exists, returns the first non-blank one. If a
* {@link MessagingException} occurs while reading the header, returns null.
*
* @param message
* The message to extra headers from, required.
* @param headerName
* The headerName to extract, required.
* @return The value of the specified header, if it exists.
*/
public static String getHeaderSafe(final Message message, final String headerName) {
String[] headers;
try {
headers = message.getHeader(headerName);
} catch (final MessagingException e) {
log.log(Level.WARNING, e.getMessage(), e);
return null;
}
if (headers == null || headers.length == 0) {
return null;
}
if (headers.length == 1) {
return headers[0];
}
for (final String header : headers) {
if (!StringUtils.isBlank(header)) {
return header;
}
}
return null;
}
private static String getHTMLAsText(final String html) {
final Document doc = Jsoup.parse(html);
final String text = doc.body().text();
return text;
}
/**
* Determines if the message is text/html.
*
* @param msg
* The message to inspect.
* @return true if the message is text/html, otherwise false.
* @throws MessagingException
*/
public static boolean isHtml(final AjahMimeMessage msg) throws MessagingException {
return msg != null && (msg.getAjahMimeType() == AjahMimeType.TEXT_HTML);
}
/**
* Determines if the message part is text/html.
*
* @param bodyPart
* The message part to inspect.
* @return true if the message part is text/html, otherwise false.
* @throws MessagingException
*/
public static boolean isHtml(final BodyPart bodyPart) throws MessagingException {
return bodyPart != null && (AjahMimeType.get(bodyPart.getContentType()) == AjahMimeType.TEXT_HTML);
}
private static String removeExtraWhitespace(final String text) {
final String retVal = text.replaceAll("\\\\r", "\\\\n").replaceAll("\\\\n+", "\\\\n");
return retVal.trim();
}
}
| apache-2.0 |
codders/k2-sling-fork | bundles/api/src/main/java/org/apache/sling/api/servlets/ServletResolver.java | 2641 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.api.servlets;
import javax.servlet.Servlet;
import org.apache.sling.api.SlingHttpServletRequest;
/**
* The <code>ServletResolver</code> defines the API for a service capable of
* resolving <code>javax.servlet.Servlet</code> instances to handle the
* processing of a request or resource.
* <p>
* Applications of the Sling Framework generally do not need the servlet
* resolver as resolution of the servlets to process requests and sub-requests
* through a <code>RequestDispatcher</code> is handled by the Sling Framework.
* <p>
*/
public interface ServletResolver {
/**
* Resolves a <code>javax.servlet.Servlet</code> whose
* <code>service</code> method may be used to handle the given
* <code>request</code>.
* <p>
* The returned servlet must be assumed to be initialized and ready to run.
* That is, the <code>init</code> nor the <code>destroy</code> methods
* must <em>NOT</em> be called on the returned servlet.
* <p>
* This method must not return a <code>Servlet</code> instance
* implementing the {@link OptingServlet} interface and returning
* <code>false</code> when the
* {@link OptingServlet#accepts(SlingHttpServletRequest)} method is called.
*
* @param request The {@link SlingHttpServletRequest} object used to drive
* selection of the servlet.
* @return The servlet whose <code>service</code> method may be called to
* handle the request.
* @throws org.apache.sling.api.SlingException Is thrown if an error occurrs
* while trying to find an appropriate servlet to handle the
* request or if no servlet could be resolved to handle the
* request.
*/
Servlet resolveServlet(SlingHttpServletRequest request);
}
| apache-2.0 |
joewalnes/idea-community | java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java | 16061 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Class LineBreakpoint
* @author Jeka
*/
package com.intellij.debugger.ui.breakpoints;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.jsp.JspFile;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.util.Processor;
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.xdebugger.XDebuggerUtil;
import com.intellij.xdebugger.ui.DebuggerIcons;
import com.sun.jdi.*;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.request.BreakpointRequest;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class LineBreakpoint extends BreakpointWithHighlighter {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.LineBreakpoint");
// icons
public static Icon ICON = DebuggerIcons.ENABLED_BREAKPOINT_ICON;
public static final Icon MUTED_ICON = DebuggerIcons.MUTED_BREAKPOINT_ICON;
public static final Icon DISABLED_ICON = DebuggerIcons.DISABLED_BREAKPOINT_ICON;
public static final Icon MUTED_DISABLED_ICON = DebuggerIcons.MUTED_DISABLED_BREAKPOINT_ICON;
private static final Icon ourVerifiedWarningsIcon = IconLoader.getIcon("/debugger/db_verified_warning_breakpoint.png");
private static final Icon ourMutedVerifiedWarningsIcon = IconLoader.getIcon("/debugger/db_muted_verified_warning_breakpoint.png");
private String myMethodName;
public static final @NonNls Key<LineBreakpoint> CATEGORY = BreakpointCategory.lookup("line_breakpoints");
protected LineBreakpoint(Project project) {
super(project);
}
protected LineBreakpoint(Project project, RangeHighlighter highlighter) {
super(project, highlighter);
}
protected Icon getDisabledIcon(boolean isMuted) {
final Breakpoint master = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().findMasterBreakpoint(this);
if (isMuted) {
return master == null? MUTED_DISABLED_ICON : DebuggerIcons.MUTED_DISABLED_DEPENDENT_BREAKPOINT_ICON;
}
else {
return master == null? DISABLED_ICON : DebuggerIcons.DISABLED_DEPENDENT_BREAKPOINT_ICON;
}
}
protected Icon getSetIcon(boolean isMuted) {
return isMuted? MUTED_ICON : ICON;
}
protected Icon getInvalidIcon(boolean isMuted) {
return isMuted? DebuggerIcons.MUTED_INVALID_BREAKPOINT_ICON : DebuggerIcons.INVALID_BREAKPOINT_ICON;
}
protected Icon getVerifiedIcon(boolean isMuted) {
return isMuted? DebuggerIcons.MUTED_VERIFIED_BREAKPOINT_ICON : DebuggerIcons.VERIFIED_BREAKPOINT_ICON;
}
protected Icon getVerifiedWarningsIcon(boolean isMuted) {
return isMuted? ourMutedVerifiedWarningsIcon : ourVerifiedWarningsIcon;
}
public Key<LineBreakpoint> getCategory() {
return CATEGORY;
}
protected void reload(PsiFile file) {
super.reload(file);
myMethodName = findMethodName(file, getHighlighter().getStartOffset());
}
protected void createOrWaitPrepare(DebugProcessImpl debugProcess, String classToBeLoaded) {
if (isInScopeOf(debugProcess, classToBeLoaded)) {
super.createOrWaitPrepare(debugProcess, classToBeLoaded);
}
}
protected void createRequestForPreparedClass(final DebugProcessImpl debugProcess, final ReferenceType classType) {
if (!isInScopeOf(debugProcess, classType.name())) {
return;
}
try {
List<Location> locs = debugProcess.getPositionManager().locationsOfLine(classType, getSourcePosition());
if (locs.size() > 0) {
for (final Location location : locs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found location for reference type " + classType.name() + " at line " + getLineIndex() + "; isObsolete: " + (debugProcess.getVirtualMachineProxy().versionHigher("1.4") && location.method().isObsolete()));
}
BreakpointRequest request = debugProcess.getRequestsManager().createBreakpointRequest(LineBreakpoint.this, location);
debugProcess.getRequestsManager().enableRequest(request);
if (LOG.isDebugEnabled()) {
LOG.debug("Created breakpoint request for reference type " + classType.name() + " at line " + getLineIndex());
}
}
}
else {
// there's no executable code in this class
debugProcess.getRequestsManager().setInvalid(LineBreakpoint.this, DebuggerBundle.message(
"error.invalid.breakpoint.no.executable.code", (getLineIndex() + 1), classType.name())
);
if (LOG.isDebugEnabled()) {
LOG.debug("No locations of type " + classType.name() + " found at line " + getLineIndex());
}
}
}
catch (ClassNotPreparedException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("ClassNotPreparedException: " + ex.getMessage());
}
// there's a chance to add a breakpoint when the class is prepared
}
catch (ObjectCollectedException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("ObjectCollectedException: " + ex.getMessage());
}
// there's a chance to add a breakpoint when the class is prepared
}
catch (InvalidLineNumberException ex) {
if (LOG.isDebugEnabled()) {
LOG.debug("InvalidLineNumberException: " + ex.getMessage());
}
debugProcess.getRequestsManager().setInvalid(LineBreakpoint.this, DebuggerBundle.message("error.invalid.breakpoint.bad.line.number"));
}
catch (InternalException ex) {
LOG.info(ex);
}
catch(Exception ex) {
LOG.info(ex);
}
updateUI();
}
private boolean isInScopeOf(DebugProcessImpl debugProcess, String className) {
final SourcePosition position = getSourcePosition();
if (position != null) {
final VirtualFile breakpointFile = position.getFile().getVirtualFile();
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
if (breakpointFile != null && fileIndex.isInSourceContent(breakpointFile)) {
// apply filtering to breakpoints from content sources only, not for sources attached to libraries
final Collection<VirtualFile> candidates = findClassCandidatesInSourceContent(className, debugProcess.getSearchScope(), fileIndex);
if (candidates == null) {
return true;
}
for (VirtualFile classFile : candidates) {
if (breakpointFile.equals(classFile)) {
return true;
}
}
return false;
}
}
return true;
}
@Nullable
private Collection<VirtualFile> findClassCandidatesInSourceContent(final String className, final GlobalSearchScope scope, final ProjectFileIndex fileIndex) {
final int dollarIndex = className.indexOf("$");
final String topLevelClassName = dollarIndex >= 0? className.substring(0, dollarIndex) : className;
return ApplicationManager.getApplication().runReadAction(new Computable<Collection<VirtualFile>>() {
@Nullable
public Collection<VirtualFile> compute() {
final PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(topLevelClassName, scope);
if (classes.length == 0) {
return null;
}
final List<VirtualFile> list = new ArrayList<VirtualFile>(classes.length);
for (PsiClass aClass : classes) {
final PsiFile psiFile = aClass.getContainingFile();
if (psiFile != null) {
final VirtualFile vFile = psiFile.getVirtualFile();
if (vFile != null && fileIndex.isInSourceContent(vFile)) {
list.add(vFile);
}
}
}
return list;
}
});
}
public boolean evaluateCondition(EvaluationContextImpl context, LocatableEvent event) throws EvaluateException {
if(CLASS_FILTERS_ENABLED){
Value value = context.getThisObject();
ObjectReference thisObject = (ObjectReference)value;
if(thisObject == null) {
return false;
}
String name = DebuggerUtilsEx.getQualifiedClassName(thisObject.referenceType().name(), getProject());
if(name == null) {
return false;
}
ClassFilter [] filters = getClassFilters();
boolean matches = false;
for (ClassFilter classFilter : filters) {
if (classFilter.isEnabled() && classFilter.matches(name)) {
matches = true;
break;
}
}
if(!matches) {
return false;
}
ClassFilter [] ifilters = getClassExclusionFilters();
for (ClassFilter classFilter : ifilters) {
if (classFilter.isEnabled() && classFilter.matches(name)) {
return false;
}
}
}
return super.evaluateCondition(context, event);
}
public String toString() {
return getDescription();
}
public String getDisplayName() {
final int lineNumber = (getHighlighter().getDocument().getLineNumber(getHighlighter().getStartOffset()) + 1);
if(isValid()) {
final String className = getClassName();
final boolean hasClassInfo = className != null && className.length() > 0;
final boolean hasMethodInfo = myMethodName != null && myMethodName.length() > 0;
if (hasClassInfo || hasMethodInfo) {
final StringBuilder info = StringBuilderSpinAllocator.alloc();
try {
String packageName = null;
if (hasClassInfo) {
final int dotIndex = className.lastIndexOf(".");
if (dotIndex >= 0) {
info.append(className.substring(dotIndex + 1));
packageName = className.substring(0, dotIndex);
}
else {
info.append(className);
}
}
if(hasMethodInfo) {
if (hasClassInfo) {
info.append(".");
}
info.append(myMethodName);
}
if (packageName != null) {
info.append(" (").append(packageName).append(")");
}
return DebuggerBundle.message("line.breakpoint.display.name.with.class.or.method", lineNumber, info.toString());
}
finally {
StringBuilderSpinAllocator.dispose(info);
}
}
return DebuggerBundle.message("line.breakpoint.display.name", lineNumber);
}
return DebuggerBundle.message("status.breakpoint.invalid");
}
private static @Nullable String findMethodName(final PsiFile file, final int offset) {
if (file instanceof JspFile) {
return null;
}
if (file instanceof PsiJavaFile) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
public String compute() {
final PsiMethod method = DebuggerUtilsEx.findPsiMethod(file, offset);
return method != null? method.getName() + "()" : null;
}
});
}
return null;
}
public String getEventMessage(LocatableEvent event) {
final Location location = event.location();
try {
return DebuggerBundle.message(
"status.line.breakpoint.reached",
location.declaringType().name() + "." + location.method().name(),
location.sourceName(),
getLineIndex() + 1
);
}
catch (AbsentInformationException e) {
final String sourceName = getSourcePosition().getFile().getName();
return DebuggerBundle.message(
"status.line.breakpoint.reached",
location.declaringType().name() + "." + location.method().name(),
sourceName,
getLineIndex() + 1
);
}
}
public PsiElement getEvaluationElement() {
return PositionUtil.getContextElement(getSourcePosition());
}
protected static LineBreakpoint create(Project project, Document document, int lineIndex) {
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) return null;
LineBreakpoint breakpoint = new LineBreakpoint(project, createHighlighter(project, document, lineIndex));
return (LineBreakpoint)breakpoint.init();
}
public boolean canMoveTo(SourcePosition position) {
if (!super.canMoveTo(position)) {
return false;
}
final Document document = PsiDocumentManager.getInstance(getProject()).getDocument(position.getFile());
return canAddLineBreakpoint(myProject, document, position.getLine());
}
public static boolean canAddLineBreakpoint(Project project, final Document document, final int lineIndex) {
if (lineIndex < 0 || lineIndex >= document.getLineCount()) {
return false;
}
final BreakpointManager breakpointManager = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager();
final LineBreakpoint breakpointAtLine = breakpointManager.findBreakpoint( document, document.getLineStartOffset(lineIndex), CATEGORY);
if (breakpointAtLine != null) {
// there already exists a line breakpoint at this line
return false;
}
PsiDocumentManager.getInstance(project).commitDocument(document);
final boolean[] canAdd = new boolean[]{false};
XDebuggerUtil.getInstance().iterateLine(project, document, lineIndex, new Processor<PsiElement>() {
public boolean process(PsiElement element) {
if ((element instanceof PsiWhiteSpace) || (PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null)) {
return true;
}
PsiElement child = element;
while(element != null) {
final int offset = element.getTextOffset();
if (offset >= 0) {
if (document.getLineNumber(offset) != lineIndex) {
break;
}
}
child = element;
element = element.getParent();
}
if(child instanceof PsiMethod && child.getTextRange().getEndOffset() >= document.getLineEndOffset(lineIndex)) {
PsiCodeBlock body = ((PsiMethod)child).getBody();
if(body == null) {
canAdd[0] = false;
}
else {
PsiStatement[] statements = body.getStatements();
canAdd[0] = statements.length > 0 && document.getLineNumber(statements[0].getTextOffset()) == lineIndex;
}
}
else {
canAdd[0] = true;
}
return false;
}
});
return canAdd[0];
}
public @Nullable String getMethodName() {
return myMethodName;
}
}
| apache-2.0 |
joewalnes/idea-community | platform/util/src/com/intellij/openapi/util/Pair.java | 1781 | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util;
import com.intellij.util.Function;
import org.jetbrains.annotations.Nullable;
public class Pair<A, B> {
public final A first;
public final B second;
public Pair(A first, B second) {
this.first = first;
this.second = second;
}
public final A getFirst() {
return first;
}
public final B getSecond() {
return second;
}
public static <A, B> Pair<A, B> create(A first, B second) {
return new Pair<A,B>(first, second);
}
@SuppressWarnings({"UnusedDeclaration"})
public static <A, B> Function<A, Pair<A, B>> createFunction(@Nullable final B value) {
return new Function<A, Pair<A, B>>() {
public Pair<A, B> fun(A a) {
return create(a, value);
}
};
}
public final boolean equals(Object o) {
return o instanceof Pair && Comparing.equal(first, ((Pair)o).first) && Comparing.equal(second, ((Pair)o).second);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "<" + first + "," + second + ">";
}
}
| apache-2.0 |
lorislab/tower | tower-store/src/main/java/org/lorislab/tower/store/ejb/BuildService.java | 5349 | /*
* Copyright 2014 lorislab.org.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lorislab.tower.store.ejb;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Fetch;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.lorislab.tower.store.criteria.BuildCriteria;
import org.lorislab.tower.store.model.Application;
import org.lorislab.tower.store.model.Build;
import org.lorislab.tower.store.model.Build_;
import org.lorislab.tower.store.model.Application_;
import org.lorislab.jel.ejb.services.AbstractEntityServiceBean;
/**
* The build service.
*
* @author Andrej Petras
*/
@Stateless
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class BuildService extends AbstractStoreEntityServiceBean<Build> {
/**
* Saves the store build.
*
* @param data the build.
* @return the saved build.
*/
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public Build saveBuild(Build data) {
return this.save(data);
}
/**
* Gets the build by GUID.
*
* @param guid the GUID.
* @return the corresponding build.
*/
public Build getBuild(String guid) {
BuildCriteria criteria = new BuildCriteria();
criteria.setGuid(guid);
return getBuild(criteria);
}
/**
* Gets the build by criteria.
*
* @param criteria the criteria.
* @return the corresponding build.
*/
public Build getBuild(BuildCriteria criteria) {
Build result = null;
List<Build> tmp = getBuilds(criteria);
if (tmp != null && !tmp.isEmpty()) {
result = tmp.get(0);
}
return result;
}
/**
* Gets all builds.
*
* @return the list of all builds.
*/
public List<Build> getBuilds() {
return getBuilds(new BuildCriteria());
}
/**
* Gets the builds by criteria.
*
* @param criteria the criteria.
* @return the corresponding list of criteria.
*/
public List<Build> getBuilds(BuildCriteria criteria) {
List<Build> result = new ArrayList<>();
CriteriaBuilder cb = getBaseEAO().getCriteriaBuilder();
CriteriaQuery<Build> cq = getBaseEAO().createCriteriaQuery();
Root<Build> root = cq.from(Build.class);
List<Predicate> predicates = new ArrayList<>();
if (criteria.isFetchParameters()) {
root.fetch(Build_.parameters, JoinType.LEFT);
}
if (criteria.isFetchApplication()) {
Fetch<Build, Application> af = root.fetch(Build_.application, JoinType.LEFT);
if (criteria.isFetchApplicationProject()) {
af.fetch(Application_.project, JoinType.LEFT);
}
}
if (criteria.getMavenVersion() != null) {
predicates.add(cb.equal(root.get(Build_.mavenVersion), criteria.getMavenVersion()));
}
if (criteria.getApplication() != null) {
predicates.add(cb.equal(root.get(Build_.application).get(Application_.guid), criteria.getApplication()));
}
if (criteria.getGuid() != null) {
predicates.add(cb.equal(root.get(Build_.guid), criteria.getGuid()));
}
if (criteria.getAgent() != null) {
predicates.add(cb.equal(root.get(Build_.agent), criteria.getAgent()));
}
if (criteria.getDate() != null) {
predicates.add(cb.equal(root.get(Build_.date), criteria.getDate()));
}
if (!predicates.isEmpty()) {
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
}
List<Order> orders = new ArrayList<>();
if (criteria.getOrderByDate() != null) {
if (criteria.getOrderByDate()) {
orders.add( cb.asc(root.get(Build_.date)));
} else {
orders.add( cb.desc(root.get(Build_.date)));
}
}
if (!orders.isEmpty()) {
cq.orderBy(orders);
}
try {
TypedQuery<Build> typeQuery = getBaseEAO().createTypedQuery(cq);
result = typeQuery.getResultList();
} catch (NoResultException ex) {
// do nothing
}
return result;
}
}
| apache-2.0 |
ChiangC/FMTech | GooglePlay6.0.5/app/src/main/java/android/support/v7/internal/app/ToolbarActionBar.java | 13672 | package android.support.v7.internal.app;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.Resources.Theme;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnMenuVisibilityListener;
import android.support.v7.appcompat.R.attr;
import android.support.v7.appcompat.R.layout;
import android.support.v7.appcompat.R.style;
import android.support.v7.internal.view.WindowCallbackWrapper;
import android.support.v7.internal.view.menu.ListMenuPresenter;
import android.support.v7.internal.view.menu.MenuBuilder;
import android.support.v7.internal.view.menu.MenuBuilder.Callback;
import android.support.v7.internal.view.menu.MenuPresenter.Callback;
import android.support.v7.internal.widget.DecorToolbar;
import android.support.v7.internal.widget.ToolbarWidgetWrapper;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.Toolbar.OnMenuItemClickListener;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window.Callback;
import android.widget.ListAdapter;
import java.util.ArrayList;
public final class ToolbarActionBar
extends ActionBar
{
DecorToolbar mDecorToolbar;
private boolean mLastMenuVisibility;
ListMenuPresenter mListMenuPresenter;
private boolean mMenuCallbackSet;
private final Toolbar.OnMenuItemClickListener mMenuClicker = new Toolbar.OnMenuItemClickListener()
{
public final boolean onMenuItemClick(MenuItem paramAnonymousMenuItem)
{
return ToolbarActionBar.this.mWindowCallback.onMenuItemSelected(0, paramAnonymousMenuItem);
}
};
private final Runnable mMenuInvalidator = new Runnable()
{
public final void run()
{
ToolbarActionBar localToolbarActionBar = ToolbarActionBar.this;
Menu localMenu = localToolbarActionBar.getMenu();
if ((localMenu instanceof MenuBuilder)) {}
for (localMenuBuilder = (MenuBuilder)localMenu;; localMenuBuilder = null)
{
if (localMenuBuilder != null) {
localMenuBuilder.stopDispatchingItemsChanged();
}
try
{
localMenu.clear();
if ((!localToolbarActionBar.mWindowCallback.onCreatePanelMenu(0, localMenu)) || (!localToolbarActionBar.mWindowCallback.onPreparePanel(0, null, localMenu))) {
localMenu.clear();
}
return;
}
finally
{
if (localMenuBuilder == null) {
break;
}
localMenuBuilder.startDispatchingItemsChanged();
}
}
}
};
private ArrayList<ActionBar.OnMenuVisibilityListener> mMenuVisibilityListeners = new ArrayList();
boolean mToolbarMenuPrepared;
public Window.Callback mWindowCallback;
public ToolbarActionBar(Toolbar paramToolbar, CharSequence paramCharSequence, Window.Callback paramCallback)
{
this.mDecorToolbar = new ToolbarWidgetWrapper(paramToolbar, false);
this.mWindowCallback = new ToolbarCallbackWrapper(paramCallback);
this.mDecorToolbar.setWindowCallback(this.mWindowCallback);
paramToolbar.setOnMenuItemClickListener(this.mMenuClicker);
this.mDecorToolbar.setWindowTitle(paramCharSequence);
}
public final void addOnMenuVisibilityListener(ActionBar.OnMenuVisibilityListener paramOnMenuVisibilityListener)
{
this.mMenuVisibilityListeners.add(paramOnMenuVisibilityListener);
}
public final boolean collapseActionView()
{
if (this.mDecorToolbar.hasExpandedActionView())
{
this.mDecorToolbar.collapseActionView();
return true;
}
return false;
}
public final void dispatchMenuVisibilityChanged(boolean paramBoolean)
{
if (paramBoolean == this.mLastMenuVisibility) {}
for (;;)
{
return;
this.mLastMenuVisibility = paramBoolean;
int i = this.mMenuVisibilityListeners.size();
for (int j = 0; j < i; j++) {
((ActionBar.OnMenuVisibilityListener)this.mMenuVisibilityListeners.get(j)).onMenuVisibilityChanged(paramBoolean);
}
}
}
public final int getDisplayOptions()
{
return this.mDecorToolbar.getDisplayOptions();
}
public final int getHeight()
{
return this.mDecorToolbar.getHeight();
}
final Menu getMenu()
{
if (!this.mMenuCallbackSet)
{
this.mDecorToolbar.setMenuCallbacks(new ActionMenuPresenterCallback((byte)0), new MenuBuilderCallback((byte)0));
this.mMenuCallbackSet = true;
}
return this.mDecorToolbar.getMenu();
}
public final Context getThemedContext()
{
return this.mDecorToolbar.getContext();
}
public final void hide()
{
this.mDecorToolbar.setVisibility(8);
}
public final boolean invalidateOptionsMenu()
{
this.mDecorToolbar.getViewGroup().removeCallbacks(this.mMenuInvalidator);
ViewCompat.postOnAnimation(this.mDecorToolbar.getViewGroup(), this.mMenuInvalidator);
return true;
}
public final void onConfigurationChanged(Configuration paramConfiguration)
{
super.onConfigurationChanged(paramConfiguration);
}
public final boolean onKeyShortcut(int paramInt, KeyEvent paramKeyEvent)
{
Menu localMenu = getMenu();
int i;
if (localMenu != null)
{
if (paramKeyEvent == null) {
break label54;
}
i = paramKeyEvent.getDeviceId();
if (KeyCharacterMap.load(i).getKeyboardType() == 1) {
break label60;
}
}
label54:
label60:
for (boolean bool = true;; bool = false)
{
localMenu.setQwertyMode(bool);
localMenu.performShortcut(paramInt, paramKeyEvent, 0);
return true;
i = -1;
break;
}
}
public final void setBackgroundDrawable(Drawable paramDrawable)
{
this.mDecorToolbar.setBackgroundDrawable(paramDrawable);
}
public final void setDefaultDisplayHomeAsUpEnabled(boolean paramBoolean) {}
public final void setDisplayHomeAsUpEnabled(boolean paramBoolean)
{
if (paramBoolean) {}
for (int i = 4;; i = 0)
{
setDisplayOptions(i, 4);
return;
}
}
public final void setDisplayOptions(int paramInt1, int paramInt2)
{
int i = this.mDecorToolbar.getDisplayOptions();
this.mDecorToolbar.setDisplayOptions(paramInt1 & paramInt2 | i & (paramInt2 ^ 0xFFFFFFFF));
}
public final void setHomeActionContentDescription(int paramInt)
{
this.mDecorToolbar.setNavigationContentDescription(paramInt);
}
public final void setHomeAsUpIndicator(int paramInt)
{
this.mDecorToolbar.setNavigationIcon(paramInt);
}
public final void setHomeAsUpIndicator(Drawable paramDrawable)
{
this.mDecorToolbar.setNavigationIcon(paramDrawable);
}
public final void setLogo(Drawable paramDrawable)
{
this.mDecorToolbar.setLogo(paramDrawable);
}
public final void setShowHideAnimationEnabled(boolean paramBoolean) {}
public final void setSubtitle(CharSequence paramCharSequence)
{
this.mDecorToolbar.setSubtitle(paramCharSequence);
}
public final void setTitle(CharSequence paramCharSequence)
{
this.mDecorToolbar.setTitle(paramCharSequence);
}
public final void setWindowTitle(CharSequence paramCharSequence)
{
this.mDecorToolbar.setWindowTitle(paramCharSequence);
}
public final void show()
{
this.mDecorToolbar.setVisibility(0);
}
private final class ActionMenuPresenterCallback
implements MenuPresenter.Callback
{
private boolean mClosingActionMenu;
private ActionMenuPresenterCallback() {}
public final void onCloseMenu(MenuBuilder paramMenuBuilder, boolean paramBoolean)
{
if (this.mClosingActionMenu) {
return;
}
this.mClosingActionMenu = true;
ToolbarActionBar.this.mDecorToolbar.dismissPopupMenus();
if (ToolbarActionBar.this.mWindowCallback != null) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, paramMenuBuilder);
}
this.mClosingActionMenu = false;
}
public final boolean onOpenSubMenu(MenuBuilder paramMenuBuilder)
{
if (ToolbarActionBar.this.mWindowCallback != null)
{
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, paramMenuBuilder);
return true;
}
return false;
}
}
private final class MenuBuilderCallback
implements MenuBuilder.Callback
{
private MenuBuilderCallback() {}
public final boolean onMenuItemSelected(MenuBuilder paramMenuBuilder, MenuItem paramMenuItem)
{
return false;
}
public final void onMenuModeChange(MenuBuilder paramMenuBuilder)
{
if (ToolbarActionBar.this.mWindowCallback != null)
{
if (!ToolbarActionBar.this.mDecorToolbar.isOverflowMenuShowing()) {
break label41;
}
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, paramMenuBuilder);
}
label41:
while (!ToolbarActionBar.this.mWindowCallback.onPreparePanel(0, null, paramMenuBuilder)) {
return;
}
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, paramMenuBuilder);
}
}
private final class PanelMenuPresenterCallback
implements MenuPresenter.Callback
{
private PanelMenuPresenterCallback() {}
public final void onCloseMenu(MenuBuilder paramMenuBuilder, boolean paramBoolean)
{
if (ToolbarActionBar.this.mWindowCallback != null) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(0, paramMenuBuilder);
}
}
public final boolean onOpenSubMenu(MenuBuilder paramMenuBuilder)
{
if ((paramMenuBuilder == null) && (ToolbarActionBar.this.mWindowCallback != null)) {
ToolbarActionBar.this.mWindowCallback.onMenuOpened(0, paramMenuBuilder);
}
return true;
}
}
private final class ToolbarCallbackWrapper
extends WindowCallbackWrapper
{
public ToolbarCallbackWrapper(Window.Callback paramCallback)
{
super();
}
public final View onCreatePanelView(int paramInt)
{
switch (paramInt)
{
}
Menu localMenu;
do
{
return super.onCreatePanelView(paramInt);
localMenu = ToolbarActionBar.this.mDecorToolbar.getMenu();
} while ((!onPreparePanel(paramInt, null, localMenu)) || (!onMenuOpened(paramInt, localMenu)));
ToolbarActionBar localToolbarActionBar = ToolbarActionBar.this;
MenuBuilder localMenuBuilder;
Context localContext;
Resources.Theme localTheme;
if ((localToolbarActionBar.mListMenuPresenter == null) && ((localMenu instanceof MenuBuilder)))
{
localMenuBuilder = (MenuBuilder)localMenu;
localContext = localToolbarActionBar.mDecorToolbar.getContext();
TypedValue localTypedValue = new TypedValue();
localTheme = localContext.getResources().newTheme();
localTheme.setTo(localContext.getTheme());
localTheme.resolveAttribute(R.attr.actionBarPopupTheme, localTypedValue, true);
if (localTypedValue.resourceId != 0) {
localTheme.applyStyle(localTypedValue.resourceId, true);
}
localTheme.resolveAttribute(R.attr.panelMenuListTheme, localTypedValue, true);
if (localTypedValue.resourceId == 0) {
break label261;
}
localTheme.applyStyle(localTypedValue.resourceId, true);
}
for (;;)
{
ContextThemeWrapper localContextThemeWrapper = new ContextThemeWrapper(localContext, 0);
localContextThemeWrapper.getTheme().setTo(localTheme);
localToolbarActionBar.mListMenuPresenter = new ListMenuPresenter(localContextThemeWrapper, R.layout.abc_list_menu_item_layout);
localToolbarActionBar.mListMenuPresenter.mCallback = new ToolbarActionBar.PanelMenuPresenterCallback(localToolbarActionBar, (byte)0);
localMenuBuilder.addMenuPresenter(localToolbarActionBar.mListMenuPresenter);
if ((localMenu != null) && (localToolbarActionBar.mListMenuPresenter != null)) {
break;
}
return null;
label261:
localTheme.applyStyle(R.style.Theme_AppCompat_CompactMenu, true);
}
if (localToolbarActionBar.mListMenuPresenter.getAdapter().getCount() > 0) {
return (View)localToolbarActionBar.mListMenuPresenter.getMenuView(localToolbarActionBar.mDecorToolbar.getViewGroup());
}
return null;
}
public final boolean onPreparePanel(int paramInt, View paramView, Menu paramMenu)
{
boolean bool = super.onPreparePanel(paramInt, paramView, paramMenu);
if ((bool) && (!ToolbarActionBar.this.mToolbarMenuPrepared))
{
ToolbarActionBar.this.mDecorToolbar.setMenuPrepared();
ToolbarActionBar.this.mToolbarMenuPrepared = true;
}
return bool;
}
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: android.support.v7.internal.app.ToolbarActionBar
* JD-Core Version: 0.7.0.1
*/ | apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_1034.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_1034 {
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_2255.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_2255 {
}
| apache-2.0 |
gravitee-io/gravitee-management-rest-api | gravitee-rest-api-management/gravitee-rest-api-management-rest/src/main/java/io/gravitee/rest/api/management/rest/resource/param/AbstractParam.java | 1816 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.gravitee.rest.api.management.rest.resource.param;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
* @author David BRASSELY (brasseld at gmail.com)
*/
public abstract class AbstractParam<V> {
private final V value;
private final String originalParam;
public AbstractParam(String param) throws WebApplicationException {
this.originalParam = param;
try {
this.value = parse(param);
} catch (Throwable e) {
throw new WebApplicationException(onError(param, e));
}
}
public V getValue() {
return value;
}
public String getOriginalParam() {
return originalParam;
}
@Override
public String toString() {
return value.toString();
}
protected abstract V parse(String param) throws Throwable;
protected Response onError(String param, Throwable e) {
return Response.status(Response.Status.BAD_REQUEST).entity(getErrorMessage(param, e)).build();
}
protected String getErrorMessage(String param, Throwable e) {
return "Invalid parameter: " + param + " (" + e.getMessage() + ")";
}
}
| apache-2.0 |
sisqbates/vertx-cassandra | vertx-cassandra-client/src/main/java/io/vertx/ext/cassandra/ExecutionOptions.java | 4561 | package io.vertx.ext.cassandra;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
@DataObject
public class ExecutionOptions {
public static final int DEFAULT_FETCH_SIZE = -1;
private boolean tracing = false;
private ConsistencyLevel consistencyLevel;
private Long timestamp;
private int fetchSize = DEFAULT_FETCH_SIZE;
private boolean idempotent = false;
private RetryPolicy retryPolicy = RetryPolicy.DEFAULT;
private ConsistencyLevel serialConsistencyLevel;
private String pagingState;
public ExecutionOptions() {
}
public ExecutionOptions(ExecutionOptions other) {
this.tracing = other.tracing;
this.consistencyLevel = other.consistencyLevel;
this.timestamp = other.timestamp;
this.fetchSize = other.fetchSize;
this.idempotent = other.idempotent;
this.retryPolicy = other.retryPolicy;
this.serialConsistencyLevel = other.serialConsistencyLevel;
this.pagingState = other.pagingState;
}
public ExecutionOptions(JsonObject json) {
this.tracing = json.getBoolean("tracing", false);
this.consistencyLevel = this.getEnum(json.getString("consistencyLevel"), ConsistencyLevel.class);
this.timestamp = json.getLong("timestamp", null);
this.fetchSize = json.getInteger("fetchSize", -1);
this.idempotent = json.getBoolean("idempotent", false);
this.retryPolicy = this.getEnum(json.getString("retryPolicy"), RetryPolicy.class);
this.serialConsistencyLevel = this.getEnum(json.getString("serialConsistencyLevel"), ConsistencyLevel.class);
this.pagingState = json.getString("pagingState");
}
public JsonObject toJson() {
JsonObject result = new JsonObject();
result.put("tracing", this.tracing);
if (this.consistencyLevel != null) {
result.put("consistencyLevel", this.consistencyLevel.name());
}
if (this.timestamp != null) {
result.put("timestamp", this.timestamp);
}
if (this.fetchSize != DEFAULT_FETCH_SIZE) {
result.put("fetchSize", fetchSize);
}
result.put("idempotent", idempotent);
if (this.retryPolicy != null) {
result.put("retryPolicy", this.retryPolicy.name());
}
if (this.serialConsistencyLevel != null) {
result.put("serialConsistencyLevel", this.serialConsistencyLevel.name());
}
if (this.pagingState != null) {
result.put("pagingState", this.pagingState);
}
return result;
}
public boolean isTracing() {
return tracing;
}
public ExecutionOptions setTracing(boolean tracing) {
this.tracing = tracing;
return this;
}
public ConsistencyLevel getConsistencyLevel() {
return consistencyLevel;
}
public ExecutionOptions setConsistencyLevel(ConsistencyLevel consistencyLevel) {
this.consistencyLevel = consistencyLevel;
return this;
}
public Long getTimestamp() {
return timestamp;
}
public ExecutionOptions setTimestamp(Long timestamp) {
this.timestamp = timestamp;
return this;
}
public int getFetchSize() {
return fetchSize;
}
public ExecutionOptions setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
return this;
}
public boolean isIdempotent() {
return idempotent;
}
public ExecutionOptions setIdempotent(boolean idempotent) {
this.idempotent = idempotent;
return this;
}
public RetryPolicy getRetryPolicy() {
return retryPolicy;
}
public ExecutionOptions setRetryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
public ConsistencyLevel getSerialConsistencyLevel() {
return serialConsistencyLevel;
}
public ExecutionOptions setSerialConsistencyLevel(ConsistencyLevel serialConsistencyLevel) {
this.serialConsistencyLevel = serialConsistencyLevel;
return this;
}
public String getPagingState() {
return pagingState;
}
public ExecutionOptions setPagingState(String pagingState) {
this.pagingState = pagingState;
return this;
}
private <T extends Enum<T>> T getEnum(String name, Class<T> enumClass) {
if (name == null) {
return null;
} else {
return Enum.valueOf(enumClass, name);
}
}
}
| apache-2.0 |
MariaBaikova/java-test-training-baikova | addressbook-selenium-tests/src/com/example/tests/RandomDataGenerator.java | 549 | package com.example.tests;
import java.util.Random;
public class RandomDataGenerator {
public static String generateRandomString(){
Random rnd = new Random();
if (rnd.nextInt(3) ==0) {
return "";
}
else {
return "test"+rnd.nextInt();
}
}
public static String generateNotEmptyRandomString(){
Random rnd = new Random();
return "test"+rnd.nextInt();
}
public static String generateRandomNumber(){
Random rnd = new Random();
return rnd.nextInt()+"";
}
}
| apache-2.0 |
cordisvictor/easyml-lib | easyml/test/net/sourceforge/easyml/MultiThreadEasyMLTest.java | 7699 | /*
* Copyright 2012 Victor Cordis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Please contact the author ( cordis.victor@gmail.com ) if you need additional
* information or have any questions.
*/
package net.sourceforge.easyml;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import net.sourceforge.easyml.testmodel.FacultyDTO;
import net.sourceforge.easyml.testmodel.StudentPersonDTO;
import static org.junit.Assert.*;
import org.junit.Test;
/**
*
* @author victor
*/
public class MultiThreadEasyMLTest {
private EasyML easyml;
@Test
public void testMultiThreadsCtorFieldCaching() throws Exception {
easyml = new EasyML();
final WorkerThread<FacultyDTO> t1 = new WorkerThread(new FacultyDTO(144, "Faculty Name", new StudentPersonDTO[]{new StudentPersonDTO()}));
final WorkerThread<StudentPersonDTO> t2 = new WorkerThread(new StudentPersonDTO(1, "fn1", "ln1", true, null));
final WorkerThread<StudentPersonDTO> t3 = new WorkerThread(new StudentPersonDTO(2, "fn2", "ln2", false, new FacultyDTO(22, "Faculty")));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
assertEquals(t1.src, t1.dest);
assertEquals(t2.src, t2.dest);
assertEquals(t3.src, t3.dest);
}
@Test
public void testMultiThreadsCtorFieldCachingNewWritersReaders() throws Exception {
easyml = new EasyML();
final WorkerThread<FacultyDTO> t1 = new NewWorkerThread(new FacultyDTO(144, "Faculty Name", new StudentPersonDTO[]{new StudentPersonDTO()}));
final WorkerThread<StudentPersonDTO> t2 = new NewWorkerThread(new StudentPersonDTO(1, "fn1", "ln1", true, null));
final WorkerThread<StudentPersonDTO> t3 = new NewWorkerThread(new StudentPersonDTO(2, "fn2", "ln2", false, new FacultyDTO(22, "Faculty")));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
assertEquals(t1.src, t1.dest);
assertEquals(t2.src, t2.dest);
assertEquals(t3.src, t3.dest);
}
@Test
public void testMultiThreads1() throws Exception {
easyml = new EasyML();
final WorkerThread<List<Integer>> t1 = new WorkerThread(new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)));
final WorkerThread<List<Integer>> t2 = new WorkerThread(new ArrayList(Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1)));
final WorkerThread<List<Integer>> t3 = new WorkerThread(new ArrayList(Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1)));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
List<Integer> result = new ArrayList();
for (int i = 0; i < 8; i++) {
result.add(t1.dest.get(i) + t2.dest.get(i) + t3.dest.get(i));
}
System.out.println("Threads result:" + result);
assertEquals(new ArrayList(Arrays.asList(10, 10, 10, 10, 10, 10, 10, 10)), result);
}
@Test
public void testMultiThreads2() throws Exception {
easyml = new EasyMLBuilder().withDateFormat("dd-MM-yyyy'T'HH:mm:ss:SSS").build();
final WorkerThread<List<Integer>> t1 = new WorkerThread(new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)));
final WorkerThread<List<Integer>> t2 = new WorkerThread(new ArrayList(Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1)));
final WorkerThread<List<Integer>> t3 = new WorkerThread(new ArrayList(Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1)));
final WorkerThread<Date> t4 = new WorkerThread(new Date());
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
List<Integer> result = new ArrayList();
for (int i = 0; i < 8; i++) {
result.add(t1.dest.get(i) + t2.dest.get(i) + t3.dest.get(i));
}
System.out.println("Threads result:" + result);
assertEquals(new ArrayList(Arrays.asList(10, 10, 10, 10, 10, 10, 10, 10)), result);
assertEquals(t4.src, t4.dest);
}
@Test
public void testMultiThreads1new() throws Exception {
easyml = new EasyML();
final WorkerThread<List<Integer>> t1 = new NewWorkerThread(new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)));
final WorkerThread<List<Integer>> t2 = new NewWorkerThread(new ArrayList(Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1)));
final WorkerThread<List<Integer>> t3 = new NewWorkerThread(new ArrayList(Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1)));
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
List<Integer> result = new ArrayList();
for (int i = 0; i < 8; i++) {
result.add(t1.dest.get(i) + t2.dest.get(i) + t3.dest.get(i));
}
System.out.println("Threads result:" + result);
assertEquals(new ArrayList(Arrays.asList(10, 10, 10, 10, 10, 10, 10, 10)), result);
}
@Test
public void testMultiThreads2new() throws Exception {
easyml = new EasyMLBuilder().withDateFormat("dd-MM-yyyy'T'HH:mm:ss:SSS").build();
final WorkerThread<List<Integer>> t1 = new NewWorkerThread(new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)));
final WorkerThread<List<Integer>> t2 = new NewWorkerThread(new ArrayList(Arrays.asList(8, 7, 6, 5, 4, 3, 2, 1)));
final WorkerThread<List<Integer>> t3 = new NewWorkerThread(new ArrayList(Arrays.asList(1, 1, 1, 1, 1, 1, 1, 1)));
final WorkerThread<Date> t4 = new NewWorkerThread(new Date());
t1.start();
t2.start();
t3.start();
t4.start();
t1.join();
t2.join();
t3.join();
t4.join();
List<Integer> result = new ArrayList();
for (int i = 0; i < 8; i++) {
result.add(t1.dest.get(i) + t2.dest.get(i) + t3.dest.get(i));
}
System.out.println("Threads result:" + result);
assertEquals(new ArrayList(Arrays.asList(10, 10, 10, 10, 10, 10, 10, 10)), result);
assertEquals(t4.src, t4.dest);
}
private class WorkerThread<T> extends Thread {
protected final T src;
protected final ByteArrayOutputStream out;
protected T dest;
public WorkerThread(T src) {
this.src = src;
this.out = new ByteArrayOutputStream();
}
@Override
public void run() {
easyml.serialize(src, out);
dest = (T) easyml.deserialize(new ByteArrayInputStream(out.toByteArray()));
}
}
private class NewWorkerThread<T> extends WorkerThread<T> {
public NewWorkerThread(T src) {
super(src);
}
@Override
public void run() {
final XMLWriter w = easyml.newWriter(out);
w.write(src);
w.close();
final XMLReader r = easyml.newReader(new ByteArrayInputStream(out.toByteArray()));
dest = (T) r.read();
r.close();
}
}
}
| apache-2.0 |
SteveBush/thrift-utils | thrift-types/src/main/java/com/bushchang/thrift/types/TimeStampType.java | 407 | package com.bushchang.thrift.types;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by stevebu on 3/2/2015.
*/
public class TimeStampType extends Date{
/**
* Creates a timestamp with current local time
*/
public TimeStampType(long timeStampLong)
{
super(timeStampLong);
}
public TimeStampType()
{
}
}
| apache-2.0 |
wakhub/monodict | app/src/main/java/com/github/wakhub/monodict/dice/IIndexCacheFile.java | 925 | /**
* Copyright (C) 2014 wak
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.wakhub.monodict.dice;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public interface IIndexCacheFile {
FileInputStream getInput() throws FileNotFoundException;
FileOutputStream getOutput() throws FileNotFoundException;
}
| apache-2.0 |
alexeremeev/aeremeev | chapter_003(IO)/src/main/java/ru/job4j/io/filesort/SortFile.java | 497 | package ru.job4j.io.filesort;
import java.io.File;
import java.io.IOException;
/**
* interface SortFile - сортировка файла по длине строк и запись нового.
*/
public interface SortFile {
/**
* Сортирует файл по длине строк и записывает новый.
* @param source исходный файл.
* @param destination файл назначения.
*/
void sort(File source, File destination);
}
| apache-2.0 |
everttigchelaar/camel-svn | components/camel-http4/src/test/java/org/apache/camel/component/http4/HttpCompressionTest.java | 6411 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.http4;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.http4.handler.HeaderValidationHandler;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.localserver.LocalTestServer;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
/**
*
* @version
*/
public class HttpCompressionTest extends BaseHttpTest {
@Test
public void compressedHttpPost() throws Exception {
Exchange exchange = template.request("http4://" + getHostName() + ":" + getPort() + "/", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
exchange.getIn().setHeader(Exchange.CONTENT_ENCODING, "gzip");
exchange.getIn().setBody(getBody());
}
});
assertNotNull(exchange);
Message out = exchange.getOut();
assertNotNull(out);
Map<String, Object> headers = out.getHeaders();
assertEquals(HttpStatus.SC_OK, headers.get(Exchange.HTTP_RESPONSE_CODE));
assertEquals("gzip", headers.get("Content-Encoding"));
assertBody(out.getBody(String.class));
}
@Override
protected BasicHttpProcessor getBasicHttpProcessor() {
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new RequestDecompressingInterceptor());
httpproc.addInterceptor(new ResponseCompressingInterceptor());
return httpproc;
}
@Override
protected void registerHandler(LocalTestServer server) {
Map<String, String> expectedHeaders = new HashMap<String, String>();
expectedHeaders.put("Content-Type", "text/plain");
expectedHeaders.put("Content-Encoding", "gzip");
server.register("/", new HeaderValidationHandler("POST", null, getBody(), getExpectedContent(), expectedHeaders));
}
protected String getBody() {
return "hl=en&q=camel";
}
static class RequestDecompressingInterceptor implements HttpRequestInterceptor {
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
Header contentEncoding = request.getFirstHeader("Content-Encoding");
if (contentEncoding != null
&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request)
.getEntity();
((HttpEntityEnclosingRequest) request)
.setEntity(new GzipDecompressingEntity(entity));
}
}
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isStreaming() {
return false;
}
}
}
static class ResponseCompressingInterceptor implements HttpResponseInterceptor {
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
response.setHeader("Content-Encoding", "gzip");
HttpEntity entity = response.getEntity();
response.setEntity(new GzipCompressingEntity(entity));
}
static class GzipCompressingEntity extends HttpEntityWrapper {
public GzipCompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public Header getContentEncoding() {
return new BasicHeader("Content-Encoding", "gzip");
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
GZIPOutputStream gzip = new GZIPOutputStream(outstream);
gzip.write(EntityUtils.toByteArray(wrappedEntity));
gzip.close();
}
@Override
public long getContentLength() {
return -1;
}
@Override
public boolean isStreaming() {
return false;
}
}
}
} | apache-2.0 |
Linggify/AtticEngine | attic/core/src/main/java/com/github/linggify/attic/render/IBatch.java | 594 | package com.github.linggify.attic.render;
import com.github.linggify.attic.logic.IProperty;
/**
* Batches are groups of geometry batched together to reduce driver overhead when rendering.
* their implementation may be platform-specific.
*
* A Batch recieves its Vertex-attributes at creation.
*
* @author Fredie
*
*/
public interface IBatch {
/**
* Tries to add the given {@link IProperty} to this {@link IBatch} for rendering
* @param property
* @return true if the given Property was accepted
*/
boolean accept(IProperty<RenderData> property);
}
| apache-2.0 |
wendal/alipay-sdk | src/main/java/com/alipay/api/response/ZhimaCustomerEpCertificationQueryResponse.java | 905 | package com.alipay.api.response;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: zhima.customer.ep.certification.query response.
*
* @author auto create
* @since 1.0, 2017-10-27 14:28:48
*/
public class ZhimaCustomerEpCertificationQueryResponse extends AlipayResponse {
private static final long serialVersionUID = 5674329346368713655L;
/**
* 认证不通过的原因
*/
@ApiField("failed_reason")
private String failedReason;
/**
* 认证是否通过,通过为true,不通过为false
*/
@ApiField("passed")
private String passed;
public void setFailedReason(String failedReason) {
this.failedReason = failedReason;
}
public String getFailedReason( ) {
return this.failedReason;
}
public void setPassed(String passed) {
this.passed = passed;
}
public String getPassed( ) {
return this.passed;
}
}
| apache-2.0 |
ilooner/javaflow | src/main/java/org/apache/commons/javaflow/bytecode/transformation/asm/ContinuationMethodAdapter.java | 15463 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.javaflow.bytecode.transformation.asm;
import java.util.List;
import org.apache.commons.javaflow.bytecode.StackRecorder;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.analysis.Analyzer;
import org.objectweb.asm.tree.analysis.BasicValue;
import org.objectweb.asm.tree.analysis.Frame;
public final class ContinuationMethodAdapter extends MethodVisitor implements Opcodes {
private static final String STACK_RECORDER = Type.getInternalName(StackRecorder.class);
private static final String POP_METHOD = "pop";
private static final String PUSH_METHOD = "push";
private static final String[] SUFFIXES = {
"Object", // 0 void
"Int", // 1 boolean
"Int", // 2 char
"Int", // 3 byte
"Int", // 4 short
"Int", // 5 int
"Float", // 6 float
"Long", // 7 long
"Double", // 8 double
"Object", // 9 array
"Object", // 10 object
};
private final ContinuationMethodAnalyzer canalyzer;
private final Analyzer analyzer;
private Label startLabel = new Label();
private final List<Label> labels;
private final List<MethodInsnNode> nodes;
private final int stackRecorderVar;
private final boolean isStatic;
private final String methodDesc;
private int currentIndex = 0;
private Frame currentFrame = null;
public ContinuationMethodAdapter(ContinuationMethodAnalyzer a) {
super(Opcodes.ASM4, a.mv);
this.canalyzer = a;
this.analyzer = a.analyzer;
this.labels = a.labels;
this.nodes = a.nodes;
this.stackRecorderVar = a.stackRecorderVar;
this.isStatic = (a.access & ACC_STATIC) > 0;
this.methodDesc = a.desc;
}
@Override
public void visitCode() {
mv.visitCode();
int fsize = labels.size();
Label[] restoreLabels = new Label[fsize];
for (int i = 0; i < restoreLabels.length; i++) {
restoreLabels[i] = new Label();
}
// verify if restoring
Label l0 = new Label();
// PC: StackRecorder stackRecorder = StackRecorder.get();
mv.visitMethodInsn(INVOKESTATIC, STACK_RECORDER, "get", "()L" + STACK_RECORDER + ";");
mv.visitInsn(DUP);
mv.visitVarInsn(ASTORE, stackRecorderVar);
mv.visitLabel(startLabel);
// PC: if (stackRecorder != null && !stackRecorder.isRestoring) {
mv.visitJumpInsn(IFNULL, l0);
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitFieldInsn(GETFIELD, STACK_RECORDER, "isRestoring", "Z");
mv.visitJumpInsn(IFEQ, l0);
mv.visitVarInsn(ALOAD, stackRecorderVar);
// PC: stackRecorder.popInt();
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, POP_METHOD + "Int", "()I");
mv.visitTableSwitchInsn(0, fsize - 1, l0, restoreLabels);
// switch cases
for (int i = 0; i < fsize; i++) {
Label frameLabel = labels.get(i);
mv.visitLabel(restoreLabels[i]);
MethodInsnNode mnode = nodes.get(i);
Frame frame = analyzer.getFrames()[canalyzer.getIndex(mnode)];
// for each local variable store the value in locals popping it from the stack!
// locals
int lsize = frame.getLocals();
for (int j = lsize - 1; j >= 0; j--) {
BasicValue value = (BasicValue) frame.getLocal(j);
if (isNull(value)) {
mv.visitInsn(ACONST_NULL);
mv.visitVarInsn(ASTORE, j);
} else if (value == BasicValue.UNINITIALIZED_VALUE) {
// TODO ??
} else if (value == BasicValue.RETURNADDRESS_VALUE) {
// TODO ??
} else {
mv.visitVarInsn(ALOAD, stackRecorderVar);
Type type = value.getType();
if (value.isReference()) {
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, POP_METHOD + "Object", "()Ljava/lang/Object;");
Type t = value.getType();
String desc = t.getDescriptor();
if (desc.charAt(0) == '[') {
mv.visitTypeInsn(CHECKCAST, desc);
} else {
mv.visitTypeInsn(CHECKCAST, t.getInternalName());
}
mv.visitVarInsn(ASTORE, j);
} else {
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, getPopMethod(type), "()" + type.getDescriptor());
mv.visitVarInsn(type.getOpcode(ISTORE), j);
}
}
}
if (frame instanceof MonitoringFrame) {
int[] monitoredLocals = ((MonitoringFrame) frame).getMonitored();
// System.out.println(System.identityHashCode(frame)+" AMonitored locals "+monitoredLocals.length);
for (int monitoredLocal : monitoredLocals) {
// System.out.println(System.identityHashCode(frame)+" AMonitored local "+monitoredLocals[j]);
mv.visitVarInsn(ALOAD, monitoredLocal);
mv.visitInsn(MONITORENTER);
}
}
// stack
int argSize = Type.getArgumentTypes(mnode.desc).length;
int ownerSize = mnode.getOpcode() == INVOKESTATIC ? 0 : 1; // TODO
int initSize = mnode.name.equals("<init>") ? 2 : 0;
int ssize = frame.getStackSize();
for (int j = 0; j < ssize - argSize - ownerSize - initSize; j++) {
BasicValue value = (BasicValue) frame.getStack(j);
if (isNull(value)) {
mv.visitInsn(ACONST_NULL);
} else if (value == BasicValue.UNINITIALIZED_VALUE) {
// TODO ??
} else if (value == BasicValue.RETURNADDRESS_VALUE) {
// TODO ??
} else if (value.isReference()) {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, POP_METHOD + "Object", "()Ljava/lang/Object;");
mv.visitTypeInsn(CHECKCAST, value.getType().getInternalName());
} else {
Type type = value.getType();
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, getPopMethod(type), "()" + type.getDescriptor());
}
}
if (mnode.getOpcode() != INVOKESTATIC) {
// Load the object whose method we are calling
BasicValue value = ((BasicValue) frame.getStack(ssize - argSize - 1));
if (isNull(value)) {
// If user code causes NPE, then we keep this behavior: load null to get NPE at runtime
mv.visitInsn(ACONST_NULL);
} else {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, POP_METHOD + "Reference", "()Ljava/lang/Object;");
mv.visitTypeInsn(CHECKCAST, value.getType().getInternalName());
}
}
// Create null types for the parameters of the method invocation
for (Type paramType : Type.getArgumentTypes(mnode.desc)) {
pushDefault(paramType);
}
// continue to the next method
mv.visitJumpInsn(GOTO, frameLabel);
}
// PC: }
// end of start block
mv.visitLabel(l0);
}
@Override
public void visitLabel(Label label) {
if (currentIndex < labels.size() && label == labels.get(currentIndex)) {
int i = canalyzer.getIndex(nodes.get(currentIndex));
currentFrame = analyzer.getFrames()[i];
}
mv.visitLabel(label);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc) {
mv.visitMethodInsn(opcode, owner, name, desc);
if (currentFrame != null) {
Label fl = new Label();
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitJumpInsn(IFNULL, fl);
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitFieldInsn(GETFIELD, STACK_RECORDER, "isCapturing", "Z");
mv.visitJumpInsn(IFEQ, fl);
// save stack
Type returnType = Type.getReturnType(desc);
boolean hasReturn = returnType != Type.VOID_TYPE;
if (hasReturn) {
mv.visitInsn(returnType.getSize() == 1 ? POP : POP2);
}
Type[] params = Type.getArgumentTypes(desc);
int argSize = params.length;
int ownerSize = opcode == INVOKESTATIC ? 0 : 1; // TODO
int ssize = currentFrame.getStackSize() - argSize - ownerSize;
for (int i = ssize - 1; i >= 0; i--) {
BasicValue value = (BasicValue) currentFrame.getStack(i);
if (isNull(value)) {
mv.visitInsn(POP);
} else if (value == BasicValue.UNINITIALIZED_VALUE) {
// TODO ??
} else if (value.isReference()) {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, PUSH_METHOD + "Object", "(Ljava/lang/Object;)V");
} else {
Type type = value.getType();
if (type.getSize() > 1) {
mv.visitInsn(ACONST_NULL); // dummy stack entry
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitInsn(DUP2_X2); // swap2 for long/double
mv.visitInsn(POP2);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, getPushMethod(type), "(" + type.getDescriptor() + ")V");
mv.visitInsn(POP); // remove dummy stack entry
} else {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitInsn(SWAP);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, getPushMethod(type), "(" + type.getDescriptor() + ")V");
}
}
}
if (!isStatic) {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, PUSH_METHOD + "Reference", "(Ljava/lang/Object;)V");
}
// save locals
int fsize = currentFrame.getLocals();
for (int j = 0; j < fsize; j++) {
BasicValue value = (BasicValue) currentFrame.getLocal(j);
if (isNull(value)) {
// no need to save null
} else if (value == BasicValue.UNINITIALIZED_VALUE) {
// no need to save uninitialized objects
} else if (value.isReference()) {
mv.visitVarInsn(ALOAD, stackRecorderVar);
mv.visitVarInsn(ALOAD, j);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, PUSH_METHOD + "Object", "(Ljava/lang/Object;)V");
} else {
mv.visitVarInsn(ALOAD, stackRecorderVar);
Type type = value.getType();
mv.visitVarInsn(type.getOpcode(ILOAD), j);
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, getPushMethod(type), "(" + type.getDescriptor() + ")V");
}
}
mv.visitVarInsn(ALOAD, stackRecorderVar);
if(currentIndex >= 128) {
// if > 127 then it's a SIPUSH, not a BIPUSH...
mv.visitIntInsn(SIPUSH, currentIndex);
} else {
// TODO optimize to iconst_0...
mv.visitIntInsn(BIPUSH, currentIndex);
}
mv.visitMethodInsn(INVOKEVIRTUAL, STACK_RECORDER, "pushInt", "(I)V");
if (currentFrame instanceof MonitoringFrame) {
int[] monitoredLocals = ((MonitoringFrame) currentFrame).getMonitored();
// System.out.println(System.identityHashCode(currentFrame)+" Monitored locals "+monitoredLocals.length);
for (int monitoredLocal : monitoredLocals) {
// System.out.println(System.identityHashCode(currentFrame)+" Monitored local "+monitoredLocals[j]);
mv.visitVarInsn(ALOAD, monitoredLocal);
mv.visitInsn(MONITOREXIT);
}
}
Type methodReturnType = Type.getReturnType(methodDesc);
pushDefault(methodReturnType);
mv.visitInsn(methodReturnType.getOpcode(IRETURN));
mv.visitLabel(fl);
currentIndex++;
currentFrame = null;
}
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
Label endLabel = new Label();
mv.visitLabel(endLabel);
mv.visitLocalVariable("__stackRecorder", "L" + STACK_RECORDER + ";", null, startLabel, endLabel, stackRecorderVar);
mv.visitMaxs(0, 0);
}
static boolean isNull(BasicValue value) {
if (null == value) {
return true;
}
if (!value.isReference()) {
return false;
}
final Type type = value.getType();
return "Lnull;".equals(type.getDescriptor());
}
void pushDefault(Type type) {
switch (type.getSort()) {
case Type.VOID:
break;
case Type.DOUBLE:
mv.visitInsn(DCONST_0);
break;
case Type.LONG:
mv.visitInsn(LCONST_0);
break;
case Type.FLOAT:
mv.visitInsn(FCONST_0);
break;
case Type.OBJECT:
case Type.ARRAY:
mv.visitInsn(ACONST_NULL);
break;
default:
mv.visitInsn(ICONST_0);
break;
}
}
String getPopMethod(Type type) {
return POP_METHOD + SUFFIXES[type.getSort()];
}
String getPushMethod(Type type) {
return PUSH_METHOD + SUFFIXES[type.getSort()];
}
}
| apache-2.0 |
STRiDGE/dozer | core/src/test/java/org/dozer/loader/xml/MappingStreamReaderTest.java | 1421 | /*
* Copyright 2005-2017 Dozer Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dozer.loader.xml;
import java.io.IOException;
import java.io.InputStream;
import org.dozer.classmap.MappingFileData;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Dmitry Buzdin
*/
public class MappingStreamReaderTest {
private MappingStreamReader streamReader;
@Before
public void setUp() throws Exception {
streamReader = new MappingStreamReader(XMLParserFactory.getInstance());
}
@Test
public void loadFromStreamTest() throws IOException {
InputStream xmlStream = getClass().getClassLoader().getResourceAsStream("dozerBeanMapping.xml");
MappingFileData data = streamReader.read(xmlStream);
xmlStream.close();
assertThat(data, notNullValue());
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-globalaccelerator/src/main/java/com/amazonaws/services/globalaccelerator/model/DeleteAcceleratorRequest.java | 3789 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.globalaccelerator.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/globalaccelerator-2018-08-08/DeleteAccelerator"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteAcceleratorRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of an accelerator.
* </p>
*/
private String acceleratorArn;
/**
* <p>
* The Amazon Resource Name (ARN) of an accelerator.
* </p>
*
* @param acceleratorArn
* The Amazon Resource Name (ARN) of an accelerator.
*/
public void setAcceleratorArn(String acceleratorArn) {
this.acceleratorArn = acceleratorArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of an accelerator.
* </p>
*
* @return The Amazon Resource Name (ARN) of an accelerator.
*/
public String getAcceleratorArn() {
return this.acceleratorArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of an accelerator.
* </p>
*
* @param acceleratorArn
* The Amazon Resource Name (ARN) of an accelerator.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DeleteAcceleratorRequest withAcceleratorArn(String acceleratorArn) {
setAcceleratorArn(acceleratorArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAcceleratorArn() != null)
sb.append("AcceleratorArn: ").append(getAcceleratorArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DeleteAcceleratorRequest == false)
return false;
DeleteAcceleratorRequest other = (DeleteAcceleratorRequest) obj;
if (other.getAcceleratorArn() == null ^ this.getAcceleratorArn() == null)
return false;
if (other.getAcceleratorArn() != null && other.getAcceleratorArn().equals(this.getAcceleratorArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAcceleratorArn() == null) ? 0 : getAcceleratorArn().hashCode());
return hashCode;
}
@Override
public DeleteAcceleratorRequest clone() {
return (DeleteAcceleratorRequest) super.clone();
}
}
| apache-2.0 |
melish/icecat | src/main/java/edw/icecat/ws/response/Product.java | 37355 |
package edw.icecat.ws.response;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for Product complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Product">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Category" type="{}Category" maxOccurs="unbounded"/>
* <element name="CategoryFeatureGroup" type="{}CategoryFeatureGroup" maxOccurs="unbounded" minOccurs="0"/>
* <element name="EANCode" type="{}EANCode" maxOccurs="unbounded" minOccurs="0"/>
* <element name="FeatureLogo" type="{}FeatureLogo" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProductBullets" type="{}ProductBullets" minOccurs="0"/>
* <element name="ProductBullets_HTMLs" type="{}ProductBullets_HTMLs" minOccurs="0"/>
* <element name="ReasonsToBuy" type="{}ReasonsToBuy" minOccurs="0"/>
* <element name="ProductBundled" type="{}ProductBundled" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProductDescription" type="{}ProductDescription" maxOccurs="unbounded"/>
* <element name="ProductFamily" type="{}ProductFamily" minOccurs="0"/>
* <element name="ProductFeature" type="{}ProductFeature" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProductGallery" type="{}ProductGallery" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProductMultimediaObject" type="{}ProductMultimediaObject" maxOccurs="unbounded" minOccurs="0"/>
* <element name="ProductRelated" type="{}ProductRelated" maxOccurs="unbounded" minOccurs="0"/>
* <element name="SummaryDescription" type="{}SummaryDescription" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Supplier" type="{}Supplier"/>
* </sequence>
* <attribute name="ID" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="Name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Prod_id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="ThumbPic" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="Quality" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Code" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="EANCode" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="HighPic" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="LowPic" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="Score" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="ProductsDescription" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Relevance" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="LowPicSize" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="LowPicWidth" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="LowPicHeight" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="HighPicSize" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="HighPicWidth" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="HighPicHeight" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="ThumbPicSize" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="ErrorMessage" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Map_product_id" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="ReleaseDate" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="BrandStartOfSaleDate" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="BrandEndOfSaleDate" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Title" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="Pic500x500" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="Pic500x500Size" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="Pic500x500Width" type="{http://www.w3.org/2001/XMLSchema}integer" />
* <attribute name="Pic500x500Height" type="{http://www.w3.org/2001/XMLSchema}integer" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Product", propOrder = {
"category",
"categoryFeatureGroup",
"eanCode",
"featureLogo",
"productBullets",
"productBulletsHTMLs",
"reasonsToBuy",
"productBundled",
"productDescription",
"productFamily",
"productFeature",
"productGallery",
"productMultimediaObject",
"productRelated",
"summaryDescription",
"supplier"
})
public class Product
implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlElement(name = "Category", required = true)
protected List<Category> category;
@XmlElement(name = "CategoryFeatureGroup")
protected List<CategoryFeatureGroup> categoryFeatureGroup;
@XmlElement(name = "EANCode")
protected List<EANCode> eanCode;
@XmlElement(name = "FeatureLogo")
protected List<FeatureLogo> featureLogo;
@XmlElement(name = "ProductBullets")
protected ProductBullets productBullets;
@XmlElement(name = "ProductBullets_HTMLs")
protected ProductBulletsHTMLs productBulletsHTMLs;
@XmlElement(name = "ReasonsToBuy")
protected ReasonsToBuy reasonsToBuy;
@XmlElement(name = "ProductBundled")
protected List<ProductBundled> productBundled;
@XmlElement(name = "ProductDescription", required = true)
protected List<ProductDescription> productDescription;
@XmlElement(name = "ProductFamily")
protected ProductFamily productFamily;
@XmlElement(name = "ProductFeature")
protected List<ProductFeature> productFeature;
@XmlElement(name = "ProductGallery")
protected List<ProductGallery> productGallery;
@XmlElement(name = "ProductMultimediaObject")
protected List<ProductMultimediaObject> productMultimediaObject;
@XmlElement(name = "ProductRelated")
protected List<ProductRelated> productRelated;
@XmlElement(name = "SummaryDescription")
protected List<SummaryDescription> summaryDescription;
@XmlElement(name = "Supplier", required = true)
protected Supplier supplier;
@XmlAttribute(name = "ID", required = true)
@XmlJavaTypeAdapter(Adapter1 .class)
@XmlSchemaType(name = "integer")
protected String id;
@XmlAttribute(name = "Name", required = true)
protected String name;
@XmlAttribute(name = "Prod_id", required = true)
protected String prodId;
@XmlAttribute(name = "ThumbPic", required = true)
@XmlSchemaType(name = "anyURI")
protected String thumbPic;
@XmlAttribute(name = "Quality")
protected String quality;
@XmlAttribute(name = "Code")
protected BigInteger code;
@XmlAttribute(name = "EANCode")
protected String eanCodeAttr;
@XmlAttribute(name = "HighPic")
@XmlSchemaType(name = "anyURI")
protected String highPic;
@XmlAttribute(name = "LowPic")
@XmlSchemaType(name = "anyURI")
protected String lowPic;
@XmlAttribute(name = "Score")
protected BigInteger score;
@XmlAttribute(name = "ProductsDescription")
protected String productsDescription;
@XmlAttribute(name = "Relevance")
protected BigInteger relevance;
@XmlAttribute(name = "LowPicSize")
protected BigInteger lowPicSize;
@XmlAttribute(name = "LowPicWidth")
protected BigInteger lowPicWidth;
@XmlAttribute(name = "LowPicHeight")
protected BigInteger lowPicHeight;
@XmlAttribute(name = "HighPicSize")
protected BigInteger highPicSize;
@XmlAttribute(name = "HighPicWidth")
protected BigInteger highPicWidth;
@XmlAttribute(name = "HighPicHeight")
protected BigInteger highPicHeight;
@XmlAttribute(name = "ThumbPicSize")
protected BigInteger thumbPicSize;
@XmlAttribute(name = "ErrorMessage")
protected String errorMessage;
@XmlAttribute(name = "Map_product_id")
protected BigInteger mapProductId;
@XmlAttribute(name = "ReleaseDate")
protected String releaseDate;
@XmlAttribute(name = "BrandStartOfSaleDate")
protected String brandStartOfSaleDate;
@XmlAttribute(name = "BrandEndOfSaleDate")
protected String brandEndOfSaleDate;
@XmlAttribute(name = "Title")
protected String title;
@XmlAttribute(name = "Pic500x500")
@XmlSchemaType(name = "anyURI")
protected String pic500X500;
@XmlAttribute(name = "Pic500x500Size")
protected BigInteger pic500X500Size;
@XmlAttribute(name = "Pic500x500Width")
protected BigInteger pic500X500Width;
@XmlAttribute(name = "Pic500x500Height")
protected BigInteger pic500X500Height;
/**
* Gets the value of the category property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the category property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCategory().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Category }
*
*
*/
public List<Category> getCategory() {
if (category == null) {
category = new ArrayList<Category>();
}
return this.category;
}
/**
* Gets the value of the categoryFeatureGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the categoryFeatureGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCategoryFeatureGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CategoryFeatureGroup }
*
*
*/
public List<CategoryFeatureGroup> getCategoryFeatureGroup() {
if (categoryFeatureGroup == null) {
categoryFeatureGroup = new ArrayList<CategoryFeatureGroup>();
}
return this.categoryFeatureGroup;
}
/**
* Gets the value of the eanCode property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the eanCode property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEANCode().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EANCode }
*
*
*/
public List<EANCode> getEANCode() {
if (eanCode == null) {
eanCode = new ArrayList<EANCode>();
}
return this.eanCode;
}
/**
* Gets the value of the featureLogo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the featureLogo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFeatureLogo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FeatureLogo }
*
*
*/
public List<FeatureLogo> getFeatureLogo() {
if (featureLogo == null) {
featureLogo = new ArrayList<FeatureLogo>();
}
return this.featureLogo;
}
/**
* Gets the value of the productBullets property.
*
* @return
* possible object is
* {@link ProductBullets }
*
*/
public ProductBullets getProductBullets() {
return productBullets;
}
/**
* Sets the value of the productBullets property.
*
* @param value
* allowed object is
* {@link ProductBullets }
*
*/
public void setProductBullets(ProductBullets value) {
this.productBullets = value;
}
/**
* Gets the value of the productBulletsHTMLs property.
*
* @return
* possible object is
* {@link ProductBulletsHTMLs }
*
*/
public ProductBulletsHTMLs getProductBulletsHTMLs() {
return productBulletsHTMLs;
}
/**
* Sets the value of the productBulletsHTMLs property.
*
* @param value
* allowed object is
* {@link ProductBulletsHTMLs }
*
*/
public void setProductBulletsHTMLs(ProductBulletsHTMLs value) {
this.productBulletsHTMLs = value;
}
/**
* Gets the value of the reasonsToBuy property.
*
* @return
* possible object is
* {@link ReasonsToBuy }
*
*/
public ReasonsToBuy getReasonsToBuy() {
return reasonsToBuy;
}
/**
* Sets the value of the reasonsToBuy property.
*
* @param value
* allowed object is
* {@link ReasonsToBuy }
*
*/
public void setReasonsToBuy(ReasonsToBuy value) {
this.reasonsToBuy = value;
}
/**
* Gets the value of the productBundled property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productBundled property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductBundled().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductBundled }
*
*
*/
public List<ProductBundled> getProductBundled() {
if (productBundled == null) {
productBundled = new ArrayList<ProductBundled>();
}
return this.productBundled;
}
/**
* Gets the value of the productDescription property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productDescription property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductDescription }
*
*
*/
public List<ProductDescription> getProductDescription() {
if (productDescription == null) {
productDescription = new ArrayList<ProductDescription>();
}
return this.productDescription;
}
/**
* Gets the value of the productFamily property.
*
* @return
* possible object is
* {@link ProductFamily }
*
*/
public ProductFamily getProductFamily() {
return productFamily;
}
/**
* Sets the value of the productFamily property.
*
* @param value
* allowed object is
* {@link ProductFamily }
*
*/
public void setProductFamily(ProductFamily value) {
this.productFamily = value;
}
/**
* Gets the value of the productFeature property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productFeature property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductFeature().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductFeature }
*
*
*/
public List<ProductFeature> getProductFeature() {
if (productFeature == null) {
productFeature = new ArrayList<ProductFeature>();
}
return this.productFeature;
}
/**
* Gets the value of the productGallery property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productGallery property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductGallery().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductGallery }
*
*
*/
public List<ProductGallery> getProductGallery() {
if (productGallery == null) {
productGallery = new ArrayList<ProductGallery>();
}
return this.productGallery;
}
/**
* Gets the value of the productMultimediaObject property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productMultimediaObject property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductMultimediaObject().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductMultimediaObject }
*
*
*/
public List<ProductMultimediaObject> getProductMultimediaObject() {
if (productMultimediaObject == null) {
productMultimediaObject = new ArrayList<ProductMultimediaObject>();
}
return this.productMultimediaObject;
}
/**
* Gets the value of the productRelated property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the productRelated property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProductRelated().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProductRelated }
*
*
*/
public List<ProductRelated> getProductRelated() {
if (productRelated == null) {
productRelated = new ArrayList<ProductRelated>();
}
return this.productRelated;
}
/**
* Gets the value of the summaryDescription property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the summaryDescription property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSummaryDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SummaryDescription }
*
*
*/
public List<SummaryDescription> getSummaryDescription() {
if (summaryDescription == null) {
summaryDescription = new ArrayList<SummaryDescription>();
}
return this.summaryDescription;
}
/**
* Gets the value of the supplier property.
*
* @return
* possible object is
* {@link Supplier }
*
*/
public Supplier getSupplier() {
return supplier;
}
/**
* Sets the value of the supplier property.
*
* @param value
* allowed object is
* {@link Supplier }
*
*/
public void setSupplier(Supplier value) {
this.supplier = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setID(String value) {
this.id = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the prodId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProdId() {
return prodId;
}
/**
* Sets the value of the prodId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProdId(String value) {
this.prodId = value;
}
/**
* Gets the value of the thumbPic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getThumbPic() {
return thumbPic;
}
/**
* Sets the value of the thumbPic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setThumbPic(String value) {
this.thumbPic = value;
}
/**
* Gets the value of the quality property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQuality() {
return quality;
}
/**
* Sets the value of the quality property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQuality(String value) {
this.quality = value;
}
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setCode(BigInteger value) {
this.code = value;
}
/**
* Gets the value of the eanCodeAttr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEANCodeAttr() {
return eanCodeAttr;
}
/**
* Sets the value of the eanCodeAttr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEANCodeAttr(String value) {
this.eanCodeAttr = value;
}
/**
* Gets the value of the highPic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHighPic() {
return highPic;
}
/**
* Sets the value of the highPic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHighPic(String value) {
this.highPic = value;
}
/**
* Gets the value of the lowPic property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLowPic() {
return lowPic;
}
/**
* Sets the value of the lowPic property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLowPic(String value) {
this.lowPic = value;
}
/**
* Gets the value of the score property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getScore() {
return score;
}
/**
* Sets the value of the score property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setScore(BigInteger value) {
this.score = value;
}
/**
* Gets the value of the productsDescription property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProductsDescription() {
return productsDescription;
}
/**
* Sets the value of the productsDescription property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProductsDescription(String value) {
this.productsDescription = value;
}
/**
* Gets the value of the relevance property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getRelevance() {
return relevance;
}
/**
* Sets the value of the relevance property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setRelevance(BigInteger value) {
this.relevance = value;
}
/**
* Gets the value of the lowPicSize property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getLowPicSize() {
return lowPicSize;
}
/**
* Sets the value of the lowPicSize property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setLowPicSize(BigInteger value) {
this.lowPicSize = value;
}
/**
* Gets the value of the lowPicWidth property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getLowPicWidth() {
return lowPicWidth;
}
/**
* Sets the value of the lowPicWidth property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setLowPicWidth(BigInteger value) {
this.lowPicWidth = value;
}
/**
* Gets the value of the lowPicHeight property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getLowPicHeight() {
return lowPicHeight;
}
/**
* Sets the value of the lowPicHeight property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setLowPicHeight(BigInteger value) {
this.lowPicHeight = value;
}
/**
* Gets the value of the highPicSize property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getHighPicSize() {
return highPicSize;
}
/**
* Sets the value of the highPicSize property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setHighPicSize(BigInteger value) {
this.highPicSize = value;
}
/**
* Gets the value of the highPicWidth property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getHighPicWidth() {
return highPicWidth;
}
/**
* Sets the value of the highPicWidth property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setHighPicWidth(BigInteger value) {
this.highPicWidth = value;
}
/**
* Gets the value of the highPicHeight property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getHighPicHeight() {
return highPicHeight;
}
/**
* Sets the value of the highPicHeight property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setHighPicHeight(BigInteger value) {
this.highPicHeight = value;
}
/**
* Gets the value of the thumbPicSize property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getThumbPicSize() {
return thumbPicSize;
}
/**
* Sets the value of the thumbPicSize property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setThumbPicSize(BigInteger value) {
this.thumbPicSize = value;
}
/**
* Gets the value of the errorMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* Sets the value of the errorMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setErrorMessage(String value) {
this.errorMessage = value;
}
/**
* Gets the value of the mapProductId property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getMapProductId() {
return mapProductId;
}
/**
* Sets the value of the mapProductId property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setMapProductId(BigInteger value) {
this.mapProductId = value;
}
/**
* Gets the value of the releaseDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReleaseDate() {
return releaseDate;
}
/**
* Sets the value of the releaseDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReleaseDate(String value) {
this.releaseDate = value;
}
/**
* Gets the value of the brandStartOfSaleDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBrandStartOfSaleDate() {
return brandStartOfSaleDate;
}
/**
* Sets the value of the brandStartOfSaleDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBrandStartOfSaleDate(String value) {
this.brandStartOfSaleDate = value;
}
/**
* Gets the value of the brandEndOfSaleDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBrandEndOfSaleDate() {
return brandEndOfSaleDate;
}
/**
* Sets the value of the brandEndOfSaleDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBrandEndOfSaleDate(String value) {
this.brandEndOfSaleDate = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the pic500X500 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPic500X500() {
return pic500X500;
}
/**
* Sets the value of the pic500X500 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPic500X500(String value) {
this.pic500X500 = value;
}
/**
* Gets the value of the pic500X500Size property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPic500X500Size() {
return pic500X500Size;
}
/**
* Sets the value of the pic500X500Size property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPic500X500Size(BigInteger value) {
this.pic500X500Size = value;
}
/**
* Gets the value of the pic500X500Width property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPic500X500Width() {
return pic500X500Width;
}
/**
* Sets the value of the pic500X500Width property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPic500X500Width(BigInteger value) {
this.pic500X500Width = value;
}
/**
* Gets the value of the pic500X500Height property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPic500X500Height() {
return pic500X500Height;
}
/**
* Sets the value of the pic500X500Height property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPic500X500Height(BigInteger value) {
this.pic500X500Height = value;
}
}
| apache-2.0 |
ssimd/obd-java-api | src/main/java/pt/lighthouselabs/obd/commands/control/VinObdCommand.java | 1511 | /**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package pt.lighthouselabs.obd.commands.control;
import pt.lighthouselabs.obd.commands.PersistentObdCommand;
import pt.lighthouselabs.obd.enums.AvailableCommandNames;
public class VinObdCommand extends PersistentObdCommand {
String vin = "";
/**
* Default ctor.
*/
public VinObdCommand() {
super("09 02");
}
/**
* Copy ctor.
*
* @param other a {@link VinObdCommand} object.
*/
public VinObdCommand(VinObdCommand other) {
super(other);
}
@Override
protected void performCalculations() {
// ignore first two bytes [01 31] of the response
StringBuilder b = new StringBuilder();
for (int i = 2; i < buffer.size(); i++) {
b.append(Character.toChars(buffer.get(i)));
}
vin = b.toString();
}
@Override
public String getFormattedResult() {
return String.valueOf(rawData);
}
@Override
public String getName() {
return AvailableCommandNames.VIN.getValue();
}
}
| apache-2.0 |
mcwarman/interlok | adapter/src/main/java/com/adaptris/core/fs/FsHelper.java | 6910 | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.fs;
import static org.apache.commons.lang.StringUtils.isEmpty;
import java.io.File;
import java.io.FileFilter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import com.adaptris.fs.FsException;
import com.adaptris.fs.FsFilenameExistsException;
import com.adaptris.fs.FsWorker;
/**
* <p>
* Helper class for <code>FsMessageConsumer</code> and <code>FsMessageProducer</code>.
* </p>
*/
public final class FsHelper {
private FsHelper() {
// no instances
}
/**
* Create a file reference from a URL using the platform default encoding for the URL.
*
* @see #createFileReference(URL, String)
*/
public static File createFileReference(URL url) throws UnsupportedEncodingException {
return createFileReference(url, null);
}
/**
* Create a file reference from a URL using the platform default encoding for the URL.
*
* @param url the URL.
* @param charset the encoding that the url is considered to be in.
* @return a File object
* @throws UnsupportedEncodingException if the encoding was not supported.
*/
public static File createFileReference(URL url, String charset) throws UnsupportedEncodingException {
String charSetToUse = charset == null ? System.getProperty("file.encoding") : charset;
String filename = URLDecoder.decode(url.getPath(), charSetToUse);
// Cope with file://localhost/./config/blah -> /./config/blah is the result of getPath()
// Munge that properly.
if (filename.startsWith("/.")) {
filename = filename.substring(1);
}
return new File(filename);
}
/**
* <p>
* Creates a {@link URL} based on the passed destination. If a <i>scheme</i> is present and is equal to <code>"file"</code> then
* the <code>URL</code> is deemed to be <b>absolute</b> and is used as is. If the <i>scheme</i> is <code>null</code> the
* <code>URL</code> is deemed to of scheme <code>"file"</code> and <b>relative</b> to the current working directory.
* </p>
* <p>
* Note that this method will not convert backslashes into forward slashes, so passing in a string like {@code ..\dir\} will fail
* with a URISyntaxException; use {@link #createUrlFromString(String, boolean)} to convert backslashes into forward slashes prior
* to processing.
* </p>
*
* @param s the String to convert to a URL.
* @return a new URL
* @see #createUrlFromString(String, boolean)
* @deprecated use {@link #createUrlFromString(String, boolean)} since 3.0.3
*/
@Deprecated
public static URL createUrlFromString(String s) throws Exception {
return createUrlFromString(s, false);
}
/**
* <p>
* Creates a {@link URL} based on the passed destination. If a <i>scheme</i> is present and is equal to <code>"file"</code> then
* the <code>URL</code> is deemed to be <b>absolute</b> and is used as is. If the <i>scheme</i> is <code>null</code> the
* <code>URL</code> is deemed to of scheme <code>"file"</code> and <b>relative</b> to the current working directory.
* </p>
*
* @param s the string to convert to a URL.
* @param backslashConvert whether or not to convert backslashes into forward slashes.
*
*/
public static URL createUrlFromString(String s, boolean backslashConvert) throws Exception {
String destToConvert = backslashConvert ? backslashToSlash(s) : s;
URI configuredUri = null;
try {
configuredUri = new URI(destToConvert);
}
catch (URISyntaxException e) {
// Specifically here to cope with file:///c:/ (which is
// technically illegal according to RFC2396 but we need
// to support it
if (destToConvert.split(":").length >= 3) {
configuredUri = new URI(URLEncoder.encode(destToConvert, "UTF-8"));
}
else {
throw e;
}
}
String scheme = configuredUri.getScheme();
if ("file".equals(scheme)) {
// nb for some reason, configuredUri.toUrl() doesn't work...
// return configuredUri.toURL();
return new URL(configuredUri.toString());
}
else {
if (scheme == null) {
return relativeConfig(configuredUri);
}
else {
throw new IllegalArgumentException("illegal destination [" + s + "]");
}
}
}
public static FileFilter createFilter(String filterExpression, String filterImpl) throws Exception {
FileFilter result = null;
if (isEmpty(filterExpression)) {
result = new NoOpFileFilter();
}
else {
Class[] paramTypes =
{
filterExpression.getClass()
};
Object[] args =
{
filterExpression
};
Class c = Class.forName(filterImpl);
Constructor cnst = c.getDeclaredConstructor(paramTypes);
result = (FileFilter) cnst.newInstance(args);
}
return result;
}
public static File renameFile(File file, String suffix, FsWorker worker) throws FsException {
File newFile = new File(file.getAbsolutePath() + suffix);
try {
worker.rename(file, newFile);
}
catch (FsFilenameExistsException e) {
newFile = new File(file.getParentFile(), System.currentTimeMillis() + "." + file.getName() + suffix);
worker.rename(file, newFile);
}
return newFile;
}
/**
*
* @param uri the relative <code>URI</code> to process
* @return a <code>file:/// URL</code> based on the current working directory (obtained by calling
* <code>System.getProperty("user.dir")</code>) plus the passed relative <code>uri</code>
* @throws Exception wrapping any underlying <code>Exception</code>
*/
private static URL relativeConfig(URI uri) throws Exception {
String pwd = System.getProperty("user.dir");
String path = pwd + "/" + uri; // ok even if uri starts with a /
URL result = new URL("file:///" + path);
return result;
}
private static String backslashToSlash(String url) {
if (!isEmpty(url)) {
return url.replaceAll("\\\\", "/");
}
return url;
}
private static class NoOpFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return true;
}
}
}
| apache-2.0 |
smanvi-pivotal/geode | geode-cq/src/main/java/org/apache/geode/cache/client/internal/CreateCQOp.java | 6289 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.client.internal;
import org.apache.geode.InternalGemFireError;
import org.apache.geode.cache.client.ServerOperationException;
import org.apache.geode.cache.client.internal.AbstractOp;
import org.apache.geode.cache.client.internal.Connection;
import org.apache.geode.cache.client.internal.ConnectionStats;
import org.apache.geode.cache.client.internal.ExecutablePool;
import org.apache.geode.internal.Version;
import org.apache.geode.internal.cache.tier.MessageType;
import org.apache.geode.internal.cache.tier.sockets.ChunkedMessage;
import org.apache.geode.internal.cache.tier.sockets.Message;
import org.apache.geode.internal.cache.tier.sockets.Part;
import org.apache.geode.security.NotAuthorizedException;
/**
* Creates a CQ on a server
*
* @since GemFire 5.7
*/
public class CreateCQOp {
/**
* Create a continuous query on the server using connections from the given pool to communicate
* with the server.
*
* @param pool the pool to use to communicate with the server.
* @param cqName name of the CQ to create
* @param queryStr string OQL statement to be executed
* @param cqState int cqState to be set.
* @param isDurable true if CQ is durable
* @param regionDataPolicy the data policy ordinal of the region
*/
public static Object execute(ExecutablePool pool, String cqName, String queryStr, int cqState,
boolean isDurable, byte regionDataPolicy) {
AbstractOp op = new CreateCQOpImpl(cqName, queryStr, cqState, isDurable, regionDataPolicy);
return pool.executeOnQueuesAndReturnPrimaryResult(op);
}
/**
* Create a continuous query on the server using a specific connections from the given pool.
*
* @param pool the pool to use to communicate with the server.
* @param conn the actual connection to use
* @param cqName name of the CQ to create
* @param queryStr string OQL statement to be executed
* @param cqState int cqState to be set.
* @param isDurable true if CQ is durable
* @param regionDataPolicy the data policy ordinal of the region
*/
public static Object executeOn(ExecutablePool pool, Connection conn, String cqName,
String queryStr, int cqState, boolean isDurable, byte regionDataPolicy) {
AbstractOp op = new CreateCQOpImpl(cqName, queryStr, cqState, isDurable, regionDataPolicy);
return pool.executeOn(conn, op);
}
private CreateCQOp() {
// no instances allowed
}
/**
* Note both StopCQOpImpl and CloseCQOpImpl extend this class
*/
protected static class CreateCQOpImpl extends AbstractOp {
/**
* @throws org.apache.geode.SerializationException if serialization fails
*/
public CreateCQOpImpl(String cqName, String queryStr, int cqState, boolean isDurable,
byte regionDataPolicy) {
super(MessageType.EXECUTECQ_MSG_TYPE, 5);
getMessage().addStringPart(cqName);
getMessage().addStringPart(queryStr);
getMessage().addIntPart(cqState);
{
byte durableByte = (byte) (isDurable ? 0x01 : 0x00);
getMessage().addBytesPart(new byte[] {durableByte});
}
getMessage().addBytesPart(new byte[] {regionDataPolicy});
}
@Override
protected Message createResponseMessage() {
return new ChunkedMessage(1, Version.CURRENT);
}
@Override
protected Object processResponse(Message m) throws Exception {
ChunkedMessage msg = (ChunkedMessage) m;
msg.readHeader();
int msgType = msg.getMessageType();
msg.receiveChunk();
if (msgType == MessageType.REPLY) {
return Boolean.TRUE;
} else {
if (msgType == MessageType.EXCEPTION) {
Part part = msg.getPart(0);
String s = "While performing a remote " + getOpName();
throw new ServerOperationException(s, (Throwable) part.getObject());
} else if (isErrorResponse(msgType)) {
Part part = msg.getPart(0);
// Dan Smith- a hack, but I don't want to change the protocol right
// now. We need to throw a security exception so that the exception
// will be propagated up properly. Ideally, this exception would be
// contained in the message..
String errorMessage = part.getString();
if (errorMessage.indexOf("Not authorized") >= 0) {
throw new NotAuthorizedException(errorMessage);
}
throw new ServerOperationException(errorMessage);
} else {
throw new InternalGemFireError(
"Unexpected message type " + MessageType.getString(msgType));
}
}
}
/**
* This constructor is for our subclasses
*
* @throws org.apache.geode.SerializationException if serialization fails
*/
protected CreateCQOpImpl(int msgType, int numParts) {
super(msgType, numParts);
}
protected String getOpName() {
return "createCQ";
}
@Override
protected boolean isErrorResponse(int msgType) {
return msgType == MessageType.CQDATAERROR_MSG_TYPE
|| msgType == MessageType.CQ_EXCEPTION_TYPE;
}
@Override
protected long startAttempt(ConnectionStats stats) {
return stats.startCreateCQ();
}
@Override
protected void endSendAttempt(ConnectionStats stats, long start) {
stats.endCreateCQSend(start, hasFailed());
}
@Override
protected void endAttempt(ConnectionStats stats, long start) {
stats.endCreateCQ(start, hasTimedOut(), hasFailed());
}
}
}
| apache-2.0 |
openegovplatform/OEPv2 | oep-processmgt-portlet/docroot/WEB-INF/service/org/oep/processmgt/model/DossierProc2ProcessSoap.java | 6545 | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package org.oep.processmgt.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* This class is used by SOAP remote services, specifically {@link org.oep.processmgt.service.http.DossierProc2ProcessServiceSoap}.
*
* @author trungdk
* @see org.oep.processmgt.service.http.DossierProc2ProcessServiceSoap
* @generated
*/
public class DossierProc2ProcessSoap implements Serializable {
public static DossierProc2ProcessSoap toSoapModel(DossierProc2Process model) {
DossierProc2ProcessSoap soapModel = new DossierProc2ProcessSoap();
soapModel.setDossierProc2ProcessId(model.getDossierProc2ProcessId());
soapModel.setUserId(model.getUserId());
soapModel.setGroupId(model.getGroupId());
soapModel.setCompanyId(model.getCompanyId());
soapModel.setCreateDate(model.getCreateDate());
soapModel.setModifiedDate(model.getModifiedDate());
soapModel.setDossierProcId(model.getDossierProcId());
soapModel.setGovAgencyId(model.getGovAgencyId());
soapModel.setGovAgencyName(model.getGovAgencyName());
soapModel.setDossierProcessId(model.getDossierProcessId());
soapModel.setAaaa(model.getAaaa());
soapModel.setBbb(model.getBbb());
soapModel.setDaysDuration(model.getDaysDuration());
soapModel.setPaymentFee(model.getPaymentFee());
soapModel.setPaymentOneGate(model.getPaymentOneGate());
soapModel.setPaymentEservice(model.getPaymentEservice());
soapModel.setOrganizationId(model.getOrganizationId());
soapModel.setEbPartnershipId(model.getEbPartnershipId());
return soapModel;
}
public static DossierProc2ProcessSoap[] toSoapModels(
DossierProc2Process[] models) {
DossierProc2ProcessSoap[] soapModels = new DossierProc2ProcessSoap[models.length];
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModel(models[i]);
}
return soapModels;
}
public static DossierProc2ProcessSoap[][] toSoapModels(
DossierProc2Process[][] models) {
DossierProc2ProcessSoap[][] soapModels = null;
if (models.length > 0) {
soapModels = new DossierProc2ProcessSoap[models.length][models[0].length];
}
else {
soapModels = new DossierProc2ProcessSoap[0][0];
}
for (int i = 0; i < models.length; i++) {
soapModels[i] = toSoapModels(models[i]);
}
return soapModels;
}
public static DossierProc2ProcessSoap[] toSoapModels(
List<DossierProc2Process> models) {
List<DossierProc2ProcessSoap> soapModels = new ArrayList<DossierProc2ProcessSoap>(models.size());
for (DossierProc2Process model : models) {
soapModels.add(toSoapModel(model));
}
return soapModels.toArray(new DossierProc2ProcessSoap[soapModels.size()]);
}
public DossierProc2ProcessSoap() {
}
public long getPrimaryKey() {
return _dossierProc2ProcessId;
}
public void setPrimaryKey(long pk) {
setDossierProc2ProcessId(pk);
}
public long getDossierProc2ProcessId() {
return _dossierProc2ProcessId;
}
public void setDossierProc2ProcessId(long dossierProc2ProcessId) {
_dossierProc2ProcessId = dossierProc2ProcessId;
}
public long getUserId() {
return _userId;
}
public void setUserId(long userId) {
_userId = userId;
}
public long getGroupId() {
return _groupId;
}
public void setGroupId(long groupId) {
_groupId = groupId;
}
public long getCompanyId() {
return _companyId;
}
public void setCompanyId(long companyId) {
_companyId = companyId;
}
public Date getCreateDate() {
return _createDate;
}
public void setCreateDate(Date createDate) {
_createDate = createDate;
}
public Date getModifiedDate() {
return _modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
_modifiedDate = modifiedDate;
}
public long getDossierProcId() {
return _dossierProcId;
}
public void setDossierProcId(long dossierProcId) {
_dossierProcId = dossierProcId;
}
public String getGovAgencyId() {
return _govAgencyId;
}
public void setGovAgencyId(String govAgencyId) {
_govAgencyId = govAgencyId;
}
public String getGovAgencyName() {
return _govAgencyName;
}
public void setGovAgencyName(String govAgencyName) {
_govAgencyName = govAgencyName;
}
public long getDossierProcessId() {
return _dossierProcessId;
}
public void setDossierProcessId(long dossierProcessId) {
_dossierProcessId = dossierProcessId;
}
public String getAaaa() {
return _aaaa;
}
public void setAaaa(String aaaa) {
_aaaa = aaaa;
}
public String getBbb() {
return _bbb;
}
public void setBbb(String bbb) {
_bbb = bbb;
}
public int getDaysDuration() {
return _daysDuration;
}
public void setDaysDuration(int daysDuration) {
_daysDuration = daysDuration;
}
public int getPaymentFee() {
return _paymentFee;
}
public void setPaymentFee(int paymentFee) {
_paymentFee = paymentFee;
}
public int getPaymentOneGate() {
return _paymentOneGate;
}
public void setPaymentOneGate(int paymentOneGate) {
_paymentOneGate = paymentOneGate;
}
public int getPaymentEservice() {
return _paymentEservice;
}
public void setPaymentEservice(int paymentEservice) {
_paymentEservice = paymentEservice;
}
public long getOrganizationId() {
return _organizationId;
}
public void setOrganizationId(long organizationId) {
_organizationId = organizationId;
}
public long getEbPartnershipId() {
return _ebPartnershipId;
}
public void setEbPartnershipId(long ebPartnershipId) {
_ebPartnershipId = ebPartnershipId;
}
private long _dossierProc2ProcessId;
private long _userId;
private long _groupId;
private long _companyId;
private Date _createDate;
private Date _modifiedDate;
private long _dossierProcId;
private String _govAgencyId;
private String _govAgencyName;
private long _dossierProcessId;
private String _aaaa;
private String _bbb;
private int _daysDuration;
private int _paymentFee;
private int _paymentOneGate;
private int _paymentEservice;
private long _organizationId;
private long _ebPartnershipId;
} | apache-2.0 |
CMPUT301F16T15/Youber | app/src/main/java/com/youber/cmput301f16t15/youber/commands/AddRequestCommand.java | 1564 | package com.youber.cmput301f16t15.youber.commands;
import com.youber.cmput301f16t15.youber.elasticsearch.ElasticSearchController;
import com.youber.cmput301f16t15.youber.elasticsearch.ElasticSearchRequest;
import com.youber.cmput301f16t15.youber.requests.Request;
/**
* Created by Jess on 2016-11-16.
*
* @author Jessica Huynh, Aaron Philips, Calvin Ho, Tyler Mathieu, Reem Maarouf
*
* This class implements the command pattern to add a request to elastic search.
*
* @see DeleteRequestCommand
* @see ElasticSearchRequest
* @see Command
* @see RequestCommand
*/
public class AddRequestCommand extends RequestCommand {
public AddRequestCommand(Request r) {
request = r;
}
@Override
public void execute() {
try {
ElasticSearchController.setupPutmap();
// This is for the specific case where we were offline and add an offer as a driver
// but this request had already gotten a selected driver (someone else)
Request esRequest = ElasticSearchController.getRequest(request.getUUID());
if(esRequest != null && !esRequest.getDriverUsernameID().isEmpty() && request.getDriverUsernameID().isEmpty()) {
executionState = true;
return;
}
ElasticSearchRequest.add adder = new ElasticSearchRequest.add();
adder.execute(request);
executionState = true;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void unexecute() {
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/NativeStyleService.java | 3440 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202108;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.2.9-b130926.1035
* Generated source version: 2.1
*
*/
@WebServiceClient(name = "NativeStyleService", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108", wsdlLocation = "https://ads.google.com/apis/ads/publisher/v202108/NativeStyleService?wsdl")
public class NativeStyleService
extends Service
{
private final static URL NATIVESTYLESERVICE_WSDL_LOCATION;
private final static WebServiceException NATIVESTYLESERVICE_EXCEPTION;
private final static QName NATIVESTYLESERVICE_QNAME = new QName("https://www.google.com/apis/ads/publisher/v202108", "NativeStyleService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("https://ads.google.com/apis/ads/publisher/v202108/NativeStyleService?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
NATIVESTYLESERVICE_WSDL_LOCATION = url;
NATIVESTYLESERVICE_EXCEPTION = e;
}
public NativeStyleService() {
super(__getWsdlLocation(), NATIVESTYLESERVICE_QNAME);
}
public NativeStyleService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
/**
*
* @return
* returns NativeStyleServiceInterface
*/
@WebEndpoint(name = "NativeStyleServiceInterfacePort")
public NativeStyleServiceInterface getNativeStyleServiceInterfacePort() {
return super.getPort(new QName("https://www.google.com/apis/ads/publisher/v202108", "NativeStyleServiceInterfacePort"), NativeStyleServiceInterface.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns NativeStyleServiceInterface
*/
@WebEndpoint(name = "NativeStyleServiceInterfacePort")
public NativeStyleServiceInterface getNativeStyleServiceInterfacePort(WebServiceFeature... features) {
return super.getPort(new QName("https://www.google.com/apis/ads/publisher/v202108", "NativeStyleServiceInterfacePort"), NativeStyleServiceInterface.class, features);
}
private static URL __getWsdlLocation() {
if (NATIVESTYLESERVICE_EXCEPTION!= null) {
throw NATIVESTYLESERVICE_EXCEPTION;
}
return NATIVESTYLESERVICE_WSDL_LOCATION;
}
}
| apache-2.0 |
alexishida/aquaino | CoreRaspberry/src/com/aquaino/utils/SerialEvent.java | 2192 | /*
Autor: Alex Ishida
Descrição: Classe para criada para comunicao do arduino via porta
serial utilizando o jssc
Versão: 1.0 (beta)
Data: 08/10/2014
*/
package com.aquaino.utils;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
/**
*
* @author Alex
*/
public class SerialEvent implements SerialPortEventListener {
private SerialPort serialAtiva;
private String retorno = "";
public SerialEvent(SerialPort conexSerial) {
this.serialAtiva = conexSerial;
}
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR()){//If data is available
if(event.getEventValue() > 0){//Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
String buffer = serialAtiva.readString();
retorno = retorno + buffer;
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){///If DSR line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
public String getRetorno() {
String retorno_final = retorno;
retorno = "";
// retorno_final=retorno_final.replace("\r","").replace("\n","");
return retorno_final;
}
}
| apache-2.0 |
youdonghai/intellij-community | jps/model-serialization/src/org/jetbrains/jps/model/serialization/java/JpsJavaModelSerializerExtension.java | 18030 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.model.serialization.java;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsProject;
import org.jetbrains.jps.model.JpsUrlList;
import org.jetbrains.jps.model.java.*;
import org.jetbrains.jps.model.library.JpsOrderRootType;
import org.jetbrains.jps.model.module.JpsDependencyElement;
import org.jetbrains.jps.model.module.JpsModule;
import org.jetbrains.jps.model.module.JpsModuleReference;
import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
import org.jetbrains.jps.model.serialization.JDomSerializationUtil;
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension;
import org.jetbrains.jps.model.serialization.JpsProjectExtensionSerializer;
import org.jetbrains.jps.model.serialization.artifact.JpsPackagingElementSerializer;
import org.jetbrains.jps.model.serialization.java.compiler.*;
import org.jetbrains.jps.model.serialization.library.JpsLibraryRootTypeSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer;
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer;
import java.util.Arrays;
import java.util.List;
/**
* @author nik
*/
public class JpsJavaModelSerializerExtension extends JpsModelSerializerExtension {
public static final String EXPORTED_ATTRIBUTE = "exported";
public static final String SCOPE_ATTRIBUTE = "scope";
public static final String OUTPUT_TAG = "output";
public static final String URL_ATTRIBUTE = "url";
public static final String LANGUAGE_LEVEL_ATTRIBUTE = "languageLevel";
public static final String EXPLODED_TAG = "exploded";
public static final String EXCLUDE_EXPLODED_TAG = "exclude-exploded";
public static final String TEST_OUTPUT_TAG = "output-test";
public static final String INHERIT_COMPILER_OUTPUT_ATTRIBUTE = "inherit-compiler-output";
public static final String EXCLUDE_OUTPUT_TAG = "exclude-output";
private static final String ANNOTATION_PATHS_TAG = "annotation-paths";
private static final String JAVADOC_PATHS_TAG = "javadoc-paths";
private static final String MODULE_LANGUAGE_LEVEL_ATTRIBUTE = "LANGUAGE_LEVEL";
public static final String ROOT_TAG = "root";
private static final String RELATIVE_OUTPUT_PATH_ATTRIBUTE = "relativeOutputPath";
private static final String IS_GENERATED_ATTRIBUTE = "generated";
public static final JavaSourceRootPropertiesSerializer JAVA_SOURCE_ROOT_PROPERTIES_SERIALIZER =
new JavaSourceRootPropertiesSerializer(JavaSourceRootType.SOURCE, JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID);
@Override
public void loadRootModel(@NotNull JpsModule module, @NotNull Element rootModel) {
loadExplodedDirectoryExtension(module, rootModel);
loadJavaModuleExtension(module, rootModel);
}
@Override
public void saveRootModel(@NotNull JpsModule module, @NotNull Element rootModel) {
saveExplodedDirectoryExtension(module, rootModel);
saveJavaModuleExtension(module, rootModel);
}
@Override
public void loadModuleOptions(@NotNull JpsModule module, @NotNull Element rootElement) {
Element testModuleProperties = JDomSerializationUtil.findComponent(rootElement, "TestModuleProperties");
if (testModuleProperties != null) {
String productionModuleName = testModuleProperties.getAttributeValue("production-module");
if (productionModuleName != null) {
getService().setTestModuleProperties(module, JpsElementFactory.getInstance().createModuleReference(productionModuleName));
}
}
}
@NotNull
@Override
public List<? extends JpsProjectExtensionSerializer> getProjectExtensionSerializers() {
return Arrays.asList(new JavaProjectExtensionSerializer(),
new JpsJavaCompilerConfigurationSerializer(),
new JpsJavaCompilerNotNullableSerializer(),
new JpsCompilerValidationExcludeSerializer(),
new JpsJavaCompilerWorkspaceConfigurationSerializer(),
new JpsJavaCompilerOptionsSerializer("JavacSettings", "Javac"),
new JpsEclipseCompilerOptionsSerializer("EclipseCompilerSettings", "Eclipse"),
new RmicCompilerOptionsSerializer("RmicSettings", "Rmic"));
}
@NotNull
@Override
public List<? extends JpsModuleSourceRootPropertiesSerializer<?>> getModuleSourceRootPropertiesSerializers() {
return Arrays.asList(JAVA_SOURCE_ROOT_PROPERTIES_SERIALIZER,
new JavaSourceRootPropertiesSerializer(JavaSourceRootType.TEST_SOURCE, JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID),
new JavaResourceRootPropertiesSerializer(JavaResourceRootType.RESOURCE, "java-resource"),
new JavaResourceRootPropertiesSerializer(JavaResourceRootType.TEST_RESOURCE, "java-test-resource"));
}
@Override
public void loadModuleDependencyProperties(JpsDependencyElement dependency, Element entry) {
boolean exported = entry.getAttributeValue(EXPORTED_ATTRIBUTE) != null;
String scopeName = entry.getAttributeValue(SCOPE_ATTRIBUTE);
JpsJavaDependencyScope scope;
try {
scope = scopeName != null ? JpsJavaDependencyScope.valueOf(scopeName) : JpsJavaDependencyScope.COMPILE;
}
catch (IllegalArgumentException e) {
scope = JpsJavaDependencyScope.COMPILE;
}
final JpsJavaDependencyExtension extension = getService().getOrCreateDependencyExtension(dependency);
extension.setExported(exported);
extension.setScope(scope);
}
@Override
public void saveModuleDependencyProperties(JpsDependencyElement dependency, Element orderEntry) {
JpsJavaDependencyExtension extension = getService().getDependencyExtension(dependency);
if (extension != null) {
if (extension.isExported()) {
orderEntry.setAttribute(EXPORTED_ATTRIBUTE, "");
}
JpsJavaDependencyScope scope = extension.getScope();
if (scope != JpsJavaDependencyScope.COMPILE) {
orderEntry.setAttribute(SCOPE_ATTRIBUTE, scope.name());
}
}
}
@Override
public List<JpsLibraryRootTypeSerializer> getLibraryRootTypeSerializers() {
return Arrays.asList(new JpsLibraryRootTypeSerializer("JAVADOC", JpsOrderRootType.DOCUMENTATION, true),
new JpsLibraryRootTypeSerializer("ANNOTATIONS", JpsAnnotationRootType.INSTANCE, false),
new JpsLibraryRootTypeSerializer("NATIVE", JpsNativeLibraryRootType.INSTANCE, false));
}
@NotNull
@Override
public List<JpsLibraryRootTypeSerializer> getSdkRootTypeSerializers() {
return Arrays.asList(new JpsLibraryRootTypeSerializer("javadocPath", JpsOrderRootType.DOCUMENTATION, true),
new JpsLibraryRootTypeSerializer("annotationsPath", JpsAnnotationRootType.INSTANCE, true));
}
@NotNull
@Override
public List<? extends JpsPackagingElementSerializer<?>> getPackagingElementSerializers() {
return Arrays.asList(new JpsModuleOutputPackagingElementSerializer(), new JpsTestModuleOutputPackagingElementSerializer());
}
private static void loadExplodedDirectoryExtension(JpsModule module, Element rootModelComponent) {
final Element exploded = rootModelComponent.getChild(EXPLODED_TAG);
if (exploded != null) {
final ExplodedDirectoryModuleExtension extension = getService().getOrCreateExplodedDirectoryExtension(module);
extension.setExcludeExploded(rootModelComponent.getChild(EXCLUDE_EXPLODED_TAG) != null);
extension.setExplodedUrl(exploded.getAttributeValue(URL_ATTRIBUTE));
}
}
private static void saveExplodedDirectoryExtension(JpsModule module, Element rootModelElement) {
ExplodedDirectoryModuleExtension extension = getService().getExplodedDirectoryExtension(module);
if (extension != null) {
if (extension.isExcludeExploded()) {
rootModelElement.addContent(0, new Element(EXCLUDE_EXPLODED_TAG));
}
rootModelElement.addContent(0, new Element(EXPLODED_TAG).setAttribute(URL_ATTRIBUTE, extension.getExplodedUrl()));
}
}
private static void loadJavaModuleExtension(JpsModule module, Element rootModelComponent) {
final JpsJavaModuleExtension extension = getService().getOrCreateModuleExtension(module);
final Element outputTag = rootModelComponent.getChild(OUTPUT_TAG);
String outputUrl = outputTag != null ? outputTag.getAttributeValue(URL_ATTRIBUTE) : null;
extension.setOutputUrl(outputUrl);
final Element testOutputTag = rootModelComponent.getChild(TEST_OUTPUT_TAG);
String testOutputUrl = testOutputTag != null ? testOutputTag.getAttributeValue(URL_ATTRIBUTE) : null;
extension.setTestOutputUrl(StringUtil.isEmpty(testOutputUrl) ? outputUrl : testOutputUrl);
extension.setInheritOutput(Boolean.parseBoolean(rootModelComponent.getAttributeValue(INHERIT_COMPILER_OUTPUT_ATTRIBUTE)));
extension.setExcludeOutput(rootModelComponent.getChild(EXCLUDE_OUTPUT_TAG) != null);
final String languageLevel = rootModelComponent.getAttributeValue(MODULE_LANGUAGE_LEVEL_ATTRIBUTE);
if (languageLevel != null) {
extension.setLanguageLevel(LanguageLevel.valueOf(languageLevel));
}
loadAdditionalRoots(rootModelComponent, ANNOTATION_PATHS_TAG, extension.getAnnotationRoots());
loadAdditionalRoots(rootModelComponent, JAVADOC_PATHS_TAG, extension.getJavadocRoots());
}
private static void saveJavaModuleExtension(JpsModule module, Element rootModelComponent) {
JpsJavaModuleExtension extension = getService().getModuleExtension(module);
if (extension == null) return;
if (extension.isExcludeOutput()) {
rootModelComponent.addContent(0, new Element(EXCLUDE_OUTPUT_TAG));
}
String testOutputUrl = extension.getTestOutputUrl();
if (testOutputUrl != null) {
rootModelComponent.addContent(0, new Element(TEST_OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, testOutputUrl));
}
String outputUrl = extension.getOutputUrl();
if (outputUrl != null) {
rootModelComponent.addContent(0, new Element(OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, outputUrl));
}
LanguageLevel languageLevel = extension.getLanguageLevel();
if (languageLevel != null) {
rootModelComponent.setAttribute(MODULE_LANGUAGE_LEVEL_ATTRIBUTE, languageLevel.name());
}
if (extension.isInheritOutput()) {
rootModelComponent.setAttribute(INHERIT_COMPILER_OUTPUT_ATTRIBUTE, "true");
}
saveAdditionalRoots(rootModelComponent, JAVADOC_PATHS_TAG, extension.getJavadocRoots());
saveAdditionalRoots(rootModelComponent, ANNOTATION_PATHS_TAG, extension.getAnnotationRoots());
}
private static void loadAdditionalRoots(Element rootModelComponent, final String rootsTagName, final JpsUrlList result) {
final Element roots = rootModelComponent.getChild(rootsTagName);
for (Element root : JDOMUtil.getChildren(roots, ROOT_TAG)) {
result.addUrl(root.getAttributeValue(URL_ATTRIBUTE));
}
}
private static void saveAdditionalRoots(Element rootModelComponent, final String rootsTagName, final JpsUrlList list) {
List<String> urls = list.getUrls();
if (!urls.isEmpty()) {
Element roots = new Element(rootsTagName);
for (String url : urls) {
roots.addContent(new Element(ROOT_TAG).setAttribute(URL_ATTRIBUTE, url));
}
rootModelComponent.addContent(roots);
}
}
private static JpsJavaExtensionService getService() {
return JpsJavaExtensionService.getInstance();
}
private static class JpsModuleOutputPackagingElementSerializer
extends JpsPackagingElementSerializer<JpsProductionModuleOutputPackagingElement> {
private JpsModuleOutputPackagingElementSerializer() {
super("module-output", JpsProductionModuleOutputPackagingElement.class);
}
@Override
public JpsProductionModuleOutputPackagingElement load(Element element) {
JpsModuleReference reference = JpsElementFactory.getInstance().createModuleReference(element.getAttributeValue("name"));
return getService().createProductionModuleOutput(reference);
}
@Override
public void save(JpsProductionModuleOutputPackagingElement element, Element tag) {
tag.setAttribute("name", element.getModuleReference().getModuleName());
}
}
private static class JpsTestModuleOutputPackagingElementSerializer extends JpsPackagingElementSerializer<JpsTestModuleOutputPackagingElement> {
private JpsTestModuleOutputPackagingElementSerializer() {
super("module-test-output", JpsTestModuleOutputPackagingElement.class);
}
@Override
public JpsTestModuleOutputPackagingElement load(Element element) {
JpsModuleReference reference = JpsElementFactory.getInstance().createModuleReference(element.getAttributeValue("name"));
return getService().createTestModuleOutput(reference);
}
@Override
public void save(JpsTestModuleOutputPackagingElement element, Element tag) {
tag.setAttribute("name", element.getModuleReference().getModuleName());
}
}
private static class JavaProjectExtensionSerializer extends JpsProjectExtensionSerializer {
public JavaProjectExtensionSerializer() {
super(null, "ProjectRootManager");
}
@Override
public void loadExtension(@NotNull JpsProject project, @NotNull Element componentTag) {
JpsJavaProjectExtension extension = getService().getOrCreateProjectExtension(project);
final Element output = componentTag.getChild(OUTPUT_TAG);
if (output != null) {
String url = output.getAttributeValue(URL_ATTRIBUTE);
if (url != null) {
extension.setOutputUrl(url);
}
}
String languageLevel = componentTag.getAttributeValue(LANGUAGE_LEVEL_ATTRIBUTE);
if (languageLevel != null) {
extension.setLanguageLevel(LanguageLevel.valueOf(languageLevel));
}
}
@Override
public void saveExtension(@NotNull JpsProject project, @NotNull Element componentTag) {
JpsJavaProjectExtension extension = getService().getProjectExtension(project);
if (extension == null) return;
String outputUrl = extension.getOutputUrl();
if (outputUrl != null) {
componentTag.addContent(new Element(OUTPUT_TAG).setAttribute(URL_ATTRIBUTE, outputUrl));
}
LanguageLevel level = extension.getLanguageLevel();
componentTag.setAttribute(LANGUAGE_LEVEL_ATTRIBUTE, level.name());
componentTag.setAttribute("assert-keyword", Boolean.toString(level.compareTo(LanguageLevel.JDK_1_4) >= 0));
componentTag.setAttribute("jdk-15", Boolean.toString(level.compareTo(LanguageLevel.JDK_1_5) >= 0));
}
}
private static class JavaSourceRootPropertiesSerializer extends JpsModuleSourceRootPropertiesSerializer<JavaSourceRootProperties> {
private JavaSourceRootPropertiesSerializer(JpsModuleSourceRootType<JavaSourceRootProperties> type, String typeId) {
super(type, typeId);
}
@Override
public JavaSourceRootProperties loadProperties(@NotNull Element sourceRootTag) {
String packagePrefix = StringUtil.notNullize(sourceRootTag.getAttributeValue(JpsModuleRootModelSerializer.PACKAGE_PREFIX_ATTRIBUTE));
boolean isGenerated = Boolean.parseBoolean(sourceRootTag.getAttributeValue(IS_GENERATED_ATTRIBUTE));
return getService().createSourceRootProperties(packagePrefix, isGenerated);
}
@Override
public void saveProperties(@NotNull JavaSourceRootProperties properties, @NotNull Element sourceRootTag) {
String isTestSource = Boolean.toString(getType().equals(JavaSourceRootType.TEST_SOURCE));
sourceRootTag.setAttribute(JpsModuleRootModelSerializer.IS_TEST_SOURCE_ATTRIBUTE, isTestSource);
String packagePrefix = properties.getPackagePrefix();
if (!packagePrefix.isEmpty()) {
sourceRootTag.setAttribute(JpsModuleRootModelSerializer.PACKAGE_PREFIX_ATTRIBUTE, packagePrefix);
}
if (properties.isForGeneratedSources()) {
sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, Boolean.TRUE.toString());
}
}
}
private static class JavaResourceRootPropertiesSerializer extends JpsModuleSourceRootPropertiesSerializer<JavaResourceRootProperties> {
private JavaResourceRootPropertiesSerializer(JpsModuleSourceRootType<JavaResourceRootProperties> type, String typeId) {
super(type, typeId);
}
@Override
public JavaResourceRootProperties loadProperties(@NotNull Element sourceRootTag) {
String relativeOutputPath = StringUtil.notNullize(sourceRootTag.getAttributeValue(RELATIVE_OUTPUT_PATH_ATTRIBUTE));
boolean isGenerated = Boolean.parseBoolean(sourceRootTag.getAttributeValue(IS_GENERATED_ATTRIBUTE));
return getService().createResourceRootProperties(relativeOutputPath, isGenerated);
}
@Override
public void saveProperties(@NotNull JavaResourceRootProperties properties, @NotNull Element sourceRootTag) {
String relativeOutputPath = properties.getRelativeOutputPath();
if (!relativeOutputPath.isEmpty()) {
sourceRootTag.setAttribute(RELATIVE_OUTPUT_PATH_ATTRIBUTE, relativeOutputPath);
}
if (properties.isForGeneratedSources()) {
sourceRootTag.setAttribute(IS_GENERATED_ATTRIBUTE, Boolean.TRUE.toString());
}
}
}
}
| apache-2.0 |
jdcasey/pnc | rest/src/test/java/org/jboss/pnc/rest/endpoint/BpmEndpointTest.java | 8900 | /**
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.pnc.rest.endpoint;
import org.jboss.pnc.auth.AuthenticationProvider;
import org.jboss.pnc.auth.AuthenticationProviderFactory;
import org.jboss.pnc.auth.NoAuthLoggedInUser;
import org.jboss.pnc.bpm.BpmManager;
import org.jboss.pnc.common.Configuration;
import org.jboss.pnc.common.json.ConfigurationParseException;
import org.jboss.pnc.common.json.moduleconfig.ScmModuleConfig;
import org.jboss.pnc.datastore.limits.DefaultPageInfoProducer;
import org.jboss.pnc.datastore.limits.DefaultSortInfoProducer;
import org.jboss.pnc.datastore.predicates.SpringDataRSQLPredicateProducer;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.RepositoryConfiguration;
import org.jboss.pnc.rest.provider.RepositoryConfigurationProvider;
import org.jboss.pnc.rest.restmodel.bpm.RepositoryCreationUrlAutoRest;
import org.jboss.pnc.rest.restmodel.mock.RepositoryCreationUrlAutoRestMockBuilder;
import org.jboss.pnc.rest.validation.exceptions.InvalidEntityException;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationAuditedRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductVersionRepository;
import org.jboss.pnc.spi.datastore.repositories.RepositoryConfigurationRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import javax.ws.rs.core.Response;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
/**
* Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
* Date: 12/7/16
* Time: 4:03 PM
*/
public class BpmEndpointTest {
private static final String INTERNAL_SCM_URL_WO_NAME = "ssh://git@github.com:22";
private static final String VALID_INTERNAL_SCM_URL = INTERNAL_SCM_URL_WO_NAME + "/rock-a-teens/woo-hoo.git";
private static final String EXISTING_INTERNAL_SCM_URL = INTERNAL_SCM_URL_WO_NAME + "/i-do/exist.git";
private static final String EXISTING_EXTERNAL_SCM_URL = "https://github.com/i-do/exist.git";
@Mock
private AuthenticationProviderFactory authProviderFactory;
@Mock
private AuthenticationProvider authProvider;
@Mock
private BuildConfigurationRepository configurationRepository;
@Mock
private BuildConfigurationAuditedRepository configurationAuditedRepository;
@Mock
private ProductVersionRepository versionRepository;
@Mock
private RepositoryConfigurationRepository repositoryConfigurationRepository;
@Mock
private BuildConfigurationRepository buildConfigurationRepository;
@Mock
private ScmModuleConfig scmModuleConfig;
@Mock
private BpmManager bpmManager;
@Mock
Configuration pncConfiguration;
private BpmEndpoint bpmEndpoint;
@Before
public void setUp() throws ConfigurationParseException, InvalidEntityException {
MockitoAnnotations.initMocks(this);
when(scmModuleConfig.getInternalScmAuthority()).thenReturn("git@github.com:22");
RepositoryConfiguration existingInternalRepositoryConfiguration = RepositoryConfiguration.Builder.newBuilder()
.internalUrl(EXISTING_INTERNAL_SCM_URL)
.externalUrl("")
.preBuildSyncEnabled(true)
.build();
RepositoryConfiguration existingExternalRepositoryConfiguration = RepositoryConfiguration.Builder.newBuilder()
.internalUrl(EXISTING_EXTERNAL_SCM_URL)
.externalUrl("")
.preBuildSyncEnabled(true)
.build();
when(authProviderFactory.getProvider()).thenReturn(authProvider);
when(authProvider.getLoggedInUser(any())).thenReturn(new NoAuthLoggedInUser());
when(pncConfiguration.getModuleConfig(any())).thenReturn(scmModuleConfig);
RepositoryConfigurationProvider repositoryConfigurationProvider = new RepositoryConfigurationProvider(
repositoryConfigurationRepository,
new SpringDataRSQLPredicateProducer(),
new DefaultSortInfoProducer(),
new DefaultPageInfoProducer(),
pncConfiguration
);
when(repositoryConfigurationRepository.queryByInternalScm(Matchers.eq(EXISTING_INTERNAL_SCM_URL)))
.thenReturn(existingInternalRepositoryConfiguration);
when(repositoryConfigurationRepository.queryByExternalScm(Matchers.eq(EXISTING_EXTERNAL_SCM_URL)))
.thenReturn(existingExternalRepositoryConfiguration);
BuildConfiguration buildConfiguartion = BuildConfiguration.Builder.newBuilder()
.id(10)
.build();
when(buildConfigurationRepository.save(any())).thenReturn(buildConfiguartion);
when(pncConfiguration.getModuleConfig(any())).thenReturn(scmModuleConfig);
bpmEndpoint = new BpmEndpoint(
bpmManager,
null,
authProviderFactory,
null,
repositoryConfigurationRepository,
repositoryConfigurationProvider,
buildConfigurationRepository,
pncConfiguration);
}
@Test
public void shouldNotStartRCCreateTaskWithInternalURLWORepoName() throws Exception {
RepositoryCreationUrlAutoRest configuration = configuration("shouldNotStartRCCreateTaskWithInternalURLWORepoName", INTERNAL_SCM_URL_WO_NAME);
assertThrows(() -> bpmEndpoint.startRCreationTaskWithSingleUrl(configuration, null), InvalidEntityException.class);
}
@Test
public void shouldNotStartRCCreateTaskWithInvalidInternalURL() throws Exception {
RepositoryCreationUrlAutoRest configuration = configuration("shouldNotStartRCCreateTaskWithInvalidInternalURL", INTERNAL_SCM_URL_WO_NAME);
assertThrows(() -> bpmEndpoint.startRCreationTaskWithSingleUrl(configuration, null), InvalidEntityException.class);
}
@Test
public void shouldStartRCCreateTaskWithValidInternalURL() throws Exception {
RepositoryCreationUrlAutoRest configuration = configuration("shouldStartRCCreateTaskWithValidInternalURL", VALID_INTERNAL_SCM_URL);
Response response = bpmEndpoint.startRCreationTaskWithSingleUrl(configuration, null);
assertThat(response.getStatus()).isEqualTo(200);
}
@Test
public void shouldNotStartRCCreateTaskWithExistingInternalURL() throws Exception {
RepositoryCreationUrlAutoRest configuration = configuration("shouldStartRCCreateTaskWithExistingInternalURL", EXISTING_INTERNAL_SCM_URL);
Response response = bpmEndpoint.startRCreationTaskWithSingleUrl(configuration, null);
assertThat(response.getStatus()).isEqualTo(Response.Status.CONFLICT.getStatusCode());
}
@Test
public void shouldNotStartRCCreateTaskWithExistingExternalURL() throws Exception {
RepositoryCreationUrlAutoRest configuration = RepositoryCreationUrlAutoRestMockBuilder.mock(
"shouldStartRCCreateTaskWithExistingExternalURL",
"mvn clean deploy",
EXISTING_EXTERNAL_SCM_URL);
Response response = bpmEndpoint.startRCreationTaskWithSingleUrl(configuration, null);
assertThat(response.getStatus()).isEqualTo(Response.Status.CONFLICT.getStatusCode());
}
private RepositoryCreationUrlAutoRest configuration(String name, String internalUrl) {
return RepositoryCreationUrlAutoRestMockBuilder.mock(name, "mvn clean deploy", internalUrl);
}
private <E extends Exception> void assertThrows(ThrowingRunnable runnable, Class<E> exceptionClass) {
try {
runnable.run();
} catch (Exception e) {
if (exceptionClass.isInstance(e)) {
return;
}
fail("Unexpected exception thrown. Expected: " + exceptionClass + ", actual: " + e);
}
fail("Expected exception not thrown. Expected: " + exceptionClass + ".");
}
interface ThrowingRunnable {
void run() throws Exception;
}
}
| apache-2.0 |
BrotherlyBoiler/Sunshine | app/src/main/java/com/example/android/sunshine/app/data/WeatherProvider.java | 14211 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.app.data;
import android.annotation.TargetApi;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
public class WeatherProvider extends ContentProvider {
// The URI Matcher used by this content provider.
private static final UriMatcher sUriMatcher = buildUriMatcher();
private WeatherDbHelper mOpenHelper;
static final int WEATHER = 100;
static final int WEATHER_WITH_LOCATION = 101;
static final int WEATHER_WITH_LOCATION_AND_DATE = 102;
static final int LOCATION = 300;
private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder;
static {
sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder();
//This is an inner join which looks like
//weather INNER JOIN location ON weather.location_id = location._id
sWeatherByLocationSettingQueryBuilder.setTables(
WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " +
WeatherContract.LocationEntry.TABLE_NAME +
" ON " + WeatherContract.WeatherEntry.TABLE_NAME +
"." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY +
" = " + WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry._ID);
}
//location.location_setting = ?
private static final String sLocationSettingSelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? ";
//location.location_setting = ? AND date >= ?
private static final String sLocationSettingWithStartDateSelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? ";
//location.location_setting = ? AND date = ?
private static final String sLocationSettingAndDaySelection =
WeatherContract.LocationEntry.TABLE_NAME +
"." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " +
WeatherContract.WeatherEntry.COLUMN_DATE + " = ? ";
private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri);
String[] selectionArgs;
String selection;
if (startDate == 0) {
selection = sLocationSettingSelection;
selectionArgs = new String[]{locationSetting};
} else {
selectionArgs = new String[]{locationSetting, Long.toString(startDate)};
selection = sLocationSettingWithStartDateSelection;
}
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
}
private Cursor getWeatherByLocationSettingAndDate(
Uri uri, String[] projection, String sortOrder) {
String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri);
long date = WeatherContract.WeatherEntry.getDateFromUri(uri);
return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(),
projection,
sLocationSettingAndDaySelection,
new String[]{locationSetting, Long.toString(date)},
null,
null,
sortOrder
);
}
/*
Students: Here is where you need to create the UriMatcher. This UriMatcher will
match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE,
and LOCATION integer constants defined above. You can test this by uncommenting the
testUriMatcher test within TestUriMatcher.
*/
static UriMatcher buildUriMatcher() {
// I know what you're thinking. Why create a UriMatcher when you can use regular
// expressions instead? Because you're not crazy, that's why.
// All paths added to the UriMatcher have a corresponding code to return when a match is
// found. The code passed into the constructor represents the code to return for the root
// URI. It's common to use NO_MATCH as the code for this case.
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = WeatherContract.CONTENT_AUTHORITY;
// For each type of URI you want to add, create a corresponding code.
matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION);
matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/#", WEATHER_WITH_LOCATION_AND_DATE);
matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION);
return matcher;
}
/*
Students: We've coded this for you. We just create a new WeatherDbHelper for later use
here.
*/
@Override
public boolean onCreate() {
mOpenHelper = new WeatherDbHelper(getContext());
return true;
}
/*
Students: Here's where you'll code the getType function that uses the UriMatcher. You can
test this by uncommenting testGetType in TestProvider.
*/
@Override
public String getType(Uri uri) {
// Use the Uri Matcher to determine what kind of URI this is.
final int match = sUriMatcher.match(uri);
switch (match) {
// Student: Uncomment and fill out these two cases
case WEATHER_WITH_LOCATION_AND_DATE:
return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE;
case WEATHER_WITH_LOCATION:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case WEATHER:
return WeatherContract.WeatherEntry.CONTENT_TYPE;
case LOCATION:
return WeatherContract.LocationEntry.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// Here's the switch statement that, given a URI, will determine what kind of request it is,
// and query the database accordingly.
Cursor retCursor;
switch (sUriMatcher.match(uri)) {
// "weather/*/*"
case WEATHER_WITH_LOCATION_AND_DATE: {
retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
break;
}
// "weather/*"
case WEATHER_WITH_LOCATION: {
retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
break;
}
// "weather"
case WEATHER: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.WeatherEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
// "location"
case LOCATION: {
retCursor = mOpenHelper.getReadableDatabase().query(
WeatherContract.LocationEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder
);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
retCursor.setNotificationUri(getContext().getContentResolver(), uri);
return retCursor;
}
/*
Student: Add the ability to insert Locations to the implementation of this function.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
Uri returnUri;
switch (match) {
case WEATHER: {
normalizeDate(values);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values);
if (_id > 0)
returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
case LOCATION: {
long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values);
if (_id > 0)
returnUri = WeatherContract.LocationEntry.buildLocationUri(_id);
else
throw new android.database.SQLException("Failed to insert row into " + uri);
break;
}
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsDeleted;
// this makes delete all rows return the number of rows deleted
if (null == selection) selection = "1";
switch (match) {
case WEATHER:
rowsDeleted = db.delete(
WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs);
break;
case LOCATION:
rowsDeleted = db.delete(
WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
// Because a null deletes all rows
if (rowsDeleted != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsDeleted;
}
private void normalizeDate(ContentValues values) {
// normalize the date value
if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) {
long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue));
}
}
@Override
public int update(
Uri uri, ContentValues values, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case WEATHER:
normalizeDate(values);
rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
case LOCATION:
rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection,
selectionArgs);
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
if (rowsUpdated != 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsUpdated;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case WEATHER:
db.beginTransaction();
int returnCount = 0;
try {
for (ContentValues value : values) {
normalizeDate(value);
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
returnCount++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
getContext().getContentResolver().notifyChange(uri, null);
return returnCount;
default:
return super.bulkInsert(uri, values);
}
}
// You do not need to call this method. This is a method specifically to assist the testing
// framework in running smoothly. You can read more at:
// http://developer.android.com/reference/android/content/ContentProvider.html#shutdown()
@Override
@TargetApi(11)
public void shutdown() {
mOpenHelper.close();
super.shutdown();
}
} | apache-2.0 |
RuthRainbow/anemone | src/main/java/group7/anemone/Genetics/Genome.java | 1704 | package group7.anemone.Genetics;
import group7.anemone.Genetics.GenomeEdge;
import java.io.Serializable;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Genome class to hold the nodes and edges needed to create a network.
*/
public abstract class Genome<node extends GenomeNode> implements Serializable {
private static final long serialVersionUID = -9023930914349095877L;
// Genes represent edges
protected final ArrayList<GenomeEdge<node>> genome;
protected final List<node> nodes;
public Genome(List<GenomeEdge<node>> genome, Collection<node> nodes) {
this.genome = new ArrayList<GenomeEdge<node>>(genome);
this.nodes = Collections.synchronizedList(new ArrayList<node>(nodes));
}
@Override
public String toString() {
return "Genome: " + this.genome;
}
public int getLength() {
return this.genome.size();
}
public node getXthIn(int x) {
return this.genome.get(x).getIn();
}
public node getXthOut(int x) {
return this.genome.get(x).getOut();
}
public double getXthWeight(int x) {
return this.genome.get(x).getWeight();
}
public int getXthDelay(int x) {
return this.genome.get(x).getDelay();
}
public ArrayList<GenomeEdge<node>> getGene() {
return this.genome;
}
public int getNodesSize() {
return this.nodes.size();
}
public synchronized ArrayList<node> copyNodes() {
ArrayList<node> toReturn = new ArrayList<node>();
for (node n : this.nodes) {
toReturn.add(n);
}
return toReturn;
}
public int getXthHistoricalMarker(int x) {
return this.genome.get(x).getHistoricalMarker();
}
public GenomeEdge<node> getXthGene(int x) {
return this.genome.get(x);
}
} | apache-2.0 |
lessthanoptimal/BoofCV | main/boofcv-recognition/src/main/java/boofcv/alg/template/TemplateSumAbsoluteDifference.java | 4094 | /*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.template;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.GrayU8;
import boofcv.struct.image.ImageBase;
import java.util.Objects;
/**
* <p>
* Scores the difference between the template and the image using sum of absolute difference (SAD) error.
* The error is multiplied by -1 to ensure that the best fits are peaks and not minimums.
* </p>
*
* <p> error = -1*Sum<sub>(o,u)</sub> |I(x,y) - T(x-o,y-u)| </p>
*
* @author Peter Abeles
*/
@SuppressWarnings("NullAway.Init")
public abstract class TemplateSumAbsoluteDifference<T extends ImageBase<T>>
implements TemplateIntensityImage.EvaluatorMethod<T> {
TemplateIntensityImage<T> o;
@Override
public void initialize( TemplateIntensityImage<T> owner ) {
this.o = owner;
}
// IF MORE IMAGE TYPES ARE ADDED CREATE A GENERATOR FOR THIS CLASS
public static class F32 extends TemplateSumAbsoluteDifference<GrayF32> {
@Override
public float evaluate( int tl_x, int tl_y ) {
float total = 0;
for (int y = 0; y < o.template.height; y++) {
int imageIndex = o.image.startIndex + (tl_y + y)*o.image.stride + tl_x;
int templateIndex = o.template.startIndex + y*o.template.stride;
float rowTotal = 0.0f;
for (int x = 0; x < o.template.width; x++) {
rowTotal += Math.abs(o.image.data[imageIndex++] - o.template.data[templateIndex++]);
}
total += rowTotal;
}
return total;
}
@Override
public float evaluateMask( int tl_x, int tl_y ) {
Objects.requireNonNull(o.mask);
float total = 0;
for (int y = 0; y < o.template.height; y++) {
int imageIndex = o.image.startIndex + (tl_y + y)*o.image.stride + tl_x;
int templateIndex = o.template.startIndex + y*o.template.stride;
int maskIndex = o.mask.startIndex + y*o.mask.stride;
float rowTotal = 0.0f;
for (int x = 0; x < o.template.width; x++) {
rowTotal += o.mask.data[maskIndex++]*Math.abs(o.image.data[imageIndex++] - o.template.data[templateIndex++]);
}
total += rowTotal;
}
return total;
}
}
public static class U8 extends TemplateSumAbsoluteDifference<GrayU8> {
@Override
public float evaluate( int tl_x, int tl_y ) {
float total = 0;
for (int y = 0; y < o.template.height; y++) {
int imageIndex = o.image.startIndex + (tl_y + y)*o.image.stride + tl_x;
int templateIndex = o.template.startIndex + y*o.template.stride;
int rowTotal = 0;
for (int x = 0; x < o.template.width; x++) {
rowTotal += Math.abs((o.image.data[imageIndex++] & 0xFF) - (o.template.data[templateIndex++] & 0xFF));
}
total += rowTotal;
}
return total;
}
@Override
public float evaluateMask( int tl_x, int tl_y ) {
Objects.requireNonNull(o.mask);
float total = 0;
for (int y = 0; y < o.template.height; y++) {
int imageIndex = o.image.startIndex + (tl_y + y)*o.image.stride + tl_x;
int templateIndex = o.template.startIndex + y*o.template.stride;
int maskIndex = o.mask.startIndex + y*o.mask.stride;
int rowTotal = 0;
for (int x = 0; x < o.template.width; x++) {
int m = o.mask.data[maskIndex++] & 0xFF;
rowTotal += m*Math.abs((o.image.data[imageIndex++] & 0xFF) - (o.template.data[templateIndex++] & 0xFF));
}
total += rowTotal;
}
return total;
}
}
@Override
public boolean isBorderProcessed() {
return false;
}
@Override
public boolean isMaximize() {
return false;
}
}
| apache-2.0 |
OpenVnmrJ/OpenVnmrJ | src/vnmrj/src/vnmr/admin/ui/WInvestigator.java | 3732 | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
package vnmr.admin.ui;
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import vnmr.util.*;
import vnmr.admin.util.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p> </p>
* not attributable
*
*/
public class WInvestigator extends ModalEntryDialog
{
public static String Investigator;
public WInvestigator(String strhelpfile)
{
super(vnmr.util.Util.getLabel("_admin_Investigator_List"),
vnmr.util.Util.getLabel("_admin_Investigator_Names:"),
strhelpfile);
// Fill Investigator for use below
String dir = FileUtil.vnmrDir(FileUtil.SYS_VNMR, "IMAGING");
Investigator = FileUtil.vnmrDir(dir, "CHOICEFILES") + File.separator + "pis";
}
public void setVisible(boolean bShow)
{
if (bShow)
{
inputText.setText("");
dolayout();
setLocationRelativeTo(getParent());
}
super.setVisible(bShow);
}
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals("ok"))
{
saveInvesti();
setVisible(false);
}
super.actionPerformed(e);
}
protected void dolayout()
{
String strPath = FileUtil.openPath(Investigator);
StringBuffer sbData = new StringBuffer();
if (strPath == null)
return;
BufferedReader reader = WFileUtil.openReadFile(strPath);
if (reader == null)
return;
String strLine;
try
{
while ((strLine = reader.readLine()) != null)
{
QuotedStringTokenizer strTok =
new QuotedStringTokenizer(strLine, " ");
if (strTok.hasMoreTokens()) {
String str = strTok.nextToken().trim();
// Put quotes in in case any items are mutiple words
sbData.append("\"" + str + "\"").append(" ");
}
}
reader.close();
inputText.setText(sbData.toString());
}
catch (Exception e)
{
//e.printStackTrace();
Messages.writeStackTrace(e);
}
}
public void saveInvesti()
{
String strValue = inputText.getText();
String strPath = FileUtil.openPath(Investigator);
if (strPath == null)
strPath = FileUtil.savePath(Investigator);
if (strPath == null)
{
Messages.logError("File " + Investigator + " not found, please check for write permission");
return;
}
try
{
StringBuffer sbData = new StringBuffer();
QuotedStringTokenizer strTok =
new QuotedStringTokenizer(strValue, ", \t\n");
while (strTok.hasMoreTokens())
{
String strUser = strTok.nextToken().trim();
sbData.append("\"").append(strUser).append("\"").append(" ");
sbData.append("\"").append(strUser).append("\"").append("\n");
}
BufferedWriter writer = WFileUtil.openWriteFile(strPath);
WFileUtil.writeAndClose(writer, sbData);
}
catch (Exception e)
{
//e.printStackTrace();
Messages.writeStackTrace(e);
}
}
}
| apache-2.0 |
chirino/hawtdb | hawtdb/src/test/java/org/fusesource/hawtdb/internal/page/ExtentTest.java | 2704 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.hawtdb.internal.page;
import static org.junit.Assert.assertEquals;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import org.fusesource.hawtdb.api.PageFile;
import org.fusesource.hawtdb.api.PageFileFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class ExtentTest {
private PageFileFactory pff;
private PageFile paged;
protected PageFileFactory createPageFileFactory() {
PageFileFactory rc = new PageFileFactory();
rc.setMappingSegementSize(rc.getPageSize()*3);
rc.setFile(new File("target/test-data/"+getClass().getName()+".db"));
return rc;
}
@Before
public void setUp() throws Exception {
pff = createPageFileFactory();
pff.getFile().delete();
pff.open();
paged = pff.getPageFile();
}
@After
public void tearDown() throws Exception {
pff.close();
}
protected void reload() throws IOException {
pff.close();
pff.open();
paged = pff.getPageFile();
}
@Test
public void testExtentStreams() throws IOException {
ExtentOutputStream eos = new ExtentOutputStream(paged);
DataOutputStream os = new DataOutputStream(eos);
for (int i = 0; i < 10000; i++) {
os.writeUTF("Test string:" + i);
}
os.close();
int page = eos.getPage();
assertEquals(0, page);
// Reload the page file.
reload();
ExtentInputStream eis = new ExtentInputStream(paged, page);
DataInputStream is = new DataInputStream(eis);
for (int i = 0; i < 10000; i++) {
assertEquals("Test string:" + i, is.readUTF());
}
assertEquals(-1, is.read());
is.close();
}
}
| apache-2.0 |
ralscha/extdirectspring-demo | src/main/java/ch/rasc/extdirectspring/demo/filter/SizeSerializer.java | 1170 | /**
* Copyright 2010-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ch.rasc.extdirectspring.demo.filter;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class SizeSerializer extends JsonSerializer<SizeEnum> {
@Override
public void serialize(SizeEnum value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeString(value.getLabel());
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/bc/businessobject/lookup/AccountSelectLookupableHelperServiceImpl.java | 2927 | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.bc.businessobject.lookup;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.kuali.kfs.module.bc.BCConstants;
import org.kuali.kfs.module.bc.BCPropertyConstants;
import org.kuali.kfs.module.bc.businessobject.BudgetConstructionAccountSelect;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.rice.kns.lookup.HtmlData;
import org.kuali.rice.kns.lookup.HtmlData.AnchorHtmlData;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.util.UrlFactory;
/**
* Lookupable helper service implementation for the account selection screens.
*/
public class AccountSelectLookupableHelperServiceImpl extends SelectLookupableHelperServiceImpl {
/**
* @see org.kuali.rice.kns.lookup.LookupableHelperService#getCustomActionUrls(org.kuali.rice.krad.bo.BusinessObject, java.util.List, java.util.List pkNames)
*/
@Override
public List<HtmlData> getCustomActionUrls(BusinessObject businessObject, List pkNames) {
BudgetConstructionAccountSelect accountSelect = (BudgetConstructionAccountSelect) businessObject;
Properties parameters = new Properties();
parameters.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, BCConstants.BC_DOCUMENT_METHOD);
parameters.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, accountSelect.getUniversityFiscalYear().toString());
parameters.put(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE, accountSelect.getChartOfAccountsCode());
parameters.put(KFSPropertyConstants.ACCOUNT_NUMBER, accountSelect.getAccountNumber());
parameters.put(KFSPropertyConstants.SUB_ACCOUNT_NUMBER, accountSelect.getSubAccountNumber());
parameters.put(BCConstants.PICK_LIST_MODE, "true");
parameters.put(BCPropertyConstants.MAIN_WINDOW, "false");
String href = UrlFactory.parameterizeUrl(BCConstants.BC_DOCUMENT_ACTION, parameters);
List<HtmlData> anchorHtmlDataList = new ArrayList<HtmlData>();
AnchorHtmlData anchorHtmlData = new AnchorHtmlData(href, BCConstants.BC_DOCUMENT_METHOD, "Load Document");
anchorHtmlData.setTarget(KFSConstants.NEW_WINDOW_URL_TARGET);
anchorHtmlDataList.add(anchorHtmlData);
return anchorHtmlDataList;
}
}
| apache-2.0 |
marc-ashman/500px | 500px-gallery/500px-App/src/main/java/com/ashman/fivehundredpx/api/auth/TwitterAuthProvider.java | 1001 | package com.ashman.fivehundredpx.api.auth;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
public class TwitterAuthProvider extends XAuthProvider {
private String twitterToken;
private String twitterSecret;
public TwitterAuthProvider(String twitterToken, String twitterSecret) {
super();
this.twitterToken = twitterToken;
this.twitterSecret = twitterSecret;
}
protected ArrayList<NameValuePair> buildParameters(OAuthParameters params) {
ArrayList<NameValuePair> tuples = new ArrayList<NameValuePair>();
tuples.add(new BasicNameValuePair(OAuthConstants.MODE, "twitter_auth"));
params.put(OAuthConstants.MODE, "twitter_auth");
tuples.add(new BasicNameValuePair(OAuthConstants.X_TOKEN, twitterToken));
params.put(OAuthConstants.X_TOKEN, twitterToken);
tuples.add(new BasicNameValuePair(OAuthConstants.X_SECRET, twitterSecret));
params.put(OAuthConstants.X_SECRET, twitterSecret);
return tuples;
}
}
| apache-2.0 |
delebash/orientdb-parent | core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorIs.java | 2407 | /*
* Copyright 2010-2012 Luca Garulli (l.garulli--at--orientechnologies.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orientechnologies.orient.core.sql.operator;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.OSQLHelper;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterCondition;
/**
* IS operator. Different by EQUALS since works also for null. Example "IS null"
*
* @author Luca Garulli
*
*/
public class OQueryOperatorIs extends OQueryOperatorEquality {
public OQueryOperatorIs() {
super("IS", 5, false);
}
@Override
protected boolean evaluateExpression(final OIdentifiable iRecord, final OSQLFilterCondition iCondition, final Object iLeft,
final Object iRight, OCommandContext iContext) {
if (OSQLHelper.NOT_NULL.equals(iRight))
return iLeft != null;
else if (OSQLHelper.NOT_NULL.equals(iLeft))
return iRight != null;
else if (OSQLHelper.DEFINED.equals(iLeft))
return evaluateDefined(iRecord, (String) iRight);
else if (OSQLHelper.DEFINED.equals(iRight))
return evaluateDefined(iRecord, (String) iLeft);
else
return iLeft == iRight;
}
protected boolean evaluateDefined(final OIdentifiable iRecord, final String iFieldName) {
if (iRecord instanceof ODocument) {
return ((ODocument) iRecord).containsField(iFieldName);
}
return false;
}
@Override
public OIndexReuseType getIndexReuseType(final Object iLeft, final Object iRight) {
return OIndexReuseType.NO_INDEX;
}
@Override
public ORID getBeginRidRange(Object iLeft, Object iRight) {
return null;
}
@Override
public ORID getEndRidRange(Object iLeft, Object iRight) {
return null;
}
}
| apache-2.0 |
abdallaadelessa/Android-Utils | library/src/main/java/com/abdallaadelessa/android/utils/Time.java | 3707 | package com.abdallaadelessa.android.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
class Time {
public static final String DEFAULT_DATE_FORMAT = "dd-MM-yyyy";
public static final String SHORT_DATE_FORMAT = "dd-MMM";
public static final String FULL_DATE_FORMAT = "dd-MM-yyyy hh:mm";
//---------------------> Time Units Conversion
public static int convertMilliSecondsToMonths(long milliSeconds) {
return (int) ((((((milliSeconds / 1000) / 60) / 60) / 24) / 30)) + 1;
}
public static long convertMilliSecondsToSeconds(long milliSeconds) {
long seconds = milliSeconds / 1000;
return seconds;
}
public static long convertSecondsToMilliSeconds(long seconds) {
long milli = seconds * 1000;
return milli;
}
//---------------------> Epoch
public static String convertEpochMilliSecondsToDefaultFormatedDate(long epochMilliSeconds, String format) {
Date date = new Date(epochMilliSeconds);
SimpleDateFormat sf = new SimpleDateFormat(format, Locale.ENGLISH);
String StringDate = sf.format(date);
return StringDate;
}
public static long convertStringDateToEpochMilliSeconds(String date, String format) throws ParseException {
long epochMilli = 0;
if(date != null) {
SimpleDateFormat sf = new SimpleDateFormat(format, Locale.ENGLISH);
Date dateObject = sf.parse(date);
epochMilli = dateObject.getTime();
}
return epochMilli;
}
//--------------------->
public static boolean isToday(String dateInDateFormat, String format) {
boolean isToday = false;
if(!Strings.isStringEmpty(dateInDateFormat)) {
String todayDate = convertEpochMilliSecondsToDefaultFormatedDate(System.currentTimeMillis(), format);
if(!Strings.isStringEmpty(todayDate) && todayDate.equals(dateInDateFormat)) {
isToday = true;
}
}
return isToday;
}
public static long getEndMillisOfTheGivenDayMilliseconds(long miliiseconds) {
Calendar c = Calendar.getInstance();
c.setTime(new Date(miliiseconds));
c.set(Calendar.HOUR_OF_DAY, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return c.getTime().getTime();
}
public static int getAge(long userBirthDateInMillis) {
int age = 0;
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTimeInMillis(userBirthDateInMillis);
if(birthDate.after(today)) {
throw new IllegalArgumentException("Can't be born in the future");
}
age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if((birthDate.get(Calendar.DAY_OF_YEAR) - today.get(Calendar.DAY_OF_YEAR) > 3) || (birthDate.get(Calendar.MONTH) > today.get(Calendar.MONTH))) {
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
}
else if((birthDate.get(Calendar.MONTH) == today.get(Calendar.MONTH)) && (birthDate.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age;
}
//--------------------->
}
| apache-2.0 |
wanggc/mongo-java-driver | src/main/com/mongodb/BSONBinaryWriter.java | 12577 | /*
* Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import org.bson.BSONException;
import org.bson.io.OutputBuffer;
import org.bson.types.BSONTimestamp;
import org.bson.types.Binary;
import org.bson.types.ObjectId;
import java.util.Stack;
import static org.bson.util.Assertions.*;
class BSONBinaryWriter extends BSONWriter {
private final BSONBinaryWriterSettings binaryWriterSettings;
private final OutputBuffer buffer;
private final Stack<Integer> maxDocumentSizeStack = new Stack<Integer>();
private Mark mark;
public BSONBinaryWriter(final OutputBuffer buffer) {
this(new BSONWriterSettings(), new BSONBinaryWriterSettings(), buffer);
}
public BSONBinaryWriter(final BSONWriterSettings settings, final BSONBinaryWriterSettings binaryWriterSettings,
final OutputBuffer buffer) {
super(settings);
this.binaryWriterSettings = binaryWriterSettings;
this.buffer = buffer;
maxDocumentSizeStack.push(binaryWriterSettings.getMaxDocumentSize());
}
@Override
public void close() {
super.close();
}
/**
* Gets the output buffer that is backing this instance.
*
* @return the buffer
*/
public OutputBuffer getBuffer() {
return buffer;
}
@Override
public void flush() {
}
@Override
protected Context getContext() {
return (Context) super.getContext();
}
@Override
public void writeBinaryData(final Binary binary) {
checkPreconditions("writeBinaryData", State.VALUE);
buffer.write(BSONType.BINARY.getValue());
writeCurrentName();
int totalLen = binary.length();
if (binary.getType() == BSONBinarySubType.OldBinary.getValue()) {
totalLen += 4;
}
buffer.writeInt(totalLen);
buffer.write(binary.getType());
if (binary.getType() == BSONBinarySubType.OldBinary.getValue()) {
buffer.writeInt(totalLen - 4);
}
buffer.write(binary.getData());
setState(getNextState());
}
@Override
public void writeBoolean(final boolean value) {
checkPreconditions("writeBoolean", State.VALUE);
buffer.write(BSONType.BOOLEAN.getValue());
writeCurrentName();
buffer.write(value ? 1 : 0);
setState(getNextState());
}
@Override
public void writeDateTime(final long value) {
checkPreconditions("writeDateTime", State.VALUE);
buffer.write(BSONType.DATE_TIME.getValue());
writeCurrentName();
buffer.writeLong(value);
setState(getNextState());
}
@Override
public void writeDouble(final double value) {
checkPreconditions("writeDouble", State.VALUE);
buffer.write(BSONType.DOUBLE.getValue());
writeCurrentName();
buffer.writeDouble(value);
setState(getNextState());
}
@Override
public void writeInt32(final int value) {
checkPreconditions("writeInt32", State.VALUE);
buffer.write(BSONType.INT32.getValue());
writeCurrentName();
buffer.writeInt(value);
setState(getNextState());
}
@Override
public void writeInt64(final long value) {
checkPreconditions("writeInt64", State.VALUE);
buffer.write(BSONType.INT64.getValue());
writeCurrentName();
buffer.writeLong(value);
setState(getNextState());
}
@Override
public void writeJavaScript(final String code) {
checkPreconditions("writeJavaScript", State.VALUE);
buffer.write(BSONType.JAVASCRIPT.getValue());
writeCurrentName();
buffer.writeString(code);
setState(getNextState());
}
@Override
public void writeJavaScriptWithScope(final String code) {
checkPreconditions("writeJavaScriptWithScope", State.VALUE);
buffer.write(BSONType.JAVASCRIPT_WITH_SCOPE.getValue());
writeCurrentName();
setContext(new Context(getContext(), BSONContextType.JAVASCRIPT_WITH_SCOPE, buffer.getPosition()));
buffer.writeInt(0);
buffer.writeString(code);
setState(State.SCOPE_DOCUMENT);
}
@Override
public void writeMaxKey() {
checkPreconditions("writeMaxKey", State.VALUE);
buffer.write(BSONType.MAX_KEY.getValue());
writeCurrentName();
setState(getNextState());
}
@Override
public void writeMinKey() {
checkPreconditions("writeMinKey", State.VALUE);
buffer.write(BSONType.MIN_KEY.getValue());
writeCurrentName();
setState(getNextState());
}
@Override
public void writeNull() {
checkPreconditions("writeNull", State.VALUE);
buffer.write(BSONType.NULL.getValue());
writeCurrentName();
setState(getNextState());
}
@Override
public void writeObjectId(final ObjectId objectId) {
checkPreconditions("writeObjectId", State.VALUE);
buffer.write(BSONType.OBJECT_ID.getValue());
writeCurrentName();
buffer.write(objectId.toByteArray());
setState(getNextState());
}
@Override
public void writeString(final String value) {
checkPreconditions("writeString", State.VALUE);
buffer.write(BSONType.STRING.getValue());
writeCurrentName();
buffer.writeString(value);
setState(getNextState());
}
@Override
public void writeSymbol(final String value) {
checkPreconditions("writeSymbol", State.VALUE);
buffer.write(BSONType.SYMBOL.getValue());
writeCurrentName();
buffer.writeString(value);
setState(getNextState());
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void writeTimestamp(final BSONTimestamp value) {
checkPreconditions("writeTimestamp", State.VALUE);
buffer.write(BSONType.TIMESTAMP.getValue());
writeCurrentName();
buffer.writeInt(value.getInc());
buffer.writeInt(value.getTime());
setState(getNextState());
}
@Override
public void writeUndefined() {
checkPreconditions("writeUndefined", State.VALUE);
buffer.write(BSONType.UNDEFINED.getValue());
writeCurrentName();
setState(getNextState());
}
@Override
public void writeStartArray() {
checkPreconditions("writeStartArray", State.VALUE);
super.writeStartArray();
buffer.write(BSONType.ARRAY.getValue());
writeCurrentName();
setContext(new Context(getContext(), BSONContextType.ARRAY, buffer.getPosition()));
buffer.writeInt(0); // reserve space for size
setState(State.VALUE);
}
@Override
public void writeStartDocument() {
checkPreconditions("writeStartDocument", State.INITIAL, State.VALUE, State.SCOPE_DOCUMENT, State.DONE);
super.writeStartDocument();
if (getState() == State.VALUE) {
buffer.write(BSONType.DOCUMENT.getValue());
writeCurrentName();
}
setContext(new Context(getContext(), BSONContextType.DOCUMENT, buffer.getPosition()));
buffer.writeInt(0); // reserve space for size
setState(State.NAME);
}
@Override
public void writeEndArray() {
checkPreconditions("writeEndArray", State.VALUE);
if (getContext().getContextType() != BSONContextType.ARRAY) {
throwInvalidContextType("WriteEndArray", getContext().getContextType(), BSONContextType.ARRAY);
}
super.writeEndArray();
buffer.write(0);
backpatchSize(); // size of document
setContext(getContext().getParentContext());
setState(getNextState());
}
@Override
public void writeEndDocument() {
checkPreconditions("writeEndDocument", State.NAME);
BSONContextType contextType = getContext().getContextType();
if (contextType != BSONContextType.DOCUMENT && contextType != BSONContextType.SCOPE_DOCUMENT) {
throwInvalidContextType("WriteEndDocument", contextType, BSONContextType.DOCUMENT, BSONContextType.SCOPE_DOCUMENT);
}
super.writeEndDocument();
buffer.write(0);
backpatchSize(); // size of document
setContext(getContext().getParentContext());
if (getContext() == null) {
setState(State.DONE);
}
else {
if (getContext().getContextType() == BSONContextType.JAVASCRIPT_WITH_SCOPE) {
backpatchSize(); // size of the JavaScript with scope value
setContext(getContext().getParentContext());
}
setState(getNextState());
}
}
public void encodeDocument(final DBEncoder encoder, final DBObject dbObject) {
checkPreconditions("writeStartDocument", State.INITIAL, State.VALUE, State.SCOPE_DOCUMENT, State.DONE);
isTrue("state is VALUE", getState() == State.VALUE);
isTrue("context not null", getContext() != null);
isTrue("context is not JAVASCRIPT_WITH_SCOPE", getContext().getContextType() != BSONContextType.JAVASCRIPT_WITH_SCOPE);
buffer.write(BSONType.DOCUMENT.getValue());
writeCurrentName();
int startPos = buffer.getPosition();
encoder.writeObject(buffer, dbObject);
throwIfSizeExceedsLimit(buffer.getPosition() - startPos);
setState(getNextState());
}
public void pushMaxDocumentSize(final int maxDocumentSize) {
maxDocumentSizeStack.push(maxDocumentSize);
}
public void popMaxDocumentSize() {
maxDocumentSizeStack.pop();
}
public void mark() {
mark = new Mark();
}
public void reset() {
if (mark == null) {
throw new IllegalStateException("Can not reset without first marking");
}
mark.reset();
mark = null;
}
private void writeCurrentName() {
if (getContext().getContextType() == BSONContextType.ARRAY) {
buffer.writeCString(Integer.toString(getContext().index++));
}
else {
buffer.writeCString(getName());
}
}
private void backpatchSize() {
final int size = buffer.getPosition() - getContext().startPosition;
throwIfSizeExceedsLimit(size);
buffer.backpatchSize(size);
}
private void throwIfSizeExceedsLimit(final int size) {
if (size > maxDocumentSizeStack.peek()) {
final String message = String.format("Size %d is larger than MaxDocumentSize %d.",
buffer.getPosition() - getContext().startPosition,
binaryWriterSettings.getMaxDocumentSize());
throw new MongoInternalException(message);
}
}
public class Context extends BSONWriter.Context {
private final int startPosition;
private int index; // used when contextType is an array
public Context(final Context parentContext, final BSONContextType contextType, final int startPosition) {
super(parentContext, contextType);
this.startPosition = startPosition;
}
public Context(final Context from) {
super(from);
startPosition = from.startPosition;
index = from.index;
}
@Override
public Context getParentContext() {
return (Context) super.getParentContext();
}
@Override
public Context copy() {
return new Context(this);
}
}
protected class Mark extends BSONWriter.Mark {
private final int position;
protected Mark() {
this.position = buffer.getPosition();
}
protected void reset() {
super.reset();
buffer.truncateToPosition(mark.position);
}
}
}
| apache-2.0 |
leafclick/intellij-community | plugins/InspectionGadgets/testsrc/com/siyeh/ig/controlflow/NestedSwitchInspectionTest.java | 802 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.siyeh.ig.controlflow;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.testFramework.LightProjectDescriptor;
import com.siyeh.ig.LightJavaInspectionTestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class NestedSwitchInspectionTest extends LightJavaInspectionTestCase {
public void testNestedSwitch() {
doTest();
}
@NotNull
@Override
protected LightProjectDescriptor getProjectDescriptor() {
return JAVA_13;
}
@Nullable
@Override
protected InspectionProfileEntry getInspection() {
return new NestedSwitchStatementInspection();
}
}
| apache-2.0 |
INAETICS/Drones-Simulator | drone.simulator.spi/src/main/java/org/inaetics/drone/simulator/spi/Constants.java | 1265 | /*******************************************************************************
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.inaetics.drone.simulator.spi;
public class Constants {
//from engine to drones: DroneState, GameState. ?KillEvent?
public static final String STATE_UPDATE_TOPIC_NAME = "state-update";
//from drones to engine: BulletEvent, DroneAnnouncement, ?EngineEvent?, etc
public static final String DRONE_UPDATE_TOPIC_NAME = "drone-update";
//COSTS
public static final double DRONE_COMPONENTS_GUN_COST = 40.0;
public static final double DRONE_COMPONENTS_RADAR_COST = 100.0;
//TODO etc
}
| apache-2.0 |
ssharma/camel | components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/SalesforceComponent.java | 21421 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.salesforce;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.ComponentConfiguration;
import org.apache.camel.Endpoint;
import org.apache.camel.component.salesforce.api.SalesforceException;
import org.apache.camel.component.salesforce.api.dto.AbstractQueryRecordsBase;
import org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase;
import org.apache.camel.component.salesforce.internal.OperationName;
import org.apache.camel.component.salesforce.internal.SalesforceSession;
import org.apache.camel.component.salesforce.internal.streaming.SubscriptionHelper;
import org.apache.camel.impl.UriEndpointComponent;
import org.apache.camel.spi.EndpointCompleter;
import org.apache.camel.spi.Metadata;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ReflectionHelper;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.eclipse.jetty.client.HttpProxy;
import org.eclipse.jetty.client.Origin;
import org.eclipse.jetty.client.ProxyConfiguration;
import org.eclipse.jetty.client.Socks4Proxy;
import org.eclipse.jetty.client.api.Authentication;
import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.client.util.DigestAuthentication;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents the component that manages {@link SalesforceEndpoint}.
*/
public class SalesforceComponent extends UriEndpointComponent implements EndpointCompleter {
private static final Logger LOG = LoggerFactory.getLogger(SalesforceComponent.class);
private static final int CONNECTION_TIMEOUT = 60000;
private static final Pattern SOBJECT_NAME_PATTERN = Pattern.compile("^.*[\\?&]sObjectName=([^&,]+).*$");
private static final String APEX_CALL_PREFIX = OperationName.APEX_CALL.value() + "/";
@Metadata(label = "security")
private SalesforceLoginConfig loginConfig;
@Metadata(label = "advanced")
private SalesforceEndpointConfig config;
// HTTP client parameters, map of property-name to value
@Metadata(label = "advanced")
private Map<String, Object> httpClientProperties;
// SSL parameters
@Metadata(label = "security")
private SSLContextParameters sslContextParameters;
// Proxy host and port
@Metadata(label = "proxy")
private String httpProxyHost;
@Metadata(label = "proxy")
private Integer httpProxyPort;
@Metadata(label = "proxy")
private boolean isHttpProxySocks4;
@Metadata(label = "proxy,security")
private boolean isHttpProxySecure = true;
@Metadata(label = "proxy")
private Set<String> httpProxyIncludedAddresses;
@Metadata(label = "proxy")
private Set<String> httpProxyExcludedAddresses;
// Proxy basic authentication
@Metadata(label = "proxy,security", secret = true)
private String httpProxyUsername;
@Metadata(label = "proxy,security", secret = true)
private String httpProxyPassword;
@Metadata(label = "proxy,security")
private String httpProxyAuthUri;
@Metadata(label = "proxy,security")
private String httpProxyRealm;
@Metadata(label = "proxy,security")
private boolean httpProxyUseDigestAuth;
// DTO packages to scan
private String[] packages;
// component state
private SalesforceHttpClient httpClient;
private SalesforceSession session;
private Map<String, Class<?>> classMap;
// Lazily created helper for consumer endpoints
private SubscriptionHelper subscriptionHelper;
public SalesforceComponent() {
super(SalesforceEndpoint.class);
}
public SalesforceComponent(CamelContext context) {
super(context, SalesforceEndpoint.class);
}
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// get Operation from remaining URI
OperationName operationName = null;
String topicName = null;
String apexUrl = null;
try {
LOG.debug("Creating endpoint for: {}", remaining);
if (remaining.startsWith(APEX_CALL_PREFIX)) {
// extract APEX URL
apexUrl = remaining.substring(APEX_CALL_PREFIX.length());
remaining = OperationName.APEX_CALL.value();
}
operationName = OperationName.fromValue(remaining);
} catch (IllegalArgumentException ex) {
// if its not an operation name, treat is as topic name for consumer endpoints
topicName = remaining;
}
// create endpoint config
if (config == null) {
config = new SalesforceEndpointConfig();
}
if (config.getHttpClient() == null) {
// set the component's httpClient as default
config.setHttpClient(httpClient);
}
// create a deep copy and map parameters
final SalesforceEndpointConfig copy = config.copy();
setProperties(copy, parameters);
// set apexUrl in endpoint config
if (apexUrl != null) {
copy.setApexUrl(apexUrl);
}
final SalesforceEndpoint endpoint = new SalesforceEndpoint(uri, this, copy,
operationName, topicName);
// map remaining parameters to endpoint (specifically, synchronous)
setProperties(endpoint, parameters);
// if operation is APEX call, map remaining parameters to query params
if (operationName == OperationName.APEX_CALL && !parameters.isEmpty()) {
Map<String, Object> queryParams = new HashMap<String, Object>(copy.getApexQueryParams());
// override component params with endpoint params
queryParams.putAll(parameters);
parameters.clear();
copy.setApexQueryParams(queryParams);
}
return endpoint;
}
private Map<String, Class<?>> parsePackages() {
Map<String, Class<?>> result = new HashMap<String, Class<?>>();
Set<Class<?>> classes = getCamelContext().getPackageScanClassResolver().
findImplementations(AbstractSObjectBase.class, packages);
for (Class<?> aClass : classes) {
// findImplementations also returns AbstractSObjectBase for some reason!!!
if (AbstractSObjectBase.class != aClass) {
result.put(aClass.getSimpleName(), aClass);
}
}
return result;
}
@Override
protected void doStart() throws Exception {
// validate properties
ObjectHelper.notNull(loginConfig, "loginConfig");
// create a Jetty HttpClient if not already set
if (null == httpClient) {
if (config != null && config.getHttpClient() != null) {
httpClient = config.getHttpClient();
} else {
// set ssl context parameters if set
final SSLContextParameters contextParameters = sslContextParameters != null
? sslContextParameters : new SSLContextParameters();
final SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setSslContext(contextParameters.createSSLContext(getCamelContext()));
httpClient = new SalesforceHttpClient(sslContextFactory);
// default settings, use httpClientProperties to set other properties
httpClient.setConnectTimeout(CONNECTION_TIMEOUT);
}
}
// set HTTP client parameters
if (httpClientProperties != null && !httpClientProperties.isEmpty()) {
IntrospectionSupport.setProperties(getCamelContext().getTypeConverter(),
httpClient, new HashMap<String, Object>(httpClientProperties));
}
// set HTTP proxy settings
if (this.httpProxyHost != null && httpProxyPort != null) {
Origin.Address proxyAddress = new Origin.Address(this.httpProxyHost, this.httpProxyPort);
ProxyConfiguration.Proxy proxy;
if (isHttpProxySocks4) {
proxy = new Socks4Proxy(proxyAddress, isHttpProxySecure);
} else {
proxy = new HttpProxy(proxyAddress, isHttpProxySecure);
}
if (httpProxyIncludedAddresses != null && !httpProxyIncludedAddresses.isEmpty()) {
proxy.getIncludedAddresses().addAll(httpProxyIncludedAddresses);
}
if (httpProxyExcludedAddresses != null && !httpProxyExcludedAddresses.isEmpty()) {
proxy.getExcludedAddresses().addAll(httpProxyExcludedAddresses);
}
httpClient.getProxyConfiguration().getProxies().add(proxy);
}
if (this.httpProxyUsername != null && httpProxyPassword != null) {
ObjectHelper.notEmpty(httpProxyAuthUri, "httpProxyAuthUri");
ObjectHelper.notEmpty(httpProxyRealm, "httpProxyRealm");
final Authentication authentication;
if (httpProxyUseDigestAuth) {
authentication = new DigestAuthentication(new URI(httpProxyAuthUri),
httpProxyRealm, httpProxyUsername, httpProxyPassword);
} else {
authentication = new BasicAuthentication(new URI(httpProxyAuthUri),
httpProxyRealm, httpProxyUsername, httpProxyPassword);
}
httpClient.getAuthenticationStore().addAuthentication(authentication);
}
// support restarts
if (null == this.session) {
this.session = new SalesforceSession(httpClient, httpClient.getTimeout(), loginConfig);
}
// set session before calling start()
httpClient.setSession(this.session);
// start the Jetty client to initialize thread pool, etc.
httpClient.start();
// login at startup if lazyLogin is disabled
if (!loginConfig.isLazyLogin()) {
ServiceHelper.startService(session);
}
if (packages != null && packages.length > 0) {
// parse the packages to create SObject name to class map
classMap = parsePackages();
LOG.info("Found {} generated classes in packages: {}", classMap.size(), Arrays.asList(packages));
} else {
// use an empty map to avoid NPEs later
LOG.warn("Missing property packages, getSObject* operations will NOT work");
classMap = new HashMap<String, Class<?>>(0);
}
if (subscriptionHelper != null) {
ServiceHelper.startService(subscriptionHelper);
}
}
@Override
protected void doStop() throws Exception {
if (classMap != null) {
classMap.clear();
}
try {
if (subscriptionHelper != null) {
// shutdown all streaming connections
// note that this is done in the component, and not in consumer
ServiceHelper.stopService(subscriptionHelper);
subscriptionHelper = null;
}
if (session != null && session.getAccessToken() != null) {
try {
// logout of Salesforce
ServiceHelper.stopService(session);
} catch (SalesforceException ignored) {
}
}
} finally {
if (httpClient != null) {
// shutdown http client connections
httpClient.stop();
// destroy http client if it was created by the component
if (config.getHttpClient() == null) {
httpClient.destroy();
}
httpClient = null;
}
}
}
public SubscriptionHelper getSubscriptionHelper(String topicName) throws Exception {
if (subscriptionHelper == null) {
// lazily create subscription helper
subscriptionHelper = new SubscriptionHelper(this, topicName);
// also start the helper to connect to Salesforce
ServiceHelper.startService(subscriptionHelper);
}
return subscriptionHelper;
}
@Override
public List<String> completeEndpointPath(ComponentConfiguration configuration, String completionText) {
final List<String> result = new ArrayList<String>();
// return operations names on empty completion text
final boolean empty = ObjectHelper.isEmpty(completionText);
if (empty || completionText.indexOf('?') == -1) {
if (empty) {
completionText = "";
}
final OperationName[] values = OperationName.values();
for (OperationName val : values) {
final String strValue = val.value();
if (strValue.startsWith(completionText)) {
result.add(strValue);
}
}
// also add place holder for user defined push topic name for empty completionText
if (empty) {
result.add("[PushTopicName]");
}
} else {
// handle package parameters
if (completionText.matches("^.*[\\?&]sObjectName=$")) {
result.addAll(classMap.keySet());
} else if (completionText.matches("^.*[\\?&]sObjectFields=$")) {
// find sObjectName from configuration or completionText
String sObjectName = (String) configuration.getParameter("sObjectName");
if (sObjectName == null) {
final Matcher matcher = SOBJECT_NAME_PATTERN.matcher(completionText);
if (matcher.matches()) {
sObjectName = matcher.group(1);
}
}
// return all fields of sObject
if (sObjectName != null) {
final Class<?> aClass = classMap.get(sObjectName);
ReflectionHelper.doWithFields(aClass, new ReflectionHelper.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// get non-static fields
if ((field.getModifiers() & Modifier.STATIC) == 0) {
result.add(field.getName());
}
}
});
}
} else if (completionText.matches("^.*[\\?&]sObjectClass=$")) {
for (Class c : classMap.values()) {
result.add(c.getName());
}
// also add Query records classes
Set<Class<?>> classes = getCamelContext().getPackageScanClassResolver().
findImplementations(AbstractQueryRecordsBase.class, packages);
for (Class<?> aClass : classes) {
// findImplementations also returns AbstractQueryRecordsBase for some reason!!!
if (AbstractQueryRecordsBase.class != aClass) {
result.add(aClass.getName());
}
}
}
}
return result;
}
public SalesforceLoginConfig getLoginConfig() {
return loginConfig;
}
/**
* To use the shared SalesforceLoginConfig as login configuration
*/
public void setLoginConfig(SalesforceLoginConfig loginConfig) {
this.loginConfig = loginConfig;
}
public SalesforceEndpointConfig getConfig() {
return config;
}
/**
* To use the shared SalesforceEndpointConfig as endpoint configuration
*/
public void setConfig(SalesforceEndpointConfig config) {
this.config = config;
}
public Map<String, Object> getHttpClientProperties() {
return httpClientProperties;
}
/**
* Used for configuring HTTP client properties as key/value pairs
*/
public void setHttpClientProperties(Map<String, Object> httpClientProperties) {
this.httpClientProperties = httpClientProperties;
}
public SSLContextParameters getSslContextParameters() {
return sslContextParameters;
}
/**
* To configure security using SSLContextParameters
*/
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
public String getHttpProxyHost() {
return httpProxyHost;
}
/**
* To configure HTTP proxy host
*/
public void setHttpProxyHost(String httpProxyHost) {
this.httpProxyHost = httpProxyHost;
}
public Integer getHttpProxyPort() {
return httpProxyPort;
}
/**
* To configure HTTP proxy port
*/
public void setHttpProxyPort(Integer httpProxyPort) {
this.httpProxyPort = httpProxyPort;
}
public String getHttpProxyUsername() {
return httpProxyUsername;
}
/**
* To configure HTTP proxy username
*/
public void setHttpProxyUsername(String httpProxyUsername) {
this.httpProxyUsername = httpProxyUsername;
}
public String getHttpProxyPassword() {
return httpProxyPassword;
}
/**
* To configure HTTP proxy password
*/
public void setHttpProxyPassword(String httpProxyPassword) {
this.httpProxyPassword = httpProxyPassword;
}
public boolean isHttpProxySocks4() {
return isHttpProxySocks4;
}
/**
* Enable for Socks4 proxy, false by default
*/
public void setIsHttpProxySocks4(boolean isHttpProxySocks4) {
this.isHttpProxySocks4 = isHttpProxySocks4;
}
public boolean isHttpProxySecure() {
return isHttpProxySecure;
}
/**
* Enable for TLS connections, true by default
*/
public void setIsHttpProxySecure(boolean isHttpProxySecure) {
this.isHttpProxySecure = isHttpProxySecure;
}
public Set<String> getHttpProxyIncludedAddresses() {
return httpProxyIncludedAddresses;
}
/**
* HTTP proxy included addresses
*/
public void setHttpProxyIncludedAddresses(Set<String> httpProxyIncludedAddresses) {
this.httpProxyIncludedAddresses = httpProxyIncludedAddresses;
}
public Set<String> getHttpProxyExcludedAddresses() {
return httpProxyExcludedAddresses;
}
/**
* HTTP proxy excluded addresses
*/
public void setHttpProxyExcludedAddresses(Set<String> httpProxyExcludedAddresses) {
this.httpProxyExcludedAddresses = httpProxyExcludedAddresses;
}
public String getHttpProxyAuthUri() {
return httpProxyAuthUri;
}
/**
* HTTP proxy authentication URI
*/
public void setHttpProxyAuthUri(String httpProxyAuthUri) {
this.httpProxyAuthUri = httpProxyAuthUri;
}
public String getHttpProxyRealm() {
return httpProxyRealm;
}
/**
* HTTP proxy authentication realm
*/
public void setHttpProxyRealm(String httpProxyRealm) {
this.httpProxyRealm = httpProxyRealm;
}
public boolean isHttpProxyUseDigestAuth() {
return httpProxyUseDigestAuth;
}
/**
* Use HTTP proxy Digest authentication, false by default
*/
public void setHttpProxyUseDigestAuth(boolean httpProxyUseDigestAuth) {
this.httpProxyUseDigestAuth = httpProxyUseDigestAuth;
}
public String[] getPackages() {
return packages;
}
/**
* Package names to scan for DTO classes (multiple packages can be separated by comma).
*/
public void setPackages(String[] packages) {
this.packages = packages;
}
/**
* Package names to scan for DTO classes (multiple packages can be separated by comma).
*/
public void setPackages(String packages) {
// split using comma
if (packages != null) {
setPackages(packages.split(","));
}
}
public SalesforceSession getSession() {
return session;
}
public Map<String, Class<?>> getClassMap() {
return classMap;
}
}
| apache-2.0 |
CSCSI/TrianaCloud | Utils/src/main/java/org/trianacode/TrianaCloud/Utils/StreamToOutput.java | 2376 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.trianacode.TrianaCloud.Utils;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* @author Ian Harvey
* @version 1.0.0 Apr 18, 2012
*/
public class StreamToOutput implements Runnable {
private Logger logger = Logger.getLogger(this.getClass().toString());
private InputStream inputStream;
private String description;
private Thread thread;
private BufferedReader inreader;
public StreamToOutput(InputStream inputStream, String description) {
this.inputStream = inputStream;
this.description = description;
inreader = new BufferedReader(new InputStreamReader(this.inputStream));
}
public void start() {
thread = new Thread(this);
thread.run();
}
@Override
public void run() {
// System.out.println("Reading stream : " + description);
try {
String str;
while ((str = inreader.readLine()) != null) {
logger.info(" >> " + description + " : " + str);
}
} catch (IOException e) {
logger.error("Error with stream " + description + " closing");
} finally {
try {
inreader.close();
} catch (IOException e) {
logger.error(e);
}
logger.info("Closed streamReader " + description);
}
}
}
| apache-2.0 |
boneman1231/org.apache.felix | trunk/upnp/tester/src/main/java/org/apache/felix/upnp/tester/gui/Util.java | 3825 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.upnp.tester.gui;
import java.awt.GridBagConstraints;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/*
* @author <a href="mailto:dev@felix.apache.org">Felix Project Team</a>
*/
public class Util {
final static GridBagConstraints constrains = new GridBagConstraints();
public static GridBagConstraints setConstrains(int x,int y,int w,int h,int wx, int wy)
{
constrains.insets.left=5;
constrains.insets.right=5;
constrains.insets.bottom=3;
constrains.fill=GridBagConstraints.BOTH;
constrains.anchor=GridBagConstraints.WEST;
constrains.gridx=x;
constrains.gridy=y;
constrains.gridwidth=w;
constrains.gridheight=h;
constrains.weightx=wx;
constrains.weighty=wy;
return constrains;
}
public static String justString(Object obj){
if (obj == null) return "";
else if (obj instanceof String[]){
String[] items = (String[])obj;
String tmp = "";
for (int i = 0; i < items.length; i++) {
tmp+=items[i]+"; ";
}
return tmp;
}
return obj.toString();
}
public static void openUrl(String url) {
try {
if (url == null) return;
String os=System.getProperty("os.name","").toLowerCase();
Process p = null;
if(os.indexOf("windows")!=-1){
String cmd = null;
cmd = "cmd.exe /C start "+url;
LogPanel.log("[Executing cmd] " +cmd);
p = Runtime.getRuntime().exec(cmd);
}else if(os.indexOf("linux")!=-1){
String[] cmd = new String[]{
"/bin/sh",
"-c",
"( $BROWSER " + url + " || mozilla-firefox '" + url + "' || firefox '" + url
+ "' || mozilla '" + url + "' || konqueror '" + url + "' || opera '" + url + "' )"
};
StringBuffer sb = new StringBuffer();
for (int i = 0; i < cmd.length; i++) {
sb.append(" ").append(cmd[i]);
}
LogPanel.log("[Executing cmd] " +sb.toString());
p = Runtime.getRuntime().exec(cmd);
}
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
while (true) {
while(err.ready()) System.err.println(err.readLine());
while(out.ready()) System.out.println(out.readLine());
try{
p.exitValue();
break;
}catch (IllegalThreadStateException e) {
}
}
} catch (Exception ex){
System.out.println(ex);
}
}
}
| apache-2.0 |
bjorndm/prebake | code/third_party/bdb/src/com/sleepycat/persist/impl/RawArrayInput.java | 1159 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: RawArrayInput.java,v 1.10 2010/01/18 15:27:04 cwl Exp $
*/
package com.sleepycat.persist.impl;
import com.sleepycat.persist.raw.RawObject;
import com.sleepycat.je.utilint.IdentityHashMap;
/**
* Extends RawAbstractInput to convert array (ObjectArrayFormat and
* PrimitiveArrayteKeyFormat) RawObject instances.
*
* @author Mark Hayes
*/
class RawArrayInput extends RawAbstractInput {
private Object[] array;
private int index;
private Format componentFormat;
RawArrayInput(Catalog catalog,
boolean rawAccess,
IdentityHashMap converted,
RawObject raw,
Format componentFormat) {
super(catalog, rawAccess, converted);
array = raw.getElements();
this.componentFormat = componentFormat;
}
@Override
public int readArrayLength() {
return array.length;
}
@Override
Object readNext() {
Object o = array[index++];
return checkAndConvert(o, componentFormat);
}
}
| apache-2.0 |
mapr/hbase | hbase-server/src/main/java/org/apache/hadoop/hbase/procedure/ZKProcedureUtil.java | 10812 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.procedure;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.hbase.zookeeper.ZKUtil;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener;
import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
import org.apache.zookeeper.KeeperException;
/**
* This is a shared ZooKeeper-based znode management utils for distributed procedure. All znode
* operations should go through the provided methods in coordinators and members.
*
* Layout of nodes in ZK is
* /hbase/[op name]/acquired/
* [op instance] - op data/
* /[nodes that have acquired]
* /reached/
* [op instance]/
* /[nodes that have completed]
* /abort/
* [op instance] - failure data
*
* NOTE: while acquired and completed are znode dirs, abort is actually just a znode.
*
* Assumption here that procedure names are unique
*/
@InterfaceAudience.Private
public abstract class ZKProcedureUtil
extends ZooKeeperListener implements Closeable {
private static final Log LOG = LogFactory.getLog(ZKProcedureUtil.class);
public static final String ACQUIRED_BARRIER_ZNODE_DEFAULT = "acquired";
public static final String REACHED_BARRIER_ZNODE_DEFAULT = "reached";
public static final String ABORT_ZNODE_DEFAULT = "abort";
public final String baseZNode;
protected final String acquiredZnode;
protected final String reachedZnode;
protected final String abortZnode;
/**
* Top-level watcher/controller for procedures across the cluster.
* <p>
* On instantiation, this ensures the procedure znodes exist. This however requires the passed in
* watcher has been started.
* @param watcher watcher for the cluster ZK. Owned by <tt>this</tt> and closed via
* {@link #close()}
* @param procDescription name of the znode describing the procedure to run
* @throws KeeperException when the procedure znodes cannot be created
*/
public ZKProcedureUtil(ZooKeeperWatcher watcher, String procDescription)
throws KeeperException {
super(watcher);
// make sure we are listening for events
watcher.registerListener(this);
// setup paths for the zknodes used in procedures
this.baseZNode = ZKUtil.joinZNode(watcher.baseZNode, procDescription);
acquiredZnode = ZKUtil.joinZNode(baseZNode, ACQUIRED_BARRIER_ZNODE_DEFAULT);
reachedZnode = ZKUtil.joinZNode(baseZNode, REACHED_BARRIER_ZNODE_DEFAULT);
abortZnode = ZKUtil.joinZNode(baseZNode, ABORT_ZNODE_DEFAULT);
// first make sure all the ZK nodes exist
// make sure all the parents exist (sometimes not the case in tests)
ZKUtil.createWithParents(watcher, acquiredZnode);
// regular create because all the parents exist
ZKUtil.createAndFailSilent(watcher, reachedZnode);
ZKUtil.createAndFailSilent(watcher, abortZnode);
}
@Override
public void close() throws IOException {
// the watcher is passed from either Master or Region Server
// watcher.close() will be called by the owner so no need to call close() here
}
public String getAcquiredBarrierNode(String opInstanceName) {
return ZKProcedureUtil.getAcquireBarrierNode(this, opInstanceName);
}
public String getReachedBarrierNode(String opInstanceName) {
return ZKProcedureUtil.getReachedBarrierNode(this, opInstanceName);
}
public String getAbortZNode(String opInstanceName) {
return ZKProcedureUtil.getAbortNode(this, opInstanceName);
}
public String getAbortZnode() {
return abortZnode;
}
public String getBaseZnode() {
return baseZNode;
}
public String getAcquiredBarrier() {
return acquiredZnode;
}
/**
* Get the full znode path for the node used by the coordinator to trigger a global barrier
* acquire on each subprocedure.
* @param controller controller running the procedure
* @param opInstanceName name of the running procedure instance (not the procedure description).
* @return full znode path to the prepare barrier/start node
*/
public static String getAcquireBarrierNode(ZKProcedureUtil controller,
String opInstanceName) {
return ZKUtil.joinZNode(controller.acquiredZnode, opInstanceName);
}
/**
* Get the full znode path for the node used by the coordinator to trigger a global barrier
* execution and release on each subprocedure.
* @param controller controller running the procedure
* @param opInstanceName name of the running procedure instance (not the procedure description).
* @return full znode path to the commit barrier
*/
public static String getReachedBarrierNode(ZKProcedureUtil controller,
String opInstanceName) {
return ZKUtil.joinZNode(controller.reachedZnode, opInstanceName);
}
/**
* Get the full znode path for the node used by the coordinator or member to trigger an abort
* of the global barrier acquisition or execution in subprocedures.
* @param controller controller running the procedure
* @param opInstanceName name of the running procedure instance (not the procedure description).
* @return full znode path to the abort znode
*/
public static String getAbortNode(ZKProcedureUtil controller, String opInstanceName) {
return ZKUtil.joinZNode(controller.abortZnode, opInstanceName);
}
public ZooKeeperWatcher getWatcher() {
return watcher;
}
/**
* Is this a procedure related znode path?
*
* TODO: this is not strict, can return true if had name just starts with same prefix but is
* different zdir.
*
* @return true if starts with baseZnode
*/
boolean isInProcedurePath(String path) {
return path.startsWith(baseZNode);
}
/**
* Is this the exact procedure barrier acquired znode
*/
boolean isAcquiredNode(String path) {
return path.equals(acquiredZnode);
}
/**
* Is this in the procedure barrier acquired znode path
*/
boolean isAcquiredPathNode(String path) {
return path.startsWith(this.acquiredZnode) && !path.equals(acquiredZnode) &&
isMemberNode(path, acquiredZnode);
}
/**
* Is this the exact procedure barrier reached znode
*/
boolean isReachedNode(String path) {
return path.equals(reachedZnode);
}
/**
* Is this in the procedure barrier reached znode path
*/
boolean isReachedPathNode(String path) {
return path.startsWith(this.reachedZnode) && !path.equals(reachedZnode) &&
isMemberNode(path, reachedZnode);
}
/*
* Returns true if the specified path is a member of the "statePath"
* /hbase/<ProcName>/<state>/<instance>/member
* |------ state path -----|
* |------------------ path ------------------|
*/
private boolean isMemberNode(final String path, final String statePath) {
int count = 0;
for (int i = statePath.length(); i < path.length(); ++i) {
count += (path.charAt(i) == ZKUtil.ZNODE_PATH_SEPARATOR) ? 1 : 0;
}
return count == 2;
}
/**
* Is this in the procedure barrier abort znode path
*/
boolean isAbortNode(String path) {
return path.equals(abortZnode);
}
/**
* Is this in the procedure barrier abort znode path
*/
public boolean isAbortPathNode(String path) {
return path.startsWith(this.abortZnode) && !path.equals(abortZnode);
}
// --------------------------------------------------------------------------
// internal debugging methods
// --------------------------------------------------------------------------
/**
* Recursively print the current state of ZK (non-transactional)
* @param root name of the root directory in zk to print
* @throws KeeperException
*/
void logZKTree(String root) {
if (!LOG.isDebugEnabled()) return;
LOG.debug("Current zk system:");
String prefix = "|-";
LOG.debug(prefix + root);
try {
logZKTree(root, prefix);
} catch (KeeperException e) {
throw new RuntimeException(e);
}
}
/**
* Helper method to print the current state of the ZK tree.
* @see #logZKTree(String)
* @throws KeeperException if an unexpected exception occurs
*/
protected void logZKTree(String root, String prefix) throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(watcher, root);
if (children == null) return;
for (String child : children) {
LOG.debug(prefix + child);
String node = ZKUtil.joinZNode(root.equals("/") ? "" : root, child);
logZKTree(node, prefix + "---");
}
}
public void clearChildZNodes() throws KeeperException {
// TODO This is potentially racy since not atomic. update when we support zk that has multi
LOG.info("Clearing all procedure znodes: " + acquiredZnode + " " + reachedZnode + " "
+ abortZnode);
// If the coordinator was shutdown mid-procedure, then we are going to lose
// an procedure that was previously started by cleaning out all the previous state. Its much
// harder to figure out how to keep an procedure going and the subject of HBASE-5487.
ZKUtil.deleteChildrenRecursively(watcher, acquiredZnode);
ZKUtil.deleteChildrenRecursively(watcher, reachedZnode);
ZKUtil.deleteChildrenRecursively(watcher, abortZnode);
}
public void clearZNodes(String procedureName) throws KeeperException {
// TODO This is potentially racy since not atomic. update when we support zk that has multi
LOG.info("Clearing all znodes for procedure " + procedureName + "including nodes "
+ acquiredZnode + " " + reachedZnode + " " + abortZnode);
ZKUtil.deleteNodeRecursively(watcher, getAcquiredBarrierNode(procedureName));
ZKUtil.deleteNodeRecursively(watcher, getReachedBarrierNode(procedureName));
ZKUtil.deleteNodeRecursively(watcher, getAbortZNode(procedureName));
}
} | apache-2.0 |
PublicHealthEngland/animal-welfare-assessment-grid | code/server/src/main/java/uk/gov/phe/erdst/sc/awag/datamodel/Study.java | 3957 | package uk.gov.phe.erdst.sc.awag.datamodel;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.google.gson.annotations.SerializedName;
@Entity
@Table(name = "study")
@NamedQueries(value = {@NamedQuery(name = Study.Q_FIND_ALL, query = "SELECT s FROM Study s"),
@NamedQuery(name = Study.Q_FIND_COUNT_ALL, query = "SELECT COUNT(s) FROM Study s"),
// CS:OFF: LineLength
@NamedQuery(name = Study.Q_FIND_ALL_STUDIES_LIKE,
query = "SELECT s FROM Study s WHERE LOWER(s.mStudyNumber) LIKE :like ORDER BY LENGTH(s.mStudyNumber) ASC,"
+ " s.mStudyNumber ASC"),
@NamedQuery(name = Study.Q_FIND_COUNT_ALL_STUDIES_LIKE,
query = "SELECT COUNT(s) FROM Study s WHERE LOWER(s.mStudyNumber) LIKE :like"),
@NamedQuery(name = Study.Q_FIND_STUDY_WITH_ANIMAL,
query = "SELECT s FROM Study s JOIN s.mStudyGroups groups JOIN groups.mAnimals animals WHERE s.mIsOpen = true AND animals = :animal")})
// CS:ON
public class Study implements Serializable, EntitySelect
{
public static final String Q_FIND_ALL = "findAll";
public static final String Q_FIND_COUNT_ALL = "findCountAll";
public static final String Q_FIND_ALL_STUDIES_LIKE = "findAllStudiesLike";
public static final String Q_FIND_COUNT_ALL_STUDIES_LIKE = "findCountAllStudiesLike";
public static final String Q_FIND_STUDY_WITH_ANIMAL = "findStudyWithAnimal";
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@SerializedName(value = "studyId")
private Long mId;
@SerializedName(value = "studyIsOpen")
private boolean mIsOpen;
@SerializedName(value = "studyName")
private String mStudyNumber;
@OneToMany
@JoinTable(name = "study_study_group", joinColumns = {@JoinColumn(name = "study_mid")},
inverseJoinColumns = {@JoinColumn(name = "mgroups_mid")})
@SerializedName(value = "studyGroups")
private Set<StudyGroup> mStudyGroups;
public Long getId()
{
return mId;
}
public void setId(Long id)
{
mId = id;
}
public boolean isOpen()
{
return mIsOpen;
}
public void setIsOpen(boolean isOpen)
{
mIsOpen = isOpen;
}
public String getStudyNumber()
{
return mStudyNumber;
}
public void setStudyNumber(String studyNumber)
{
mStudyNumber = studyNumber;
}
public Set<StudyGroup> getStudyGroups()
{
return mStudyGroups;
}
public void setStudyGroups(Set<StudyGroup> studyGroups)
{
mStudyGroups = studyGroups;
}
@Override
public Long getEntitySelectId()
{
return mId;
}
@Override
public String getEntitySelectName()
{
return mStudyNumber;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((mId == null) ? 0 : mId.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
Study other = (Study) obj;
if (mId == null)
{
if (other.mId != null)
{
return false;
}
}
else if (!mId.equals(other.mId))
{
return false;
}
return true;
}
}
| apache-2.0 |
Thar0l/mycontroller | modules/core/src/main/java/org/mycontroller/standalone/api/ResourcesGroupApi.java | 3190 | /*
* Copyright 2015-2016 Jeeva Kandasamy (jkandasa@gmail.com)
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mycontroller.standalone.api;
import java.util.HashMap;
import java.util.List;
import org.mycontroller.standalone.api.jaxrs.json.Query;
import org.mycontroller.standalone.api.jaxrs.json.QueryResponse;
import org.mycontroller.standalone.db.DaoUtils;
import org.mycontroller.standalone.db.DeleteResourceUtils;
import org.mycontroller.standalone.db.tables.ResourcesGroup;
import org.mycontroller.standalone.db.tables.ResourcesGroupMap;
import org.mycontroller.standalone.group.ResourcesGroupUtils;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 0.0.3
*/
public class ResourcesGroupApi {
public void updateResourcesGroup(ResourcesGroup resourcesGroup) {
ResourcesGroup resourcesGroupOld = DaoUtils.getResourcesGroupDao().get(resourcesGroup.getId());
resourcesGroupOld.setDescription(resourcesGroup.getDescription());
resourcesGroupOld.setName(resourcesGroup.getName());
DaoUtils.getResourcesGroupDao().update(resourcesGroupOld);
}
public void addResourcesGroup(ResourcesGroup resourcesGroup) {
DaoUtils.getResourcesGroupDao().create(resourcesGroup);
}
public ResourcesGroup getResourcesGroup(int groupId) {
return DaoUtils.getResourcesGroupDao().get(groupId);
}
public QueryResponse getAllResourcesGroups(HashMap<String, Object> filters) {
return DaoUtils.getResourcesGroupDao().getAll(Query.get(filters));
}
public void deleteResourcesGroup(List<Integer> ids) {
DeleteResourceUtils.deleteResourcesGroup(ids);
}
public void turnOn(List<Integer> ids) {
ResourcesGroupUtils.turnONresourcesGroup(ids);
}
public void turnOff(List<Integer> ids) {
ResourcesGroupUtils.turnOFFresourcesGroup(ids);
}
//Mapping
public void updateResourcesGroupMap(ResourcesGroupMap resourcesGroupMap) {
DaoUtils.getResourcesGroupMapDao().update(resourcesGroupMap);
}
public void addResourcesGroupMap(ResourcesGroupMap resourcesGroupMap) {
DaoUtils.getResourcesGroupMapDao().createOrUpdate(resourcesGroupMap);
}
public ResourcesGroupMap getResourcesGroupMap(int id) {
return DaoUtils.getResourcesGroupMapDao().get(id);
}
public QueryResponse getAllResourcesGroupsMap(HashMap<String, Object> filters) {
return DaoUtils.getResourcesGroupMapDao().getAll(Query.get(filters));
}
public void deleteResourcesGroupMap(List<Integer> ids) {
DaoUtils.getResourcesGroupMapDao().delete(ids);
}
}
| apache-2.0 |
frederic-bapst/Cojac | src/main/java/ch/eiafr/cojac/models/wrappers/WrapperDerivation.java | 8515 | /*
* *
* Copyright 2011-2014 Frédéric Bapst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ch.eiafr.cojac.models.wrappers;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleUnaryOperator;
public class WrapperDerivation extends ACompactWrapper {
private final double value;
private final double deriv;
private WrapperDerivation(double value, double dValue) {
this.value = value;
this.deriv = dValue;
}
//-------------------------------------------------------------------------
//----------------- Necessary constructor -------------------------------
//-------------------------------------------------------------------------
public WrapperDerivation(ACojacWrapper w) {
this(w==null ? 0.0 : der(w).value,
w==null ? 0.0 : der(w).deriv);
}
//-------------------------------------------------------------------------
// Most of the operations do not follow those "operator" rules,
// and are thus fully redefined
@Override
public ACojacWrapper applyUnaryOp(DoubleUnaryOperator op) {
return new WrapperDerivation(op.applyAsDouble(value), op.applyAsDouble(deriv));
}
@Override
public ACojacWrapper applyBinaryOp(DoubleBinaryOperator op, ACojacWrapper b) {
WrapperDerivation bb=(WrapperDerivation)b;
return new WrapperDerivation(op.applyAsDouble(value, bb.value),
op.applyAsDouble(deriv, bb.deriv));
}
//-------------------------------------------------------------------------
public ACojacWrapper dmul(ACojacWrapper b) {
double d=this.value*der(b).deriv + this.deriv*der(b).value;
return new WrapperDerivation(this.value*der(b).value, d);
}
public ACojacWrapper ddiv(ACojacWrapper b) {
double d=this.deriv*der(b).value - this.value*der(b).deriv;
return new WrapperDerivation(this.value/der(b).value, d);
}
public ACojacWrapper drem(ACojacWrapper b) {
double d=this.deriv;
if (der(b).deriv != 0.0) // this seems hard to consider "general" dividers
d=Double.NaN;
return new WrapperDerivation(this.value%der(b).value, d);
}
public ACojacWrapper math_sqrt() {
double value = Math.sqrt(this.value);
double dValue = this.deriv / (2.0 * Math.sqrt(this.value));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_abs(){
double value = Math.abs(this.value);
double dValue = this.value < 0.0 ? -this.deriv : this.deriv;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_sin() {
double value = Math.sin(this.value);
double dValue = Math.cos(this.value) * this.deriv;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_cos() {
double value = Math.cos(this.value);
double dValue = -Math.sin(this.value) * this.deriv;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_tan() {
double value = Math.tan(this.value);
double dValue = this.deriv / (Math.cos(this.value) * Math.cos(this.value));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_asin() {
double value = Math.asin(this.value);
double dValue = this.deriv / (Math.sqrt(1.0 - this.value * this.value));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_acos() {
double value = Math.acos(this.value);
double dValue = -this.deriv / (Math.sqrt(1.0 - this.value * this.value));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_atan() {
double value = Math.atan(this.value);
double dValue = this.deriv / (1.0 + this.value * this.value);
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_sinh() {
double value = Math.sinh(this.value);
double dValue = this.deriv * Math.cosh(this.value);
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_cosh() {
double value = Math.cosh(this.value);
double dValue = this.deriv * Math.sinh(this.value);
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_tanh() {
double value = Math.tanh(this.value);
double dValue = this.deriv / (Math.cosh(this.value) * Math.cosh(this.value));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_exp() {
double value = Math.exp(this.value);
double dValue = this.deriv * Math.exp(this.value);
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_log() {
double value = Math.log(this.value);
double dValue = this.deriv / this.value;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_log10() {
double value = Math.log10(this.value);
double dValue = this.deriv / (this.value * Math.log(10.0));
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_toRadians() {
double value = Math.toRadians(this.value);
double dValue = this.deriv;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_toDegrees() {
double value = Math.toDegrees(this.value);
double dValue = this.deriv;
return new WrapperDerivation(value, dValue);
}
public ACojacWrapper math_min(ACojacWrapper b) {
return (this.value < der(b).value) ? this : b;
}
public ACojacWrapper math_max(ACojacWrapper b) {
return (this.value > der(b).value) ? this : b;
}
public ACojacWrapper math_pow(ACojacWrapper b) {
double value = Math.pow(this.value, der(b).value);
double dValue = Math.pow(this.value, der(b).value) *
(((der(b).value * this.deriv) / this.value) +
Math.log(this.value) * der(b).deriv);
return new WrapperDerivation(value, dValue);
}
@Override public double toDouble() {
return value;
}
@Override
public ACojacWrapper fromDouble(double a, boolean wasFromFloat) {
return new WrapperDerivation(a, 0.0);
}
@Override public String asInternalString() {
return value+" (deriv="+deriv+")";
}
@Override public String wrapperName() {
return "Derivation";
}
// ------------------------------------------------------------------------
public static CommonDouble COJAC_MAGIC_getDerivation(CommonDouble d) {
WrapperDerivation res=new WrapperDerivation(der(d.val).deriv, 0);
return new CommonDouble(res);
}
public static CommonFloat COJAC_MAGIC_getDerivation(CommonFloat d) {
WrapperDerivation res=new WrapperDerivation(der(d.val).deriv, 0);
return new CommonFloat(res);
}
public static CommonDouble COJAC_MAGIC_asDerivationTarget(CommonDouble d) {
WrapperDerivation res=new WrapperDerivation(der(d.val).value, 1.0);
return new CommonDouble(res);
}
public static CommonFloat COJAC_MAGIC_asDerivationTarget(CommonFloat d) {
WrapperDerivation res=new WrapperDerivation(der(d.val).value, 1.0);
return new CommonFloat(res);
}
//-------------------------------------------------------------------------
private static WrapperDerivation der(ACojacWrapper w) {
return (WrapperDerivation)w;
}
}
| apache-2.0 |
orientechnologies/orientdb | core/src/test/java/com/orientechnologies/orient/core/sql/parser/ODropViewStatementTest.java | 686 | package com.orientechnologies.orient.core.sql.parser;
import org.junit.Test;
public class ODropViewStatementTest extends OParserTestAbstract {
@Test
public void testPlain() {
checkRightSyntax("DROP VIEW Foo");
checkRightSyntax("drop view Foo");
checkRightSyntax("DROP VIEW `Foo bar`");
checkWrongSyntax("drop VIEW Foo UNSAFE ");
checkWrongSyntax("drop view Foo bar");
}
@Test
public void testIfExists() {
checkRightSyntax("DROP VIEW Foo if exists");
checkRightSyntax("DROP VIEW Foo IF EXISTS");
checkWrongSyntax("drop view Foo if");
checkWrongSyntax("drop view Foo if exists lkj");
checkWrongSyntax("drop view Foo if lkj");
}
}
| apache-2.0 |
rholder/esthree | src/test/java/com/github/rholder/esthree/cli/LbCommandTest.java | 1589 | package com.github.rholder.esthree.cli;
import com.github.rholder.esthree.Main;
import io.airlift.command.ParseArgumentsUnexpectedException;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class LbCommandTest extends LbCommand {
@Test
public void noParameters() {
Main main = new Main();
main.parseGlobalCli("lb");
main.command.parse();
}
@Test
public void help() {
Main main = new Main();
main.parseGlobalCli("lb", "-h");
main.command.parse();
}
@Test
public void happyPath() throws IOException {
Main main = new Main();
main.parseGlobalCli("lb");
main.command.parse();
LbCommand c = (LbCommand) main.command;
Assert.assertEquals(DEFAULT_LIST_BUCKET_FORMAT, c.listBucketFormat);
}
@Test
public void happyPathWithFormat() throws IOException {
Main main = new Main();
main.parseGlobalCli("lb", "-lbf", "%3 %1$tF %1$tR s3://%2$s");
main.command.parse();
LbCommand c = (LbCommand) main.command;
Assert.assertEquals("%3 %1$tF %1$tR s3://%2$s", c.listBucketFormat);
}
@Test
public void garbageParameter() throws IOException {
Main main = new Main();
try {
main.parseGlobalCli("lb", "potato");
Assert.fail("Expected ParseArgumentsUnexpectedException");
} catch (ParseArgumentsUnexpectedException e) {
Assert.assertEquals("Found unexpected parameters: [potato]", e.getMessage());
}
}
}
| apache-2.0 |
OnPositive/aml | org.aml.typesystem.java/src/test/java/org/aml/typesystem/java/tests/data/PersonWithProps.java | 357 | package org.aml.typesystem.java.tests.data;
public class PersonWithProps {
String name;
boolean age;
String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| apache-2.0 |
GaneshSPatil/gocd | server/src/main/java/com/thoughtworks/go/server/newsecurity/filters/helpers/ServerUnavailabilityResponse.java | 4283 | /*
* Copyright 2021 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.newsecurity.filters.helpers;
import com.google.gson.JsonObject;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ServerUnavailabilityResponse {
public final String JSON = "json";
public final String XML = "xml";
private final static Logger LOGGER = LoggerFactory.getLogger(ServerUnavailabilityResponse.class);
private static final OrRequestMatcher API_REQUEST_MATCHER = new OrRequestMatcher(
new AntPathRequestMatcher("/remoting/**"),
new AntPathRequestMatcher("/add-on/*/api/**"),
new AntPathRequestMatcher("/api/**"),
new AntPathRequestMatcher("/cctray.xml")
);
private final HttpServletRequest request;
private final HttpServletResponse response;
private final String jsonMessage;
private final String htmlResponse;
public ServerUnavailabilityResponse(HttpServletRequest request,
HttpServletResponse response,
String jsonMessage,
String htmlResponse) {
this.request = request;
this.response = response;
this.jsonMessage = jsonMessage;
this.htmlResponse = htmlResponse;
}
public void render() {
response.setHeader("Cache-Control", "private, max-age=0, no-cache");
response.setDateHeader("Expires", 0);
if (isAPIRequest(request)) {
generateAPIResponse();
} else {
generateHTMLResponse();
}
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
}
private void generateAPIResponse() {
try {
HttpServletRequest httpRequest = request;
if (requestIsOfType(JSON, httpRequest)) {
response.setContentType("application/json");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("message", jsonMessage);
response.getWriter().print(jsonObject);
} else if (requestIsOfType(XML, httpRequest)) {
response.setContentType("application/xml");
String xml = String.format("<message>%s</message>", StringEscapeUtils.escapeXml11(jsonMessage));
response.getWriter().print(xml);
} else {
generateHTMLResponse();
}
} catch (IOException e) {
LOGGER.error("General IOException: {}", e.getMessage());
}
}
private void generateHTMLResponse() {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
try {
response.getWriter().print(htmlResponse);
} catch (IOException e) {
LOGGER.error("General IOException: {}", e.getMessage());
}
}
private boolean requestIsOfType(String type, HttpServletRequest request) {
String header = request.getHeader("Accept");
String contentType = request.getContentType();
String url = request.getRequestURI();
return header != null && header.contains(type) || url != null && url.endsWith(type) || contentType != null && contentType.contains(type);
}
private boolean isAPIRequest(HttpServletRequest request) {
return API_REQUEST_MATCHER.matches(request);
}
}
| apache-2.0 |
sguisse/InfoWkspOrga | 10-Application/Application/Swing-Sample-APP/src/main/java/com/sgu/infowksporga/jfx/views/file/explorer/action/ClearFilterAction.java | 1823 | package com.sgu.infowksporga.jfx.views.file.explorer.action;
import java.awt.event.ActionEvent;
import com.sgu.apt.annotation.AnnotationConfig;
import com.sgu.apt.annotation.i18n.I18n;
import com.sgu.apt.annotation.i18n.I18nProperty;
import com.sgu.infowksporga.jfx.menu.action.AbstractInfoWrkspOrgaAction;
import com.sgu.infowksporga.jfx.views.file.explorer.FileExplorerView;
import com.sgu.infowksporga.jfx.views.file.explorer.tree.UtilFileTreeFilter;
/**
* The Class ClearFilterAction.
*/
public class ClearFilterAction extends AbstractInfoWrkspOrgaAction {
/**
* The attribute serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* The reference to get the directory tree
*/
private final FileExplorerView fileExplorerView;
/**
* Constructor<br>
*/
@I18n(baseProject = AnnotationConfig.I18N_TARGET_APPLICATION_PROPERTIES_FOLDER, filePackage = "i18n", fileName = "application-prez",
properties = { // Force \n
@I18nProperty(key = "file.explorer.view.action.clear.filter.text", value = "Efface le filtre"), // Force \n
@I18nProperty(key = "file.explorer.view.action.clear.filter.tooltip",
value = "Efface le filtre et ré-affiche l'ensemble du contenu du répertoire sélectionné "), // Force \n
@I18nProperty(key = "file.explorer.view.action.clear.filter.icon", value = "/icons/table/clear-filter.png"), // Force \n
})
public ClearFilterAction(final FileExplorerView fileExplorerView) {
super("file.explorer.view.action.clear.filter");
this.fileExplorerView = fileExplorerView;
}
/** {@inheritDoc} */
@Override
public void actionPerformed(final ActionEvent evts) {
fileExplorerView.getTxtFilter().setText("");
UtilFileTreeFilter.applyFilter(fileExplorerView);
}
} | apache-2.0 |
jgangemi/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java | 6845 | package io.fabric8.maven.docker.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.StringUtils;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import static org.fusesource.jansi.Ansi.Color.*;
import static org.fusesource.jansi.Ansi.ansi;
/**
* Simple log handler for printing used during the maven build
*
* @author roland
* @since 31.03.14
*/
public class AnsiLogger implements Logger {
// prefix used for console output
public static final String DEFAULT_LOG_PREFIX = "DOCKER> ";
private final Log log;
private final String prefix;
private boolean verbose;
// ANSI escapes for various colors (or empty strings if no coloring is used)
private static Ansi.Color
COLOR_ERROR = RED,
COLOR_INFO = GREEN,
COLOR_WARNING = YELLOW,
COLOR_PROGRESS_ID = YELLOW,
COLOR_PROGRESS_STATUS = GREEN,
COLOR_PROGRESS_BAR = CYAN;
// Map remembering lines
private ThreadLocal<Map<String, Integer>> imageLines = new ThreadLocal<Map<String,Integer>>();
// Old image id when used in non ansi mode
private String oldImageId;
// Whether to use ANSI codes
private boolean useAnsi;
public AnsiLogger(Log log, boolean useColor, boolean verbose) {
this(log, useColor, verbose, DEFAULT_LOG_PREFIX);
}
public AnsiLogger(Log log, boolean useColor, boolean verbose, String prefix) {
this.log = log;
this.verbose = verbose;
this.prefix = prefix;
initializeColor(useColor);
}
/** {@inheritDoc} */
public void debug(String message, Object ... params) {
if (isDebugEnabled()) {
log.debug(prefix + String.format(message, params));
}
}
/** {@inheritDoc} */
public void debug(String msg) {
if (isDebugEnabled()) {
debug("%s", msg);
}
}
/** {@inheritDoc} */
public void info(String message, Object ... params) {
log.info(colored(message, COLOR_INFO, true, params));
}
/** {@inheritDoc} */
public void info(String message) {
info("%s", message);
}
/** {@inheritDoc} */
public void verbose(String message, Object ... params) {
if (verbose) {
log.info(ansi().fgBright(BLACK).a(prefix).a(String.format(message,params)).reset().toString());
}
}
/** {@inheritDoc} */
public void warn(String format, Object ... params) {
log.warn(colored(format, COLOR_WARNING, true, params));
}
/** {@inheritDoc} */
public void warn(String message) {
warn("%s", message);
}
/** {@inheritDoc} */
public void error(String message, Object ... params) {
log.error(colored(message, COLOR_ERROR, true, params));
}
/** {@inheritDoc} */
public void error(String message) {
error("%s", message);
}
@Override
public String errorMessage(String message) {
return colored(message, COLOR_ERROR, false);
}
/**
* Whether debugging is enabled.
*/
public boolean isDebugEnabled() {
return log.isDebugEnabled();
}
/**
* Start a progress bar
*/
public void progressStart() {
// A progress indicator is always written out to standard out if a tty is enabled.
if (log.isInfoEnabled()) {
imageLines.remove();
imageLines.set(new HashMap<String, Integer>());
oldImageId = null;
}
}
/**
* Update the progress
*/
public void progressUpdate(String layerId, String status, String progressMessage) {
if (log.isInfoEnabled() && StringUtils.isNotEmpty(layerId)) {
if (useAnsi) {
updateAnsiProgress(layerId, status, progressMessage);
} else {
updateNonAnsiProgress(layerId);
}
flush();
}
}
private void updateAnsiProgress(String imageId, String status, String progressMessage) {
Map<String,Integer> imgLineMap = imageLines.get();
Integer line = imgLineMap.get(imageId);
int diff = 0;
if (line == null) {
line = imgLineMap.size();
imgLineMap.put(imageId, line);
} else {
diff = imgLineMap.size() - line;
}
if (diff > 0) {
print(ansi().cursorUp(diff).eraseLine(Ansi.Erase.ALL).toString());
}
// Status with progress bars: (max length = 11, hence pad to 11)
// Extracting
// Downloading
String progress = progressMessage != null ? progressMessage : "";
String msg =
ansi()
.fg(COLOR_PROGRESS_ID).a(imageId).reset().a(": ")
.fg(COLOR_PROGRESS_STATUS).a(StringUtils.rightPad(status,11) + " ")
.fg(COLOR_PROGRESS_BAR).a(progress).toString();
println(msg);
if (diff > 0) {
// move cursor back down to bottom
print(ansi().cursorDown(diff - 1).toString());
}
}
private void updateNonAnsiProgress(String imageId) {
if (!imageId.equals(oldImageId)) {
print("\n" + imageId + ": .");
oldImageId = imageId;
} else {
print(".");
}
}
/**
* Finis progress meter. Must be always called if {@link #progressStart()} has been used.
*/
public void progressFinished() {
if (log.isInfoEnabled()) {
imageLines.remove();
oldImageId = null;
print(ansi().reset().toString());
if (!useAnsi) {
println("");
}
}
}
private void flush() {
System.out.flush();
}
private void initializeColor(boolean useColor) {
// sl4j simple logger used by Maven seems to escape ANSI escapes on Windows
this.useAnsi = useColor && System.console() != null && !log.isDebugEnabled() && !isWindows();
if (useAnsi) {
AnsiConsole.systemInstall();
Ansi.setEnabled(true);
}
else {
Ansi.setEnabled(false);
}
}
private boolean isWindows() {
String os = System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("windows");
}
private void println(String txt) {
System.out.println(txt);
}
private void print(String txt) {
System.out.print(txt);
}
private String colored(String message, Ansi.Color color, boolean addPrefix, Object ... params) {
Ansi ansi = ansi().fg(color);
if (addPrefix) {
ansi.a(prefix);
}
return ansi.a(String.format(message,params)).reset().toString();
}
}
| apache-2.0 |
devsong/learn | learn-java-basic/src/main/java/com/gzs/learn/patterdesign/structure/adapter/cls/Client.java | 396 | package com.gzs.learn.patterdesign.structure.adapter.cls;
public class Client {
private ObjectLifeCycle objectLifeCycle;
public Client(ObjectLifeCycle objectLifeCycle) {
this.objectLifeCycle = objectLifeCycle;
}
public static void main(String[] args) {
Client client = new Client(new ObjectDestroyListener());
client.objectLifeCycle.destroy();
}
}
| apache-2.0 |
BlucePan/MyBlog | blog/src/com/blog/service/BlogJottingsService.java | 586 | package com.blog.service;
import java.util.List;
import java.util.Map;
import com.blog.model.BlogJottings;
import com.blog.model.BlogMenu;
import com.blog.util.PageView;
public interface BlogJottingsService {
List<BlogJottings> getAllBlogjottings(BlogJottings bJottings);
PageView findByPage(PageView page,Map map);
void addBlogJottings(BlogJottings bJottings);
BlogJottings queryBlogJottingsById(String id);
void updateBlogJottings(BlogJottings bJottings);
void deleteBlogJottings(String id);
List<BlogJottings> findPageByRoll(Map map); //滚动分页加载
}
| apache-2.0 |
vkazhdan/vaadin-crichtextarea | testwidget/src/main/java/vaadin/test/richtext/client/CRichTextAreaConnector.java | 4279 | package vaadin.test.richtext.client;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.RichTextArea;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.Paintable;
import com.vaadin.client.UIDL;
import com.vaadin.client.ui.AbstractFieldConnector;
import com.vaadin.client.ui.ShortcutActionHandler.BeforeShortcutActionListener;
import com.vaadin.shared.ui.Connect;
import com.vaadin.shared.ui.Connect.LoadStyle;
import com.vaadin.shared.util.SharedUtil;
import vaadin.test.richtext.CRichTextArea;
@Connect(value = CRichTextArea.class, loadStyle = LoadStyle.LAZY)
public class CRichTextAreaConnector extends AbstractFieldConnector implements
Paintable, BeforeShortcutActionListener {
private static final vaadin.test.richtext.client.CRichTextArea.FontSize[] fontSizesConstants = new vaadin.test.richtext.client.CRichTextArea.FontSize[] {
vaadin.test.richtext.client.CRichTextArea.FontSize.XX_SMALL, vaadin.test.richtext.client.CRichTextArea.FontSize.X_SMALL,
vaadin.test.richtext.client.CRichTextArea.FontSize.SMALL, vaadin.test.richtext.client.CRichTextArea.FontSize.MEDIUM,
vaadin.test.richtext.client.CRichTextArea.FontSize.LARGE, vaadin.test.richtext.client.CRichTextArea.FontSize.X_LARGE,
vaadin.test.richtext.client.CRichTextArea.FontSize.XX_LARGE };
/*
* Last value received from the server
*/
private String cachedValue = "";
@Override
protected void init() {
getWidget().addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent event) {
flush();
}
});
}
@Override
public void updateFromUIDL(final UIDL uidl, ApplicationConnection client) {
getWidget().client = client;
getWidget().id = uidl.getId();
if (uidl.hasAttribute("fontName")) {
RichTextArea.FontSize fontSize = null;
if (uidl.hasAttribute("fontSize")) {
int fontSizeValue = uidl.getIntAttribute("fontSize");
for (RichTextArea.FontSize fontSizesConstant : fontSizesConstants) {
if (fontSizesConstant.getNumber() == fontSizeValue) {
fontSize = fontSizesConstant;
}
}
}
getWidget().setFont(uidl.getStringAttribute("fontName"), fontSize);
}
if (uidl.hasAttribute("insertHtml")) {
getWidget().insertHtml(uidl.getStringAttribute("insertHtml"));
}
if (uidl.hasVariable("text")) {
String newValue = uidl.getStringVariable("text");
if (!SharedUtil.equals(newValue, cachedValue)) {
getWidget().setValue(newValue);
cachedValue = newValue;
}
}
if (!isRealUpdate(uidl)) {
return;
}
getWidget().setEnabled(isEnabled());
getWidget().setReadOnly(isReadOnly());
getWidget().immediate = getState().immediate;
int newMaxLength = uidl.hasAttribute("maxLength") ? uidl
.getIntAttribute("maxLength") : -1;
if (newMaxLength >= 0) {
if (getWidget().maxLength == -1) {
getWidget().keyPressHandler = getWidget().rta
.addKeyPressHandler(getWidget());
}
getWidget().maxLength = newMaxLength;
} else if (getWidget().maxLength != -1) {
getWidget().getElement().setAttribute("maxlength", "");
getWidget().maxLength = -1;
getWidget().keyPressHandler.removeHandler();
}
if (uidl.hasAttribute("selectAll")) {
getWidget().selectAll();
}
}
@Override
public void onBeforeShortcutAction(Event e) {
flush();
}
@Override
public CVRichTextArea getWidget() {
return (CVRichTextArea) super.getWidget();
}
@Override
public void flush() {
if (getConnection() != null && getConnectorId() != null) {
final String html = getWidget().getSanitizedValue();
if (!html.equals(cachedValue)) {
cachedValue = html;
getConnection().updateVariable(getConnectorId(), "text", html,
getState().immediate);
}
}
};
}
| apache-2.0 |
gavanx/pdflearn | pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java | 50036 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.rendering;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.function.PDFunction;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDVectorFont;
import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased;
import org.apache.pdfbox.pdmodel.graphics.color.PDPattern;
import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationMarkup;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.util.Vector;
/**
* Paints a page in a PDF document to a Graphics context. May be subclassed to provide custom
* rendering.
* <p>
* <p>If you want to do custom graphics processing rather than Graphics2D rendering, then you should
* subclass PDFGraphicsStreamEngine instead. Subclassing PageDrawer is only suitable for cases
* where the goal is to render onto a Graphics2D surface.
*
* @author Ben Litchfield
*/
public class PageDrawer extends PDFGraphicsStreamEngine {
private static final Log LOG = LogFactory.getLog(PageDrawer.class);
// parent document renderer - note: this is needed for not-yet-implemented resource caching
private final PDFRenderer renderer;
// the graphics device to draw to, xform is the initial transform of the device (i.e. DPI)
private Graphics2D graphics;
private AffineTransform xform;
// the page box to draw (usually the crop box but may be another)
private PDRectangle pageSize;
private int pageRotation;
// whether image of a transparency group must be flipped
// needed when in a tiling pattern
private boolean flipTG = false;
// clipping winding rule used for the clipping path
private int clipWindingRule = -1;
private GeneralPath linePath = new GeneralPath();
// last clipping path
private Area lastClip;
// buffered clipping area for text being drawn
private Area textClippingArea;
// glyph caches
private final Map<PDFont, GlyphCache> glyphCaches = new HashMap<PDFont, GlyphCache>();
private final TilingPaintFactory tilingPaintFactory = new TilingPaintFactory(this);
/**
* Constructor.
*
* @param parameters Parameters for page drawing.
* @throws IOException If there is an error loading properties from the file.
*/
public PageDrawer(PageDrawerParameters parameters) throws IOException {
super(parameters.getPage());
this.renderer = parameters.getRenderer();
}
/**
* Returns the parent renderer.
*/
public final PDFRenderer getRenderer() {
return renderer;
}
/**
* Returns the underlying Graphics2D. May be null if drawPage has not yet been called.
*/
protected final Graphics2D getGraphics() {
return graphics;
}
/**
* Returns the current line path. This is reset to empty after each fill/stroke.
*/
protected final GeneralPath getLinePath() {
return linePath;
}
/**
* Sets high-quality rendering hints on the current Graphics2D.
*/
private void setRenderingHints() {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
/**
* Draws the page to the requested context.
*
* @param g The graphics context to draw onto.
* @param pageSize The size of the page to draw.
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException {
graphics = (Graphics2D) g;
xform = graphics.getTransform();
this.pageSize = pageSize;
pageRotation = getPage().getRotation() % 360;
setRenderingHints();
graphics.translate(0, pageSize.getHeight());
graphics.scale(1, -1);
// TODO use getStroke() to set the initial stroke
graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// adjust for non-(0,0) crop box
graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations()) {
showAnnotation(annotation);
}
graphics = null;
}
/**
* Draws the pattern stream to the requested context.
*
* @param g The graphics context to draw onto.
* @param pattern The tiling pattern to be used.
* @param colorSpace color space for this tiling.
* @param color color for this tiling.
* @param patternMatrix the pattern matrix
* @throws IOException If there is an IO error while drawing the page.
*/
void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace, PDColor color, Matrix patternMatrix) throws IOException {
Graphics2D oldGraphics = graphics;
graphics = g;
GeneralPath oldLinePath = linePath;
linePath = new GeneralPath();
int oldClipWindingRule = clipWindingRule;
clipWindingRule = -1;
Area oldLastClip = lastClip;
lastClip = null;
boolean oldFlipTG = flipTG;
flipTG = true;
setRenderingHints();
processTilingPattern(pattern, color, colorSpace, patternMatrix);
flipTG = oldFlipTG;
graphics = oldGraphics;
linePath = oldLinePath;
lastClip = oldLastClip;
clipWindingRule = oldClipWindingRule;
}
private float clampColor(float color) {
return color < 0 ? 0 : (color > 1 ? 1 : color);
}
/**
* Returns an AWT paint for the given PDColor.
*
* @param color The color to get a paint for. This can be an actual color or a pattern.
* @throws IOException
*/
protected Paint getPaint(PDColor color) throws IOException {
PDColorSpace colorSpace = color.getColorSpace();
if (!(colorSpace instanceof PDPattern)) {
float[] rgb = colorSpace.toRGB(color.getComponents());
return new Color(clampColor(rgb[0]), clampColor(rgb[1]), clampColor(rgb[2]));
} else {
PDPattern patternSpace = (PDPattern) colorSpace;
PDAbstractPattern pattern = patternSpace.getPattern(color);
if (pattern instanceof PDTilingPattern) {
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED) {
// colored tiling pattern
return tilingPaintFactory.create(tilingPattern, null, null, xform);
} else {
// uncolored tiling pattern
return tilingPaintFactory.create(tilingPattern, patternSpace.getUnderlyingColorSpace(), color, xform);
}
} else {
PDShadingPattern shadingPattern = (PDShadingPattern) pattern;
PDShading shading = shadingPattern.getShading();
if (shading == null) {
LOG.error("shadingPattern is null, will be filled with transparency");
return new Color(0, 0, 0, 0);
}
return shading.toPaint(Matrix.concatenate(getInitialMatrix(), shadingPattern.getMatrix()));
}
}
}
// sets the clipping path using caching for performance, we track lastClip manually because
// Graphics2D#getClip() returns a new object instead of the same one passed to setClip
private void setClip() {
Area clippingPath = getGraphicsState().getCurrentClippingPath();
if (clippingPath != lastClip) {
graphics.setClip(clippingPath);
lastClip = clippingPath;
}
}
@Override
public void beginText() throws IOException {
setClip();
beginTextClip();
}
@Override
public void endText() throws IOException {
endTextClip();
}
/**
* Begin buffering the text clipping path, if any.
*/
private void beginTextClip() {
// buffer the text clip because it represents a single clipping area
textClippingArea = new Area();
}
/**
* End buffering the text clipping path, if any.
*/
private void endTextClip() {
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
// apply the buffered clip as one area
if (renderingMode.isClip() && !textClippingArea.isEmpty()) {
state.intersectClippingPath(textClippingArea);
textClippingArea = null;
// PDFBOX-3681: lastClip needs to be reset, because after intersection it is still the same
// object, thus setClip() would believe that it is cached.
lastClip = null;
}
}
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode, Vector displacement) throws IOException {
AffineTransform at = textRenderingMatrix.createAffineTransform();
at.concatenate(font.getFontMatrix().createAffineTransform());
// create cache if it does not exist
PDVectorFont vectorFont = ((PDVectorFont) font);
GlyphCache cache = glyphCaches.get(font);
if (cache == null) {
cache = new GlyphCache(vectorFont);
glyphCaches.put(font, cache);
}
GeneralPath path = cache.getPathForCharacterCode(code);
drawGlyph(path, font, code, displacement, at);
}
/**
* Renders a glyph.
*
* @param path the GeneralPath for the glyph
* @param font the font
* @param code character code
* @param displacement the glyph's displacement (advance)
* @param at the transformation
* @throws IOException if something went wrong
*/
private void drawGlyph(GeneralPath path, PDFont font, int code, Vector displacement, AffineTransform at) throws IOException {
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
if (path != null) {
// stretch non-embedded glyph if it does not match the width contained in the PDF
if (!font.isEmbedded()) {
float fontWidth = font.getWidthFromFont(code);
if (fontWidth > 0 && // ignore spaces
Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001) {
float pdfWidth = displacement.getX() * 1000;
at.scale(pdfWidth / fontWidth, 1);
}
}
// render glyph
Shape glyph = at.createTransformedShape(path);
if (renderingMode.isFill()) {
graphics.setComposite(state.getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
graphics.fill(glyph);
}
if (renderingMode.isStroke()) {
graphics.setComposite(state.getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(glyph);
}
if (renderingMode.isClip()) {
textClippingArea.add(new Area(glyph));
}
}
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3) {
// to ensure that the path is created in the right direction, we have to create
// it by combining single lines instead of creating a simple rectangle
linePath.moveTo((float) p0.getX(), (float) p0.getY());
linePath.lineTo((float) p1.getX(), (float) p1.getY());
linePath.lineTo((float) p2.getX(), (float) p2.getY());
linePath.lineTo((float) p3.getX(), (float) p3.getY());
// close the subpath instead of adding the last line so that a possible set line
// cap style isn't taken into account at the "beginning" of the rectangle
linePath.closePath();
}
//TODO: move soft mask apply to getPaint()?
private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException {
if (softMask == null || softMask.getGroup() == null) {
return parentPaint;
}
PDColor backdropColor = null;
if (COSName.LUMINOSITY.equals(softMask.getSubType())) {
COSArray backdropColorArray = softMask.getBackdropColor();
PDColorSpace colorSpace = softMask.getGroup().getGroup().getColorSpace();
if (colorSpace != null && backdropColorArray != null) {
backdropColor = new PDColor(backdropColorArray, colorSpace);
}
}
TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true, softMask.getInitialTransformationMatrix(), backdropColor);
BufferedImage image = transparencyGroup.getImage();
if (image == null) {
// Adobe Reader ignores empty softmasks instead of using bc color
// sample file: PDFJS-6967_reduced_outside_softmask.pdf
return parentPaint;
}
BufferedImage gray = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
if (COSName.ALPHA.equals(softMask.getSubType())) {
gray.setData(image.getAlphaRaster());
} else if (COSName.LUMINOSITY.equals(softMask.getSubType())) {
Graphics g = gray.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
} else {
throw new IOException("Invalid soft mask subtype.");
}
gray = getRotatedImage(gray);
Rectangle2D tpgBounds = transparencyGroup.getBounds();
adjustRectangle(tpgBounds);
return new SoftMask(parentPaint, gray, tpgBounds, backdropColor, softMask.getTransferFunction());
}
// this adjusts the rectangle to the rotated image to put the soft mask at the correct position
//TODO after all transparency problems have been solved:
// 1. shouldn't this be done in transparencyGroup.getBounds() ?
// 2. change transparencyGroup.getBounds() to getOrigin(), because size isn't used in SoftMask
// 3. Is it possible to create the softmask and transparency group in the correct rotation?
// (needs rendering identity testing before committing!)
private void adjustRectangle(Rectangle2D r) {
Matrix m = new Matrix(xform);
if (pageRotation == 90) {
r.setRect(pageSize.getHeight() * m.getScalingFactorY() - r.getY() - r.getHeight(), r.getX(), r.getWidth(), r.getHeight());
}
if (pageRotation == 180) {
r.setRect(pageSize.getWidth() * m.getScalingFactorX() - r.getX() - r.getWidth(), pageSize.getHeight() * m.getScalingFactorY() - r.getY() - r.getHeight(), r.getWidth(), r.getHeight());
}
if (pageRotation == 270) {
r.setRect(r.getY(), pageSize.getWidth() * m.getScalingFactorX() - r.getX() - r.getWidth(), r.getWidth(), r.getHeight());
}
}
// return quadrant-rotated image with adjusted size
private BufferedImage getRotatedImage(BufferedImage gray) throws IOException {
BufferedImage gray2;
AffineTransform at;
switch (pageRotation % 360) {
case 90:
gray2 = new BufferedImage(gray.getHeight(), gray.getWidth(), BufferedImage.TYPE_BYTE_GRAY);
at = AffineTransform.getQuadrantRotateInstance(1, gray.getHeight() / 2d, gray.getHeight() / 2d);
break;
case 180:
gray2 = new BufferedImage(gray.getWidth(), gray.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
at = AffineTransform.getQuadrantRotateInstance(2, gray.getWidth() / 2d, gray.getHeight() / 2d);
break;
case 270:
gray2 = new BufferedImage(gray.getHeight(), gray.getWidth(), BufferedImage.TYPE_BYTE_GRAY);
at = AffineTransform.getQuadrantRotateInstance(3, gray.getWidth() / 2d, gray.getWidth() / 2d);
break;
default:
return gray;
}
Graphics2D g2 = (Graphics2D) gray2.getGraphics();
g2.drawImage(gray, at, null);
g2.dispose();
return gray2;
}
// returns the stroking AWT Paint
private Paint getStrokingPaint() throws IOException {
return applySoftMaskToPaint(getPaint(getGraphicsState().getStrokingColor()), getGraphicsState().getSoftMask());
}
// returns the non-stroking AWT Paint
private Paint getNonStrokingPaint() throws IOException {
return applySoftMaskToPaint(getPaint(getGraphicsState().getNonStrokingColor()), getGraphicsState().getSoftMask());
}
// create a new stroke based on the current CTM and the current stroke
private BasicStroke getStroke() {
PDGraphicsState state = getGraphicsState();
// apply the CTM
float lineWidth = transformWidth(state.getLineWidth());
// minimum line width as used by Adobe Reader
if (lineWidth < 0.25) {
lineWidth = 0.25f;
}
PDLineDashPattern dashPattern = state.getLineDashPattern();
int phaseStart = dashPattern.getPhase();
float[] dashArray = dashPattern.getDashArray();
if (dashArray != null) {
// apply the CTM
for (int i = 0; i < dashArray.length; ++i) {
// minimum line dash width avoids JVM crash, see PDFBOX-2373, PDFBOX-2929, PDFBOX-3204
// also avoid 0 in array like "[ 0 1000 ] 0 d", see PDFBOX-3724
float w = transformWidth(dashArray[i]);
dashArray[i] = Math.max(w, 0.035f);
}
phaseStart = (int) transformWidth(phaseStart);
// empty dash array is illegal
// avoid also infinite and NaN values (PDFBOX-3360)
if (dashArray.length == 0 || Float.isInfinite(phaseStart) || Float.isNaN(phaseStart)) {
dashArray = null;
} else {
for (int i = 0; i < dashArray.length; ++i) {
if (Float.isInfinite(dashArray[i]) || Float.isNaN(dashArray[i])) {
dashArray = null;
break;
}
}
}
}
return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(), state.getMiterLimit(), dashArray, phaseStart);
}
@Override
public void strokePath() throws IOException {
graphics.setComposite(getGraphicsState().getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
//TODO bbox of shading pattern should be used here? (see fillPath)
graphics.draw(linePath);
linePath.reset();
}
@Override
public void fillPath(int windingRule) throws IOException {
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
linePath.setWindingRule(windingRule);
// disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
// which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
// note that we ignore paths with a width/height under 1 as these are fills used as strokes,
// see PDFBOX-1658 for an example
Rectangle2D bounds = linePath.getBounds2D();
boolean noAntiAlias = isRectangular(linePath) && bounds.getWidth() > 1 && bounds.getHeight() > 1;
if (noAntiAlias) {
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
}
if (!(graphics.getPaint() instanceof Color)) {
// apply clip to path to avoid oversized device bounds in shading contexts (PDFBOX-2901)
Area area = new Area(linePath);
area.intersect(new Area(graphics.getClip()));
intersectShadingBBox(getGraphicsState().getNonStrokingColor(), area);
graphics.fill(area);
} else {
graphics.fill(linePath);
}
linePath.reset();
if (noAntiAlias) {
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
// checks whether this is a shading pattern and if yes,
// get the transformed BBox and intersect with current paint area
// need to do it here and not in shading getRaster() because it may have been rotated
private void intersectShadingBBox(PDColor color, Area area) throws IOException {
if (color.getColorSpace() instanceof PDPattern) {
PDColorSpace colorSpace = color.getColorSpace();
PDAbstractPattern pat = ((PDPattern) colorSpace).getPattern(color);
if (pat instanceof PDShadingPattern) {
PDShading shading = ((PDShadingPattern) pat).getShading();
PDRectangle bbox = shading.getBBox();
if (bbox != null) {
Matrix m = Matrix.concatenate(getInitialMatrix(), pat.getMatrix());
Area bboxArea = new Area(bbox.transform(m));
area.intersect(bboxArea);
}
}
}
}
/**
* Returns true if the given path is rectangular.
*/
private boolean isRectangular(GeneralPath path) {
PathIterator iter = path.getPathIterator(null);
double[] coords = new double[6];
int count = 0;
int[] xs = new int[4];
int[] ys = new int[4];
while (!iter.isDone()) {
switch (iter.currentSegment(coords)) {
case PathIterator.SEG_MOVETO:
if (count == 0) {
xs[count] = (int) Math.floor(coords[0]);
ys[count] = (int) Math.floor(coords[1]);
} else {
return false;
}
count++;
break;
case PathIterator.SEG_LINETO:
if (count < 4) {
xs[count] = (int) Math.floor(coords[0]);
ys[count] = (int) Math.floor(coords[1]);
} else {
return false;
}
count++;
break;
case PathIterator.SEG_CUBICTO:
return false;
case PathIterator.SEG_CLOSE:
break;
}
iter.next();
}
if (count == 4) {
return xs[0] == xs[1] || xs[0] == xs[2] || ys[0] == ys[1] || ys[0] == ys[3];
}
return false;
}
/**
* Fills and then strokes the path.
*
* @param windingRule The winding rule this path will use.
* @throws IOException If there is an IO error while filling the path.
*/
@Override
public void fillAndStrokePath(int windingRule) throws IOException {
// TODO can we avoid cloning the path?
GeneralPath path = (GeneralPath) linePath.clone();
fillPath(windingRule);
linePath = path;
strokePath();
}
@Override
public void clip(int windingRule) {
// the clipping path will not be updated until the succeeding painting operator is called
clipWindingRule = windingRule;
}
@Override
public void moveTo(float x, float y) {
linePath.moveTo(x, y);
}
@Override
public void lineTo(float x, float y) {
linePath.lineTo(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3) {
linePath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public Point2D getCurrentPoint() {
return linePath.getCurrentPoint();
}
@Override
public void closePath() {
linePath.closePath();
}
@Override
public void endPath() {
if (clipWindingRule != -1) {
linePath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(linePath);
clipWindingRule = -1;
}
linePath.reset();
}
@Override
public void drawImage(PDImage pdImage) throws IOException {
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
AffineTransform at = ctm.createAffineTransform();
if (!pdImage.getInterpolate()) {
boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) || pdImage.getHeight() < Math.round(at.getScaleY());
// if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
// only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
// stencils are excluded from this rule (see survey.pdf)
if (isScaledUp || pdImage.isStencil()) {
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
}
if (pdImage.isStencil()) {
if (getGraphicsState().getNonStrokingColor().getColorSpace() instanceof PDPattern) {
// The earlier code for stencils (see "else") doesn't work with patterns because the
// CTM is not taken into consideration.
// this code is based on the fact that it is easily possible to draw the mask and
// the paint at the correct place with the existing code, but not in one step.
// Thus what we do is to draw both in separate images, then combine the two and draw
// the result.
// Note that the device scale is not used. In theory, some patterns can get better
// at higher resolutions but the stencil would become more and more "blocky".
// If anybody wants to do this, have a look at the code in showTransparencyGroup().
// draw the paint
Paint paint = getNonStrokingPaint();
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
Rectangle2D bounds = at.createTransformedShape(unitRect).getBounds2D();
BufferedImage renderedPaint = new BufferedImage((int) Math.ceil(bounds.getWidth()), (int) Math.ceil(bounds.getHeight()), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) renderedPaint.getGraphics();
g.translate(-bounds.getMinX(), -bounds.getMinY());
g.setPaint(paint);
g.fill(bounds);
g.dispose();
// draw the mask
BufferedImage mask = pdImage.getImage();
BufferedImage renderedMask = new BufferedImage((int) Math.ceil(bounds.getWidth()), (int) Math.ceil(bounds.getHeight()), BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) renderedMask.getGraphics();
g.translate(-bounds.getMinX(), -bounds.getMinY());
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / mask.getWidth(), -1.0 / mask.getHeight());
imageTransform.translate(0, -mask.getHeight());
g.drawImage(mask, imageTransform, null);
g.dispose();
// apply the mask
final int[] transparent = new int[4];
int[] alphaPixel = null;
WritableRaster raster = renderedPaint.getRaster();
WritableRaster alpha = renderedMask.getRaster();
int h = renderedMask.getRaster().getHeight();
int w = renderedMask.getRaster().getWidth();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
alphaPixel = alpha.getPixel(x, y, alphaPixel);
if (alphaPixel[0] == 255) {
raster.setPixel(x, y, transparent);
}
}
}
// draw the image
setClip();
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.drawImage(renderedPaint, AffineTransform.getTranslateInstance(bounds.getMinX(), bounds.getMinY()), null);
} else {
// fill the image with stenciled paint
BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint());
// draw the image
drawBufferedImage(image, at);
}
} else {
// draw the image
drawBufferedImage(pdImage.getImage(), at);
}
if (!pdImage.getInterpolate()) {
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null) {
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1, -1);
imageTransform.translate(0, -1);
Paint awtPaint = new TexturePaint(image, new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(), imageTransform.getScaleX(), imageTransform.getScaleY()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
graphics.fill(at.createTransformedShape(unitRect));
} else {
COSBase transfer = getGraphicsState().getTransfer();
if (transfer instanceof COSArray || transfer instanceof COSDictionary) {
image = applyTransferFunction(image, transfer);
}
int width = image.getWidth(null);
int height = image.getHeight(null);
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / width, -1.0 / height);
imageTransform.translate(0, -height);
graphics.drawImage(image, imageTransform, null);
}
}
private BufferedImage applyTransferFunction(BufferedImage image, COSBase transfer) throws IOException {
BufferedImage bim;
if (image.getColorModel().hasAlpha()) {
bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
} else {
bim = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
}
// prepare transfer functions (either one per color or one for all)
// and maps (actually arrays[256] to be faster) to avoid calculating values several times
Integer rMap[], gMap[], bMap[];
PDFunction rf, gf, bf;
if (transfer instanceof COSArray) {
COSArray ar = (COSArray) transfer;
rf = PDFunction.create(ar.getObject(0));
gf = PDFunction.create(ar.getObject(1));
bf = PDFunction.create(ar.getObject(2));
rMap = new Integer[256];
gMap = new Integer[256];
bMap = new Integer[256];
} else {
rf = PDFunction.create(transfer);
gf = rf;
bf = rf;
rMap = new Integer[256];
gMap = rMap;
bMap = rMap;
}
// apply the transfer function to each color, but keep alpha
float[] input = new float[1];
for (int x = 0; x < image.getWidth(); ++x) {
for (int y = 0; y < image.getHeight(); ++y) {
int rgb = image.getRGB(x, y);
int ri = (rgb >> 16) & 0xFF;
int gi = (rgb >> 8) & 0xFF;
int bi = rgb & 0xFF;
int ro, go, bo;
if (rMap[ri] != null) {
ro = rMap[ri];
} else {
input[0] = (ri & 0xFF) / 255f;
ro = (int) (rf.eval(input)[0] * 255);
rMap[ri] = ro;
}
if (gMap[gi] != null) {
go = gMap[gi];
} else {
input[0] = (gi & 0xFF) / 255f;
go = (int) (gf.eval(input)[0] * 255);
gMap[gi] = go;
}
if (bMap[bi] != null) {
bo = bMap[bi];
} else {
input[0] = (bi & 0xFF) / 255f;
bo = (int) (bf.eval(input)[0] * 255);
bMap[bi] = bo;
}
bim.setRGB(x, y, (rgb & 0xFF000000) | (ro << 16) | (go << 8) | bo);
}
}
return bim;
}
@Override
public void shadingFill(COSName shadingName) throws IOException {
PDShading shading = getResources().getShading(shadingName);
if (shading == null) {
LOG.error("shading " + shadingName + " does not exist in resources dictionary");
return;
}
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Paint paint = shading.toPaint(ctm);
paint = applySoftMaskToPaint(paint, getGraphicsState().getSoftMask());
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(paint);
graphics.setClip(null);
lastClip = null;
// get the transformed BBox and intersect with current clipping path
// need to do it here and not in shading getRaster() because it may have been rotated
PDRectangle bbox = shading.getBBox();
if (bbox != null) {
Area bboxArea = new Area(bbox.transform(ctm));
bboxArea.intersect(getGraphicsState().getCurrentClippingPath());
graphics.fill(bboxArea);
} else {
graphics.fill(getGraphicsState().getCurrentClippingPath());
}
}
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException {
lastClip = null;
//TODO support more annotation flags (Invisible, NoZoom, NoRotate)
// Example for NoZoom can be found in p5 of PDFBOX-2348
int deviceType = graphics.getDeviceConfiguration().getDevice().getType();
if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted()) {
return;
}
if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView()) {
return;
}
if (annotation.isHidden()) {
return;
}
super.showAnnotation(annotation);
if (annotation.getAppearance() == null) {
if (annotation instanceof PDAnnotationLink) {
drawAnnotationLinkBorder((PDAnnotationLink) annotation);
}
if (annotation instanceof PDAnnotationMarkup && annotation.getSubtype().equals(PDAnnotationMarkup.SUB_TYPE_INK)) {
drawAnnotationInk((PDAnnotationMarkup) annotation);
}
}
}
// return border info. BorderStyle must be provided as parameter because
// method is not available in the base class
private AnnotationBorder getAnnotationBorder(PDAnnotation annotation, PDBorderStyleDictionary borderStyle) {
AnnotationBorder ab = new AnnotationBorder();
COSArray border = annotation.getBorder();
if (borderStyle == null) {
if (border.get(2) instanceof COSNumber) {
ab.width = ((COSNumber) border.getObject(2)).floatValue();
}
if (border.size() > 3) {
COSBase base3 = border.getObject(3);
if (base3 instanceof COSArray) {
ab.dashArray = ((COSArray) base3).toFloatArray();
}
}
} else {
ab.width = borderStyle.getWidth();
if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_DASHED)) {
ab.dashArray = borderStyle.getDashStyle().getDashArray();
}
if (borderStyle.getStyle().equals(PDBorderStyleDictionary.STYLE_UNDERLINE)) {
ab.underline = true;
}
}
ab.color = annotation.getColor();
if (ab.color == null) {
// spec is unclear, but black seems to be the right thing to do
ab.color = new PDColor(new float[]{0}, PDDeviceGray.INSTANCE);
}
if (ab.dashArray != null) {
boolean allZero = true;
for (float f : ab.dashArray) {
if (f != 0) {
allZero = false;
break;
}
}
if (allZero) {
ab.dashArray = null;
}
}
return ab;
}
private void drawAnnotationLinkBorder(PDAnnotationLink link) throws IOException {
AnnotationBorder ab = getAnnotationBorder(link, link.getBorderStyle());
if (ab.width == 0 || ab.color.getComponents().length == 0) {
return;
}
PDRectangle rectangle = link.getRectangle();
Stroke oldStroke = graphics.getStroke();
graphics.setPaint(getPaint(ab.color));
BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0);
graphics.setStroke(stroke);
graphics.setClip(null);
if (ab.underline) {
graphics.drawLine((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) (rectangle.getLowerLeftX() + rectangle.getWidth()), (int) rectangle.getLowerLeftY());
} else {
graphics.drawRect((int) rectangle.getLowerLeftX(), (int) rectangle.getLowerLeftY(), (int) rectangle.getWidth(), (int) rectangle.getHeight());
}
graphics.setStroke(oldStroke);
}
private void drawAnnotationInk(PDAnnotationMarkup inkAnnotation) throws IOException {
if (!inkAnnotation.getCOSObject().containsKey(COSName.INKLIST)) {
return;
}
//TODO there should be an InkAnnotation class with a getInkList method
COSBase base = inkAnnotation.getCOSObject().getDictionaryObject(COSName.INKLIST);
if (!(base instanceof COSArray)) {
return;
}
// PDF spec does not mention /Border for ink annotations, but it is used if /BS is not available
AnnotationBorder ab = getAnnotationBorder(inkAnnotation, inkAnnotation.getBorderStyle());
if (ab.width == 0 || ab.color.getComponents().length == 0) {
return;
}
graphics.setPaint(getPaint(ab.color));
Stroke oldStroke = graphics.getStroke();
BasicStroke stroke = new BasicStroke(ab.width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, ab.dashArray, 0);
graphics.setStroke(stroke);
graphics.setClip(null);
COSArray pathsArray = (COSArray) base;
for (COSBase baseElement : pathsArray) {
if (!(baseElement instanceof COSArray)) {
continue;
}
COSArray pathArray = (COSArray) baseElement;
int nPoints = pathArray.size() / 2;
// "When drawn, the points shall be connected by straight lines or curves
// in an implementation-dependent way" - we do lines.
GeneralPath path = new GeneralPath();
for (int i = 0; i < nPoints; ++i) {
COSBase bx = pathArray.getObject(i * 2);
COSBase by = pathArray.getObject(i * 2 + 1);
if (bx instanceof COSNumber && by instanceof COSNumber) {
float x = ((COSNumber) bx).floatValue();
float y = ((COSNumber) by).floatValue();
if (i == 0) {
path.moveTo(x, y);
} else {
path.lineTo(x, y);
}
}
}
graphics.draw(path);
}
graphics.setStroke(oldStroke);
}
@Override
public void showTransparencyGroup(PDTransparencyGroup form) throws IOException {
TransparencyGroup group = new TransparencyGroup(form, false, getGraphicsState().getCurrentTransformationMatrix(), null);
BufferedImage image = group.getImage();
if (image == null) {
// image is empty, don't bother
return;
}
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
// both the DPI xform and the CTM were already applied to the group, so all we do
// here is draw it directly onto the Graphics2D device at the appropriate position
PDRectangle bbox = group.getBBox();
AffineTransform prev = graphics.getTransform();
Matrix m = new Matrix(xform);
float xScale = Math.abs(m.getScalingFactorX());
float yScale = Math.abs(m.getScalingFactorY());
// adjust the initial translation (includes the translation used to "help" the rotation)
graphics.setTransform(AffineTransform.getTranslateInstance(xform.getTranslateX(), xform.getTranslateY()));
graphics.rotate(Math.toRadians(pageRotation));
// adjust bbox (x,y) position at the initial scale + cropbox
float x = bbox.getLowerLeftX() - pageSize.getLowerLeftX();
float y = pageSize.getUpperRightY() - bbox.getUpperRightY();
graphics.translate(x * xScale, y * yScale);
if (flipTG) {
graphics.translate(0, image.getHeight());
graphics.scale(1, -1);
}
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null) {
Paint awtPaint = new TexturePaint(image, new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * xScale, bbox.getHeight() * yScale));
} else {
graphics.drawImage(image, null, null);
}
graphics.setTransform(prev);
}
private static class AnnotationBorder {
private float[] dashArray = null;
private boolean underline = false;
private float width = 0;
private PDColor color;
}
/**
* Transparency group.
**/
private final class TransparencyGroup {
private final BufferedImage image;
private final PDRectangle bbox;
private final int minX;
private final int minY;
private final int width;
private final int height;
/**
* Creates a buffered image for a transparency group result.
*
* @param form the transparency group of the form or soft mask.
* @param isSoftMask true if this is a soft mask.
* @param ctm the relevant current transformation matrix. For soft masks, this is the CTM at
* the time the soft mask is set (not at the time the soft mask is used for fill/stroke!),
* for forms, this is the CTM at the time the form is invoked.
* @param backdropColor the color according to the /bc entry to be used for luminosity soft
* masks.
* @throws IOException
*/
private TransparencyGroup(PDTransparencyGroup form, boolean isSoftMask, Matrix ctm, PDColor backdropColor) throws IOException {
Graphics2D g2dOriginal = graphics;
Area lastClipOriginal = lastClip;
// get the CTM x Form Matrix transform
Matrix transform = Matrix.concatenate(ctm, form.getMatrix());
// transform the bbox
GeneralPath transformedBox = form.getBBox().transform(transform);
// clip the bbox to prevent giant bboxes from consuming all memory
Area clip = (Area) getGraphicsState().getCurrentClippingPath().clone();
clip.intersect(new Area(transformedBox));
Rectangle2D clipRect = clip.getBounds2D();
if (clipRect.isEmpty()) {
image = null;
bbox = null;
minX = 0;
minY = 0;
width = 0;
height = 0;
return;
}
this.bbox = new PDRectangle((float) clipRect.getX(), (float) clipRect.getY(), (float) clipRect.getWidth(), (float) clipRect.getHeight());
// apply the underlying Graphics2D device's DPI transform
Matrix m = new Matrix(xform);
AffineTransform dpiTransform = AffineTransform.getScaleInstance(Math.abs(m.getScalingFactorX()), Math.abs(m.getScalingFactorY()));
Rectangle2D bounds = dpiTransform.createTransformedShape(clip.getBounds2D()).getBounds2D();
minX = (int) Math.floor(bounds.getMinX());
minY = (int) Math.floor(bounds.getMinY());
int maxX = (int) Math.floor(bounds.getMaxX()) + 1;
int maxY = (int) Math.floor(bounds.getMaxY()) + 1;
width = maxX - minX;
height = maxY - minY;
// FIXME - color space
if (isGray(form.getGroup().getColorSpace())) {
image = create2ByteGrayAlphaImage(width, height);
} else {
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
Graphics2D g = image.createGraphics();
if (isSoftMask && backdropColor != null) {
// "If the subtype is Luminosity, the transparency group XObject G shall be
// composited with a fully opaque backdrop whose colour is everywhere defined
// by the soft-mask dictionary's BC entry."
g.setBackground(new Color(backdropColor.toRGB()));
g.clearRect(0, 0, width, height);
}
// flip y-axis
g.translate(0, image.getHeight());
g.scale(1, -1);
boolean oldFlipTG = flipTG;
flipTG = false;
// apply device transform (DPI)
// the initial translation is ignored, because we're not writing into the initial graphics device
g.transform(dpiTransform);
AffineTransform xformOriginal = xform;
xform = AffineTransform.getScaleInstance(m.getScalingFactorX(), m.getScalingFactorY());
PDRectangle pageSizeOriginal = pageSize;
pageSize = new PDRectangle(minX / Math.abs(m.getScalingFactorX()), minY / Math.abs(m.getScalingFactorY()), (float) bounds.getWidth() / Math.abs(m.getScalingFactorX()), (float) bounds.getHeight() / Math.abs(m.getScalingFactorY()));
int pageRotationOriginal = pageRotation;
pageRotation = 0;
int clipWindingRuleOriginal = clipWindingRule;
clipWindingRule = -1;
GeneralPath linePathOriginal = linePath;
linePath = new GeneralPath();
// adjust the origin
g.translate(-clipRect.getX(), -clipRect.getY());
graphics = g;
setRenderingHints();
try {
if (isSoftMask) {
processSoftMask(form);
} else {
processTransparencyGroup(form);
}
} finally {
flipTG = oldFlipTG;
lastClip = lastClipOriginal;
graphics.dispose();
graphics = g2dOriginal;
clipWindingRule = clipWindingRuleOriginal;
linePath = linePathOriginal;
pageSize = pageSizeOriginal;
xform = xformOriginal;
pageRotation = pageRotationOriginal;
}
}
// http://stackoverflow.com/a/21181943/535646
private BufferedImage create2ByteGrayAlphaImage(int width, int height) {
/**
* gray + alpha
*/
int[] bandOffsets = new int[]{1, 0};
int bands = bandOffsets.length;
/**
* Color Model usesd for raw GRAY + ALPHA
*/
final ColorModel CM_GRAY_ALPHA = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY), true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE);
// Init data buffer of type byte
DataBuffer buffer = new DataBufferByte(width * height * bands);
// Wrap the data buffer in a raster
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, width * bands, bands, bandOffsets, new Point(0, 0));
// Create a custom BufferedImage with the raster and a suitable color model
return new BufferedImage(CM_GRAY_ALPHA, raster, false, null);
}
private boolean isGray(PDColorSpace colorSpace) {
if (colorSpace instanceof PDDeviceGray) {
return true;
}
if (colorSpace instanceof PDICCBased) {
try {
return ((PDICCBased) colorSpace).getAlternateColorSpace() instanceof PDDeviceGray;
} catch (IOException ex) {
return false;
}
}
return false;
}
public BufferedImage getImage() {
return image;
}
public PDRectangle getBBox() {
return bbox;
}
public Rectangle2D getBounds() {
Point2D size = new Point2D.Double(pageSize.getWidth(), pageSize.getHeight());
// apply the underlying Graphics2D device's DPI transform and y-axis flip
Matrix m = new Matrix(xform);
AffineTransform dpiTransform = AffineTransform.getScaleInstance(Math.abs(m.getScalingFactorX()), Math.abs(m.getScalingFactorY()));
size = dpiTransform.transform(size, size);
// Flip y
return new Rectangle2D.Double(minX - pageSize.getLowerLeftX() * m.getScalingFactorX(), size.getY() - minY - height + pageSize.getLowerLeftY() * m.getScalingFactorY(), width, height);
}
}
}
| apache-2.0 |
dragonzhou/humor | src/strategy/Strategy.java | 96 | package strategy;
public abstract class Strategy {
public abstract void exceuteStrategy();
}
| apache-2.0 |
dlaboss/streamsx.topology | java/src/com/ibm/streamsx/topology/internal/streams/InvokeCancel.java | 1466 | /*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015
*/
package com.ibm.streamsx.topology.internal.streams;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.internal.process.ProcessOutputToLogger;
public class InvokeCancel {
static final Logger trace = Topology.STREAMS_LOGGER;
private final BigInteger jobId;
public InvokeCancel(BigInteger jobId) {
super();
this.jobId = jobId;
}
public void invoke() throws Exception, InterruptedException {
String si = Util.getStreamsInstall();
File sj = new File(si, "bin/streamtool");
Util.checkInvokeStreamtoolPreconditions();
List<String> commands = new ArrayList<String>();
commands.add(sj.getAbsolutePath());
commands.add("canceljob");
commands.add(jobId.toString());
trace.info("Invoking streamtool canceljob " + jobId);
ProcessBuilder pb = new ProcessBuilder(commands);
Process sjProcess = pb.start();
ProcessOutputToLogger.log(trace, sjProcess);
sjProcess.getOutputStream().close();
int rc = sjProcess.waitFor();
trace.info("streamtool canceljob complete: return code=" + rc);
if (rc != 0)
throw new Exception("streamtool canceljob failed!");
}
}
| apache-2.0 |
rylangooch/twu-biblioteca-rylangooch | test/com/twu/biblioteca/BibliotecaAppTest.java | 596 | package com.twu.biblioteca;
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.assertEquals;
import java.io.*;
public class BibliotecaAppTest {
BibliotecaApp app = new BibliotecaApp();
private final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
@Before
public void setUp() {
System.setOut(new PrintStream(myOut));
}
@Test
public void welcomeMessageTest() {
app.welcomeMessage();
String welcome = "Welcome to The Bangalore Public Library\n";
assertEquals(welcome, myOut.toString());
}
}
| apache-2.0 |
dbelokursky/dbelokursky | chapter_005/src/test/java/ru/job4j/tree/SimpleBSTTest.java | 483 | package ru.job4j.tree;
import org.junit.Test;
/**
* @author Dmitry Belokursky
* @since 26.11.17.
*/
public class SimpleBSTTest {
@Test
public void add() throws Exception {
SimpleBST simpleBST = new SimpleBST();
simpleBST.add(10);
simpleBST.add(2);
System.out.println(simpleBST.hasNext());
System.out.println(simpleBST.next());
System.out.println(simpleBST.next());
System.out.println(simpleBST.hasNext());
}
} | apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/RecognizeCelebritiesResult.java | 21410 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.rekognition.model;
import java.io.Serializable;
import javax.annotation.Generated;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RecognizeCelebritiesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities in an
* image.
* </p>
*/
private java.util.List<Celebrity> celebrityFaces;
/**
* <p>
* Details about each unrecognized face in the image.
* </p>
*/
private java.util.List<ComparedFace> unrecognizedFaces;
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*/
private String orientationCorrection;
/**
* <p>
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities in an
* image.
* </p>
*
* @return Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15
* celebrities in an image.
*/
public java.util.List<Celebrity> getCelebrityFaces() {
return celebrityFaces;
}
/**
* <p>
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities in an
* image.
* </p>
*
* @param celebrityFaces
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities
* in an image.
*/
public void setCelebrityFaces(java.util.Collection<Celebrity> celebrityFaces) {
if (celebrityFaces == null) {
this.celebrityFaces = null;
return;
}
this.celebrityFaces = new java.util.ArrayList<Celebrity>(celebrityFaces);
}
/**
* <p>
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities in an
* image.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setCelebrityFaces(java.util.Collection)} or {@link #withCelebrityFaces(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param celebrityFaces
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities
* in an image.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RecognizeCelebritiesResult withCelebrityFaces(Celebrity... celebrityFaces) {
if (this.celebrityFaces == null) {
setCelebrityFaces(new java.util.ArrayList<Celebrity>(celebrityFaces.length));
}
for (Celebrity ele : celebrityFaces) {
this.celebrityFaces.add(ele);
}
return this;
}
/**
* <p>
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities in an
* image.
* </p>
*
* @param celebrityFaces
* Details about each celebrity found in the image. Amazon Rekognition can detect a maximum of 15 celebrities
* in an image.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RecognizeCelebritiesResult withCelebrityFaces(java.util.Collection<Celebrity> celebrityFaces) {
setCelebrityFaces(celebrityFaces);
return this;
}
/**
* <p>
* Details about each unrecognized face in the image.
* </p>
*
* @return Details about each unrecognized face in the image.
*/
public java.util.List<ComparedFace> getUnrecognizedFaces() {
return unrecognizedFaces;
}
/**
* <p>
* Details about each unrecognized face in the image.
* </p>
*
* @param unrecognizedFaces
* Details about each unrecognized face in the image.
*/
public void setUnrecognizedFaces(java.util.Collection<ComparedFace> unrecognizedFaces) {
if (unrecognizedFaces == null) {
this.unrecognizedFaces = null;
return;
}
this.unrecognizedFaces = new java.util.ArrayList<ComparedFace>(unrecognizedFaces);
}
/**
* <p>
* Details about each unrecognized face in the image.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setUnrecognizedFaces(java.util.Collection)} or {@link #withUnrecognizedFaces(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param unrecognizedFaces
* Details about each unrecognized face in the image.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RecognizeCelebritiesResult withUnrecognizedFaces(ComparedFace... unrecognizedFaces) {
if (this.unrecognizedFaces == null) {
setUnrecognizedFaces(new java.util.ArrayList<ComparedFace>(unrecognizedFaces.length));
}
for (ComparedFace ele : unrecognizedFaces) {
this.unrecognizedFaces.add(ele);
}
return this;
}
/**
* <p>
* Details about each unrecognized face in the image.
* </p>
*
* @param unrecognizedFaces
* Details about each unrecognized face in the image.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public RecognizeCelebritiesResult withUnrecognizedFaces(java.util.Collection<ComparedFace> unrecognizedFaces) {
setUnrecognizedFaces(unrecognizedFaces);
return this;
}
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*
* @param orientationCorrection
* The orientation of the input image (counterclockwise direction). If your application displays the image,
* you can use this value to correct the orientation. The bounding box coordinates returned in
* <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code> represent face locations before the image
* orientation is corrected. </p> <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes
* the image's orientation. If so, and the Exif metadata for the input image populates the orientation field,
* the value of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and
* <code>UnrecognizedFaces</code> bounding box coordinates represent face locations after Exif metadata is
* used to correct the image orientation. Images in .png format don't contain Exif metadata.
* </p>
* @see OrientationCorrection
*/
public void setOrientationCorrection(String orientationCorrection) {
this.orientationCorrection = orientationCorrection;
}
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*
* @return The orientation of the input image (counterclockwise direction). If your application displays the image,
* you can use this value to correct the orientation. The bounding box coordinates returned in
* <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code> represent face locations before the image
* orientation is corrected. </p> <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes
* the image's orientation. If so, and the Exif metadata for the input image populates the orientation
* field, the value of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and
* <code>UnrecognizedFaces</code> bounding box coordinates represent face locations after Exif metadata is
* used to correct the image orientation. Images in .png format don't contain Exif metadata.
* </p>
* @see OrientationCorrection
*/
public String getOrientationCorrection() {
return this.orientationCorrection;
}
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*
* @param orientationCorrection
* The orientation of the input image (counterclockwise direction). If your application displays the image,
* you can use this value to correct the orientation. The bounding box coordinates returned in
* <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code> represent face locations before the image
* orientation is corrected. </p> <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes
* the image's orientation. If so, and the Exif metadata for the input image populates the orientation field,
* the value of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and
* <code>UnrecognizedFaces</code> bounding box coordinates represent face locations after Exif metadata is
* used to correct the image orientation. Images in .png format don't contain Exif metadata.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see OrientationCorrection
*/
public RecognizeCelebritiesResult withOrientationCorrection(String orientationCorrection) {
setOrientationCorrection(orientationCorrection);
return this;
}
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*
* @param orientationCorrection
* The orientation of the input image (counterclockwise direction). If your application displays the image,
* you can use this value to correct the orientation. The bounding box coordinates returned in
* <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code> represent face locations before the image
* orientation is corrected. </p> <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes
* the image's orientation. If so, and the Exif metadata for the input image populates the orientation field,
* the value of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and
* <code>UnrecognizedFaces</code> bounding box coordinates represent face locations after Exif metadata is
* used to correct the image orientation. Images in .png format don't contain Exif metadata.
* </p>
* @see OrientationCorrection
*/
public void setOrientationCorrection(OrientationCorrection orientationCorrection) {
withOrientationCorrection(orientationCorrection);
}
/**
* <p>
* The orientation of the input image (counterclockwise direction). If your application displays the image, you can
* use this value to correct the orientation. The bounding box coordinates returned in <code>CelebrityFaces</code>
* and <code>UnrecognizedFaces</code> represent face locations before the image orientation is corrected.
* </p>
* <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes the
* image's orientation. If so, and the Exif metadata for the input image populates the orientation field, the value
* of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code>
* bounding box coordinates represent face locations after Exif metadata is used to correct the image orientation.
* Images in .png format don't contain Exif metadata.
* </p>
* </note>
*
* @param orientationCorrection
* The orientation of the input image (counterclockwise direction). If your application displays the image,
* you can use this value to correct the orientation. The bounding box coordinates returned in
* <code>CelebrityFaces</code> and <code>UnrecognizedFaces</code> represent face locations before the image
* orientation is corrected. </p> <note>
* <p>
* If the input image is in .jpeg format, it might contain exchangeable image (Exif) metadata that includes
* the image's orientation. If so, and the Exif metadata for the input image populates the orientation field,
* the value of <code>OrientationCorrection</code> is null. The <code>CelebrityFaces</code> and
* <code>UnrecognizedFaces</code> bounding box coordinates represent face locations after Exif metadata is
* used to correct the image orientation. Images in .png format don't contain Exif metadata.
* </p>
* @return Returns a reference to this object so that method calls can be chained together.
* @see OrientationCorrection
*/
public RecognizeCelebritiesResult withOrientationCorrection(OrientationCorrection orientationCorrection) {
this.orientationCorrection = orientationCorrection.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCelebrityFaces() != null)
sb.append("CelebrityFaces: ").append(getCelebrityFaces()).append(",");
if (getUnrecognizedFaces() != null)
sb.append("UnrecognizedFaces: ").append(getUnrecognizedFaces()).append(",");
if (getOrientationCorrection() != null)
sb.append("OrientationCorrection: ").append(getOrientationCorrection());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RecognizeCelebritiesResult == false)
return false;
RecognizeCelebritiesResult other = (RecognizeCelebritiesResult) obj;
if (other.getCelebrityFaces() == null ^ this.getCelebrityFaces() == null)
return false;
if (other.getCelebrityFaces() != null && other.getCelebrityFaces().equals(this.getCelebrityFaces()) == false)
return false;
if (other.getUnrecognizedFaces() == null ^ this.getUnrecognizedFaces() == null)
return false;
if (other.getUnrecognizedFaces() != null && other.getUnrecognizedFaces().equals(this.getUnrecognizedFaces()) == false)
return false;
if (other.getOrientationCorrection() == null ^ this.getOrientationCorrection() == null)
return false;
if (other.getOrientationCorrection() != null && other.getOrientationCorrection().equals(this.getOrientationCorrection()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCelebrityFaces() == null) ? 0 : getCelebrityFaces().hashCode());
hashCode = prime * hashCode + ((getUnrecognizedFaces() == null) ? 0 : getUnrecognizedFaces().hashCode());
hashCode = prime * hashCode + ((getOrientationCorrection() == null) ? 0 : getOrientationCorrection().hashCode());
return hashCode;
}
@Override
public RecognizeCelebritiesResult clone() {
try {
return (RecognizeCelebritiesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
cljohnso/Rainfall-core | src/main/java/io/rainfall/unit/From.java | 1000 | /*
* Copyright 2014 Aurélien Broszniowski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rainfall.unit;
import io.rainfall.Unit;
/**
* @author Aurelien Broszniowski
*/
public class From extends UnitMeasurement {
public static From from(int nb, Unit unit) {
return new From(nb, unit);
}
public From(final int nb, final Unit unit) {
super(nb, unit);
}
@Override
public String getDescription() {
return "from " + super.getDescription();
}
}
| apache-2.0 |
aglne/shifu | src/test/java/ml/shifu/shifu/udf/SimpleScoreUDFTest.java | 2304 | /**
* Copyright [2012-2014] PayPal Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ml.shifu.shifu.udf;
import org.apache.commons.io.FileUtils;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
/**
* SimpleScoreUDFTest class
*/
public class SimpleScoreUDFTest {
private SimpleScoreUDF instance;
private File tmpModels = new File("models");
@BeforeClass
public void setUp() throws Exception {
File models = new File("src/test/resources/example/cancer-judgement/ModelStore/ModelSet1/models");
FileUtils.copyDirectory(models, tmpModels);
instance = new SimpleScoreUDF("LOCAL",
"src/test/resources/example/cancer-judgement/ModelStore/ModelSet1/ModelConfig.json",
"src/test/resources/example/cancer-judgement/ModelStore/ModelSet1/ColumnConfig.json",
"src/test/resources/example/cancer-judgement/DataStore/DataSet1/.pig_header",
"|");
}
@Test
public void testUDFNull() throws Exception {
Tuple tuple = TupleFactory.getInstance().newTuple(0);
Assert.assertNull(instance.exec(tuple));
}
@Test
public void testExec() throws IOException {
Tuple input = TupleFactory.getInstance().newTuple(31);
for (int i = 0; i < 31; i++) {
input.set(i, 1);
}
input.set(0, "M");
Assert.assertEquals(42, instance.exec(input).intValue());
}
@AfterClass
public void clearUp() throws IOException {
FileUtils.deleteDirectory(tmpModels);
}
}
| apache-2.0 |
lachatak/market-data-feed | feed-api/src/main/java/org/kaloz/datafeed/processor/api/instrument/InstrumentPriceRequestMessage.java | 1675 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaloz.datafeed.processor.api.instrument;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.kaloz.messaging.app.client.JsonMessage;
import org.springframework.stereotype.Component;
@Component
public class InstrumentPriceRequestMessage extends JsonMessage {
public static final String TYPE = "InstrumentPriceRequestMessage";
private String provider;
private String shortName;
public InstrumentPriceRequestMessage() {
}
public InstrumentPriceRequestMessage(String provider, String shortName) {
this.provider = provider;
this.shortName = shortName;
}
public String getMessageType(){
return TYPE;
}
public String getProvider() {
return provider;
}
public void setProvider(String provider) {
this.provider = provider;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| apache-2.0 |
mohanaraosv/commons-validator | src/main/java/org/apache/commons/validator/routines/CodeValidator.java | 8414 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines;
import java.io.Serializable;
import org.apache.commons.validator.routines.checkdigit.CheckDigit;
/**
* Generic <b>Code Validation</b> providing format, minimum/maximum
* length and {@link CheckDigit} validations.
* <p>
* Performs the following validations on a code:
* <ul>
* <li>Check the <i>format</i> of the code using a <i>regular expression.</i> (if specified)</li>
* <li>Check the <i>minimum</i> and <i>maximum</i> length (if specified) of the <i>parsed</i> code
* (i.e. parsed by the <i>regular expression</i>).</li>
* <li>Performs {@link CheckDigit} validation on the parsed code (if specified).</li>
* </ul>
* <p>
* Configure the validator with the appropriate regular expression, minimum/maximum length
* and {@link CheckDigit} validator and then call one of the two validation
* methods provided:</p>
* <ul>
* <li><code>boolean isValid(code)</code></li>
* <li><code>String validate(code)</code></li>
* </ul>
* <p>
* Codes often include <i>format</i> characters - such as hyphens - to make them
* more easily human readable. These can be removed prior to length and check digit
* validation by specifying them as a <i>non-capturing</i> group in the regular
* expression (i.e. use the <code>(?: )</code> notation).
*
* @version $Revision$
* @since Validator 1.4
*/
public final class CodeValidator implements Serializable {
private static final long serialVersionUID = 446960910870938233L;
private final RegexValidator regexValidator;
private final int minLength;
private final int maxLength;
private final CheckDigit checkdigit;
/**
* Construct a code validator with a specified regular
* expression and {@link CheckDigit}.
*
* @param regex The format regular expression
* @param checkdigit The check digit validation routine
*/
public CodeValidator(String regex, CheckDigit checkdigit) {
this(regex, -1, -1, checkdigit);
}
/**
* Construct a code validator with a specified regular
* expression, length and {@link CheckDigit}.
*
* @param regex The format regular expression.
* @param length The length of the code
* (sets the mimimum/maximum to the same)
* @param checkdigit The check digit validation routine
*/
public CodeValidator(String regex, int length, CheckDigit checkdigit) {
this(regex, length, length, checkdigit);
}
/**
* Construct a code validator with a specified regular
* expression, minimum/maximum length and {@link CheckDigit} validation.
*
* @param regex The regular expression validator
* @param minLength The minimum length of the code
* @param maxLength The maximum length of the code
* @param checkdigit The check digit validation routine
*/
public CodeValidator(String regex, int minLength, int maxLength,
CheckDigit checkdigit) {
if (regex != null && regex.length() > 0) {
this.regexValidator = new RegexValidator(regex);
} else {
this.regexValidator = null;
}
this.minLength = minLength;
this.maxLength = maxLength;
this.checkdigit = checkdigit;
}
/**
* Construct a code validator with a specified regular expression,
* validator and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param checkdigit The check digit validation routine.
*/
public CodeValidator(RegexValidator regexValidator, CheckDigit checkdigit) {
this(regexValidator, -1, -1, checkdigit);
}
/**
* Construct a code validator with a specified regular expression,
* validator, length and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param length The length of the code
* (sets the mimimum/maximum to the same value)
* @param checkdigit The check digit validation routine
*/
public CodeValidator(RegexValidator regexValidator, int length, CheckDigit checkdigit) {
this(regexValidator, length, length, checkdigit);
}
/**
* Construct a code validator with a specified regular expression
* validator, minimum/maximum length and {@link CheckDigit} validation.
*
* @param regexValidator The format regular expression validator
* @param minLength The minimum length of the code
* @param maxLength The maximum length of the code
* @param checkdigit The check digit validation routine
*/
public CodeValidator(RegexValidator regexValidator, int minLength, int maxLength,
CheckDigit checkdigit) {
this.regexValidator = regexValidator;
this.minLength = minLength;
this.maxLength = maxLength;
this.checkdigit = checkdigit;
}
/**
* Return the check digit validation routine.
* <p>
* <b>N.B.</b> Optional, if not set no Check Digit
* validation will be performed on the code.
*
* @return The check digit validation routine
*/
public CheckDigit getCheckDigit() {
return checkdigit;
}
/**
* Return the minimum length of the code.
* <p>
* <b>N.B.</b> Optional, if less than zero the
* minimum length will not be checked.
*
* @return The minimum length of the code or
* <code>-1</code> if the code has no minimum length
*/
public int getMinLength() {
return minLength;
}
/**
* Return the maximum length of the code.
* <p>
* <b>N.B.</b> Optional, if less than zero the
* maximum length will not be checked.
*
* @return The maximum length of the code or
* <code>-1</code> if the code has no maximum length
*/
public int getMaxLength() {
return maxLength;
}
/**
* Return the <i>regular expression</i> validator.
* <p>
* <b>N.B.</b> Optional, if not set no regular
* expression validation will be performed on the code.
*
* @return The regular expression validator
*/
public RegexValidator getRegexValidator() {
return regexValidator;
}
/**
* Validate the code returning either <code>true</code>
* or <code>false</code>.
*
* @param input The code to validate
* @return <code>true</code> if valid, otherwise
* <code>false</code>
*/
public boolean isValid(String input) {
return (validate(input) != null);
}
/**
* Validate the code returning either the valid code or
* <code>null</code> if invalid.
*
* @param input The code to validate
* @return The code if valid, otherwise <code>null</code>
* if invalid
*/
public Object validate(String input) {
if (input == null) {
return null;
}
String code = input.trim();
if (code.length() == 0) {
return null;
}
// validate/reformat using regular expression
if (regexValidator != null) {
code = regexValidator.validate(code);
if (code == null) {
return null;
}
}
// check the length
if ((minLength >= 0 && code.length() < minLength) ||
(maxLength >= 0 && code.length() > maxLength)) {
return null;
}
// validate the check digit
if (checkdigit != null && !checkdigit.isValid(code)) {
return null;
}
return code;
}
}
| apache-2.0 |
dunyuling/javabase | src/main/java/com/lhg/test/threadpool/ScheduledThreadPool.java | 944 | package com.lhg.test.threadpool;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by liuhg on 16-3-4.
*/
public class ScheduledThreadPool {
public static void main(String[] args) {
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常
@Override
public void run() {
//throw new RuntimeException();
System.out.println("================");
}
}, 1000, 5000, TimeUnit.MILLISECONDS);
exec.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的
@Override
public void run() {
System.out.println(System.nanoTime());
}
}, 1000, 2000, TimeUnit.MILLISECONDS);
}
}
| apache-2.0 |
oyatsukai/openkit-android-beta | OpenKitSDK/src/io/openkit/okcloud/OKCloud.java | 4726 | /**
* Copyright 2012 OpenKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.openkit.okcloud;
import java.util.HashMap;
import java.util.LinkedHashMap;
import io.openkit.*;
import org.codehaus.jackson.map.ObjectMapper;
public class OKCloud {
//==============================================================================
// Public API
//==============================================================================
public static void get(String key, OKCloudHandler h) {
OKCloud c = new OKCloud();
c.iget(key, h);
}
public static void set(Object o, String key, OKCloudHandler h) {
OKCloud c = new OKCloud();
c.iset(o, key, h);
}
//==============================================================================
// Private
//==============================================================================
private boolean validateKey(final String key) {
if (-1 != key.indexOf('.')) {
return false;
}
return true;
}
private boolean encodeObj(Object o, StringBuilder out) {
boolean success = true;
ObjectMapper mapper = new ObjectMapper();
try {
out.append(mapper.writeValueAsString(o));
} catch (Exception e) {
OKLog.d("Could not encode object!");
success = false;
}
return success;
}
private Object decodeStr(String s) {
ObjectMapper mapper = new ObjectMapper();
Object o;
try {
o = mapper.readValue(s, Object.class);
} catch (Exception e) {
OKLog.d("Could not decode String!!");
return null;
}
return o;
}
// Verifies that we can serialize and deserialize this object before
// storing to redis.
private void iset(Object o, String key, final OKCloudHandler h) {
String objRep;
StringBuilder strOut = new StringBuilder();
if(OpenKit.getCurrentUser() == null) {
h.complete(null, new OKCloudException("User is not logged in. User must be logged in when making cloud requests."));
return;
}
if (!validateKey(key)) {
h.complete(null, new OKCloudException("Invalid key: " + key));
return;
}
if (!encodeObj(o, strOut)) {
h.complete(null, new OKCloudException("Could not serialize this object."));
return;
}
objRep = strOut.toString();
final Object decodedObj = decodeStr(objRep);
if (decodedObj == null) {
h.complete(null, new OKCloudException("Serialization of object succeeded, but deserialization did not."));
return;
}
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", String.valueOf(OpenKit.getCurrentUser().getOKUserID()));
params.put("field_key", key);
params.put("field_value", objRep);
OKCloudAsyncRequest req = new OKCloudAsyncRequest("developer_data", "POST", params);
req.performWithCompletionHandler(new OKCloudAsyncRequest.CompletionHandler() {
@Override
public void complete(String response, OKCloudException e) {
h.complete(decodedObj, e);
}
});
}
private void iget(final String key, final OKCloudHandler h) {
if(OpenKit.getCurrentUser() == null) {
h.complete(null, new OKCloudException("User is not logged in. User must be logged in when making cloud requests."));
return;
}
if (!validateKey(key)) {
h.complete(null, new OKCloudException("Invalid key: " + key));
return;
}
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id", String.valueOf(OpenKit.getCurrentUser().getOKUserID()));
String path = String.format("developer_data/%s", key);
OKCloudAsyncRequest req = new OKCloudAsyncRequest(path, "GET", params);
req.performWithCompletionHandler(new OKCloudAsyncRequest.CompletionHandler() {
@Override
public void complete(String response, OKCloudException e) {
Object retVal = null;
OKCloudException retErr = e;
if (retErr == null) {
ObjectMapper mapper = new ObjectMapper();
try {
LinkedHashMap<?,?> resObj = mapper.readValue(response, LinkedHashMap.class);
retVal = resObj.get(key);
} catch(Exception badError) {
retErr = new OKCloudException("Bad stuff is happening.");
}
}
h.complete(retVal, retErr);
}
});
}
}
| apache-2.0 |
b-palaniappan/SpringSecurityHDIV | src/main/java/io/c12/bala/db/domain/InternetAddress.java | 1433 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.c12.bala.db.domain;
/**
* @author b.palaniappan
*
*/
public class InternetAddress {
private String internetAddress;
private InternetAddressType internetAddressType;
public String getInternetAddress() {
return internetAddress;
}
public void setInternetAddress(String internetAddress) {
this.internetAddress = internetAddress;
}
public InternetAddressType getInternetAddressType() {
return internetAddressType;
}
public void setInternetAddressType(InternetAddressType internetAddressType) {
this.internetAddressType = internetAddressType;
}
}
| apache-2.0 |
tgummerer/buck | test/com/facebook/buck/cxx/CxxPreprocessAndCompileStepTest.java | 11523 | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cxx;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.util.Escaper;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CxxPreprocessAndCompileStepTest {
@Test
public void outputProcessor() {
Path original = Paths.get("buck-out/foo#bar/world.h");
ImmutableMap<Path, Path> replacementPaths =
ImmutableMap.of(original, Paths.get("hello/////world.h"));
Path finalPath = Paths.get("SANITIZED/world.h");
// Setup some dummy values for inputs to the CxxPreprocessAndCompileStep
ImmutableList<String> compiler = ImmutableList.of("compiler");
Path output = Paths.get("test.ii");
Path depFile = Paths.get("test.dep");
Path input = Paths.get("test.cpp");
Path compilationDirectory = Paths.get("compDir");
DebugPathSanitizer sanitizer = new DebugPathSanitizer(
9,
File.separatorChar,
Paths.get("PWD"),
ImmutableBiMap.of(Paths.get("hello"), Paths.get("SANITIZED")));
// Create our CxxPreprocessAndCompileStep to test.
CxxPreprocessAndCompileStep cxxPreprocessStep =
new CxxPreprocessAndCompileStep(
new FakeProjectFilesystem(),
CxxPreprocessAndCompileStep.Operation.PREPROCESS,
output,
depFile,
input,
CxxSource.Type.CXX,
Optional.of(compiler),
Optional.<ImmutableList<String>>absent(),
replacementPaths,
sanitizer,
Optional.<Function<String, Iterable<String>>>absent());
Function<String, Iterable<String>> processor =
cxxPreprocessStep.createPreprocessOutputLineProcessor(compilationDirectory);
// Fixup line marker lines properly.
assertThat(
ImmutableList.of(
String.format("# 12 \"%s\"", Escaper.escapePathForCIncludeString(finalPath))),
equalTo(processor.apply(String.format("# 12 \"%s\"", original))));
assertThat(
ImmutableList.of(
String.format("# 12 \"%s\" 2 1", Escaper.escapePathForCIncludeString(finalPath))),
equalTo(processor.apply(String.format("# 12 \"%s\" 2 1", original))));
// test.h isn't in the replacement map, so shouldn't be replaced.
assertThat(ImmutableList.of("# 4 \"test.h\""), equalTo(processor.apply("# 4 \"test.h\"")));
// Don't modify non-line-marker lines.
assertThat(ImmutableList.of("int main() {"), equalTo(processor.apply("int main() {")));
}
@Test
public void errorProcessorWithRelativePaths() {
Path original = Paths.get("buck-out/foo#bar/world.h");
Path replacement = Paths.get("hello/world.h");
// Setup some dummy values for inputs to the CxxPreprocessAndCompileStep
ImmutableList<String> compiler = ImmutableList.of("compiler");
Path output = Paths.get("test.ii");
Path depFile = Paths.get("test.dep");
Path input = Paths.get("test.cpp");
ImmutableMap<Path, Path> replacementPaths = ImmutableMap.of(original, replacement);
Path compilationDirectory = Paths.get("compDir");
Path sanitizedDir = Paths.get("hello");
Path unsanitizedDir = Paths.get("buck-out/foo#bar");
DebugPathSanitizer sanitizer = new DebugPathSanitizer(
unsanitizedDir.toString().length(),
File.separatorChar,
compilationDirectory,
ImmutableBiMap.of(unsanitizedDir, sanitizedDir));
// Create our CxxPreprocessAndCompileStep to test.
CxxPreprocessAndCompileStep cxxPreprocessStep =
new CxxPreprocessAndCompileStep(
new FakeProjectFilesystem(),
CxxPreprocessAndCompileStep.Operation.COMPILE,
output,
depFile,
input,
CxxSource.Type.CXX,
Optional.<ImmutableList<String>>absent(),
Optional.of(compiler),
replacementPaths,
sanitizer,
Optional.<Function<String, Iterable<String>>>absent());
Function<String, Iterable<String>> processor =
cxxPreprocessStep.createErrorLineProcessor(compilationDirectory, false);
// Fixup lines in included traces.
assertThat(
ImmutableList.of(String.format("In file included from %s:", replacement)),
equalTo(processor.apply(String.format("In file included from %s:", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s:3:2:", replacement)),
equalTo(processor.apply(String.format("In file included from %s:3:2:", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s,", replacement)),
equalTo(processor.apply(String.format("In file included from %s,", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s:7,", replacement)),
equalTo(processor.apply(String.format("In file included from %s:7,", original))));
assertThat(
ImmutableList.of(String.format(" from %s:", replacement)),
equalTo(processor.apply(String.format(" from %s:", original))));
assertThat(
ImmutableList.of(String.format(" from %s:3:2:", replacement)),
equalTo(processor.apply(String.format(" from %s:3:2:", original))));
assertThat(
ImmutableList.of(String.format(" from %s,", replacement)),
equalTo(processor.apply(String.format(" from %s,", original))));
assertThat(
ImmutableList.of(String.format(" from %s:7,", replacement)),
equalTo(processor.apply(String.format(" from %s:7,", original))));
// Fixup lines in error messages.
assertThat(
ImmutableList.of(String.format("%s: something bad", replacement)),
equalTo(processor.apply(String.format("%s: something bad", original))));
assertThat(
ImmutableList.of(String.format("%s:4: something bad", replacement)),
equalTo(processor.apply(String.format("%s:4: something bad", original))));
assertThat(
ImmutableList.of(String.format("%s:4:2: something bad", replacement)),
equalTo(processor.apply(String.format("%s:4:2: something bad", original))));
// test.h isn't in the replacement map, so shouldn't be replaced.
assertThat(
ImmutableList.of("In file included from test.h:"),
equalTo(processor.apply("In file included from test.h:")));
// Don't modify lines without headers.
assertThat(
ImmutableList.of(" error message!"),
equalTo(processor.apply(" error message!")));
}
@Test
public void errorProcessorWithAbsolutePaths() {
Path original = Paths.get("buck-out/foo#bar/world.h");
Path replacement = Paths.get("hello/world.h");
// Setup some dummy values for inputs to the CxxPreprocessAndCompileStep
ImmutableList<String> compiler = ImmutableList.of("compiler");
Path output = Paths.get("test.ii");
Path depFile = Paths.get("test.dep");
Path input = Paths.get("test.cpp");
ImmutableMap<Path, Path> replacementPaths = ImmutableMap.of(original, replacement);
Path compilationDirectory = Paths.get("compDir");
Path sanitizedDir = Paths.get("hello");
Path unsanitizedDir = Paths.get("buck-out/foo#bar");
DebugPathSanitizer sanitizer = new DebugPathSanitizer(
unsanitizedDir.toString().length(),
File.separatorChar,
compilationDirectory,
ImmutableBiMap.of(unsanitizedDir, sanitizedDir));
// Create our CxxPreprocessAndCompileStep to test.
CxxPreprocessAndCompileStep cxxPreprocessStep =
new CxxPreprocessAndCompileStep(
new FakeProjectFilesystem(),
CxxPreprocessAndCompileStep.Operation.COMPILE,
output,
depFile,
input,
CxxSource.Type.CXX,
Optional.<ImmutableList<String>>absent(),
Optional.of(compiler),
replacementPaths,
sanitizer,
Optional.<Function<String, Iterable<String>>>absent());
Function<String, Iterable<String>> processor =
cxxPreprocessStep.createErrorLineProcessor(compilationDirectory, true);
Path expected = replacement.toAbsolutePath();
// Fixup lines in included traces.
assertThat(
ImmutableList.of(String.format("In file included from %s:", expected)),
equalTo(processor.apply(String.format("In file included from %s:", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s:3:2:", expected)),
equalTo(processor.apply(String.format("In file included from %s:3:2:", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s,", expected)),
equalTo(processor.apply(String.format("In file included from %s,", original))));
assertThat(
ImmutableList.of(String.format("In file included from %s:7,", expected)),
equalTo(processor.apply(String.format("In file included from %s:7,", original))));
assertThat(
ImmutableList.of(String.format(" from %s:", expected)),
equalTo(processor.apply(String.format(" from %s:", original))));
assertThat(
ImmutableList.of(String.format(" from %s:3:2:", expected)),
equalTo(processor.apply(String.format(" from %s:3:2:", original))));
assertThat(
ImmutableList.of(String.format(" from %s,", expected)),
equalTo(processor.apply(String.format(" from %s,", original))));
assertThat(
ImmutableList.of(String.format(" from %s:7,", expected)),
equalTo(processor.apply(String.format(" from %s:7,", original))));
// Fixup lines in error messages.
assertThat(
ImmutableList.of(String.format("%s: something bad", expected)),
equalTo(processor.apply(String.format("%s: something bad", original))));
assertThat(
ImmutableList.of(String.format("%s:4: something bad", expected)),
equalTo(processor.apply(String.format("%s:4: something bad", original))));
assertThat(
ImmutableList.of(String.format("%s:4:2: something bad", expected)),
equalTo(processor.apply(String.format("%s:4:2: something bad", original))));
// test.h isn't in the replacement map, so shouldn't be replaced.
assertThat(
ImmutableList.of(String.format("In file included from %s:",
Paths.get("test.h").toAbsolutePath().toString())),
equalTo(processor.apply("In file included from test.h:")));
// Don't modify lines without headers.
assertThat(
ImmutableList.of(" error message!"),
equalTo(processor.apply(" error message!")));
}
}
| apache-2.0 |