code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.algorithm;
import java.math.BigDecimal;
import java.math.MathContext;
import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Conjugate;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.RealConstants;
import nom.bdezonia.zorbage.algebra.SetComplex;
import nom.bdezonia.zorbage.algebra.Trigonometric;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class InvFFT {
// do not instantiate
private InvFFT() {}
/**
*
* @param <T>
* @param <U>
* @param <V>
* @param <W>
* @param cmplxAlg
* @param realAlg
* @param a
* @param b
*/
public static
<T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Conjugate<U>,
U extends SetComplex<W>,
V extends Algebra<V,W> & Trigonometric<W> & RealConstants<W> & Unity<W> &
Multiplication<W> & Addition<W> & Invertible<W>,
W>
void compute(T cmplxAlg, V realAlg, IndexedDataSource<U> a,IndexedDataSource<U> b)
{
long aSize = a.size();
long bSize = b.size();
if (aSize != FFT.enclosingPowerOf2(aSize))
throw new IllegalArgumentException("input size is not a power of 2");
if (aSize != bSize)
throw new IllegalArgumentException("output size does not match input size");
U one_over_n = cmplxAlg.construct((BigDecimal.ONE.divide(BigDecimal.valueOf(aSize), new MathContext(100))).toString());
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, a, b);
FFT.compute(cmplxAlg, realAlg, b, b);
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, b, b);
Scale.compute(cmplxAlg, one_over_n, b, b);
}
}
| bdezonia/zorbage | src/main/java/nom/bdezonia/zorbage/algorithm/InvFFT.java | Java | bsd-3-clause | 3,423 |
package eu.monnetproject.sim.entity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import eu.monnetproject.util.Logger;
import eu.monnetproject.label.LabelExtractor;
import eu.monnetproject.label.LabelExtractorFactory;
import eu.monnetproject.lang.Language;
import eu.monnetproject.ontology.Entity;
import eu.monnetproject.sim.EntitySimilarityMeasure;
import eu.monnetproject.sim.StringSimilarityMeasure;
import eu.monnetproject.sim.string.Levenshtein;
import eu.monnetproject.sim.token.TokenBagOfWordsCosine;
import eu.monnetproject.sim.util.Functions;
import eu.monnetproject.sim.util.SimilarityUtils;
import eu.monnetproject.tokenizer.FairlyGoodTokenizer;
import eu.monnetproject.translatorimpl.Translator;
import eu.monnetproject.util.Logging;
/**
* Levenshtein similarity.
* Intralingual aggregation: average
* Interlingual aggregation: maximum
*
* @author Dennis Spohr
*
*/
public class MaximumAverageLevenshtein implements EntitySimilarityMeasure {
private Logger log = Logging.getLogger(this);
private final String name = this.getClass().getName();
private LabelExtractorFactory lef;
private LabelExtractor lex = null;
private Collection<Language> languages = Collections.emptySet();
private StringSimilarityMeasure measure;
private boolean includePuns = false;
private Translator translator;
public MaximumAverageLevenshtein(LabelExtractorFactory lef) {
this.lef = lef;
this.measure = new Levenshtein();
this.translator = new Translator();
}
public void configure(Properties properties) {
this.languages = SimilarityUtils.getLanguages(properties.getProperty("languages", ""));
for (Language lang : this.languages) {
log.info("Requested language: "+lang);
}
this.includePuns = SimilarityUtils.getIncludePuns(properties.getProperty("include_puns", "false"));
}
@Override
public double getScore(Entity srcEntity, Entity tgtEntity) {
if (this.lex == null) {
this.lex = this.lef.getExtractor(SimilarityUtils.determineLabelProperties(srcEntity, tgtEntity), true, false);
}
if (this.languages.size() < 1) {
log.warning("No languages specified in config file.");
this.languages = SimilarityUtils.determineLanguages(srcEntity, tgtEntity);
String langs = "";
for (Language lang : languages) {
langs += lang.getName()+", ";
}
try {
log.warning("Using "+langs.substring(0, langs.lastIndexOf(","))+".");
} catch (Exception e) {
log.severe("No languages in source and target ontology.");
}
}
Map<Language, Collection<String>> srcMap = null;
Map<Language, Collection<String>> tgtMap = null;
if (includePuns) {
srcMap = SimilarityUtils.getLabelsIncludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsIncludingPuns(tgtEntity,lex);
} else {
srcMap = SimilarityUtils.getLabelsExcludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsExcludingPuns(tgtEntity,lex);
}
List<Double> intralingualScores = new ArrayList<Double>();
for (Language language : this.languages) {
Collection<String> srcLabels = srcMap.get(language);
Collection<String> tgtLabels = tgtMap.get(language);
if (srcLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+srcEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
srcLabels = SimilarityUtils.getTranslatedLabels(srcEntity,language,translator,lex);
}
if (tgtLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+tgtEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
tgtLabels = SimilarityUtils.getTranslatedLabels(tgtEntity,language,translator,lex);
}
double[] scores = new double[srcLabels.size()*tgtLabels.size()];
int index = 0;
for (String srcLabel : srcLabels) {
for (String tgtLabel : tgtLabels) {
scores[index++] = measure.getScore(srcLabel, tgtLabel);
}
}
intralingualScores.add(Functions.mean(scores));
}
if (intralingualScores.size() < 1)
return 0.;
double[] intralingualScoresArray = new double[intralingualScores.size()];
for (int i = 0; i < intralingualScores.size(); i++) {
intralingualScoresArray[i] = intralingualScores.get(i);
}
return Functions.max(intralingualScoresArray);
}
@Override
public String getName() {
return this.name;
}
}
| monnetproject/coal | nlp.sim/src/main/java/eu/monnetproject/sim/entity/MaximumAverageLevenshtein.java | Java | bsd-3-clause | 4,639 |
package uk.ac.soton.ecs.comp3204.l3;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.swing.JPanel;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.data.dataset.VFSGroupDataset;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider;
import uk.ac.soton.ecs.comp3204.utils.Utils;
import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
/**
* Visualise mean-centered face images
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*/
@Demonstration(title = "Mean-centred faces demo")
public class MeanCenteredFacesDemo implements Slide {
@Override
public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
final FImage mean = dataset.getRandomInstance().fill(0f);
for (final FImage i : dataset) {
mean.addInplace(i);
}
mean.divideInplace(dataset.numInstances());
final JPanel outer = new JPanel();
outer.setOpaque(false);
outer.setPreferredSize(new Dimension(width, height));
outer.setLayout(new GridBagLayout());
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height - 50));
base.setLayout(new FlowLayout());
for (int i = 0; i < 60; i++) {
final FImage img = dataset.getRandomInstance().subtract(mean).normalise();
final ImageComponent ic = new ImageComponent(true, false);
ic.setAllowPanning(false);
ic.setAllowZoom(false);
ic.setShowPixelColours(false);
ic.setShowXYPosition(false);
ic.setImage(ImageUtilities.createBufferedImageForDisplay(img));
base.add(ic);
}
outer.add(base);
return outer;
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
| jonhare/COMP3204 | app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java | Java | bsd-3-clause | 2,176 |
package com.salesforce.dva.argus.service.mq.kafka;
import com.fasterxml.jackson.databind.JavaType;
import java.io.Serializable;
import java.util.List;
public interface Consumer {
<T extends Serializable> List<T> dequeueFromBuffer(String topic, Class<T> type, int timeout, int limit);
<T extends Serializable> List<T> dequeueFromBuffer(String topic, JavaType type, int timeout, int limit);
void shutdown();
} | salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/mq/kafka/Consumer.java | Java | bsd-3-clause | 424 |
package eu.monnetproject.util;
import java.util.*;
/**
* Utility function to syntactically sugar properties for OSGi.
* This allows you to create a property map as follows
* <code>Props.prop("key1","value1")</code><br/>
* <code> .prop("key2","value2")</code>
*/
public final class Props {
public static PropsMap prop(String key, Object value) {
PropsMap pm = new PropsMap();
pm.put(key,value);
return pm;
}
public static class PropsMap extends Hashtable<String,Object> {
public PropsMap prop(String key, Object value) {
put(key,value);
return this;
}
}
} | monnetproject/coal | nlp.sim/src/main/java/eu/monnetproject/util/Props.java | Java | bsd-3-clause | 590 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.HAL;
/**
* Handle input from standard Joysticks connected to the Driver Station. This class handles standard
* input that comes from the Driver Station. Each time a value is requested the most recent value is
* returned. There is a single class instance for each joystick and the mapping of ports to hardware
* buttons depends on the code in the driver station.
*/
public class Joystick extends GenericHID {
static final byte kDefaultXAxis = 0;
static final byte kDefaultYAxis = 1;
static final byte kDefaultZAxis = 2;
static final byte kDefaultTwistAxis = 2;
static final byte kDefaultThrottleAxis = 3;
static final int kDefaultTriggerButton = 1;
static final int kDefaultTopButton = 2;
/**
* Represents an analog axis on a joystick.
*/
public enum AxisType {
kX(0), kY(1), kZ(2), kTwist(3), kThrottle(4), kNumAxis(5);
@SuppressWarnings("MemberName")
public final int value;
private AxisType(int value) {
this.value = value;
}
}
/**
* Represents a digital button on the JoyStick.
*/
public enum ButtonType {
kTrigger(0), kTop(1), kNumButton(2);
@SuppressWarnings("MemberName")
public final int value;
private ButtonType(int value) {
this.value = value;
}
}
/**
* Represents a rumble output on the JoyStick.
*/
public enum RumbleType {
kLeftRumble, kRightRumble
}
private final DriverStation m_ds;
private final int m_port;
private final byte[] m_axes;
private final byte[] m_buttons;
private int m_outputs;
private short m_leftRumble;
private short m_rightRumble;
/**
* Construct an instance of a joystick. The joystick index is the usb port on the drivers
* station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
public Joystick(final int port) {
this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value);
m_axes[AxisType.kX.value] = kDefaultXAxis;
m_axes[AxisType.kY.value] = kDefaultYAxis;
m_axes[AxisType.kZ.value] = kDefaultZAxis;
m_axes[AxisType.kTwist.value] = kDefaultTwistAxis;
m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis;
m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
HAL.report(tResourceType.kResourceType_Joystick, port);
}
/**
* Protected version of the constructor to be called by sub-classes.
*
* <p>This constructor allows the subclass to configure the number of constants for axes and
* buttons.
*
* @param port The port on the driver station that the joystick is plugged into.
* @param numAxisTypes The number of axis types in the enum.
* @param numButtonTypes The number of button types in the enum.
*/
protected Joystick(int port, int numAxisTypes, int numButtonTypes) {
m_ds = DriverStation.getInstance();
m_axes = new byte[numAxisTypes];
m_buttons = new byte[numButtonTypes];
m_port = port;
}
/**
* Get the X value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The X value of the joystick.
*/
public double getX(Hand hand) {
return getRawAxis(m_axes[AxisType.kX.value]);
}
/**
* Get the Y value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Y value of the joystick.
*/
public double getY(Hand hand) {
return getRawAxis(m_axes[AxisType.kY.value]);
}
/**
* Get the Z value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Z value of the joystick.
*/
public double getZ(Hand hand) {
return getRawAxis(m_axes[AxisType.kZ.value]);
}
/**
* Get the twist value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Twist value of the joystick.
*/
public double getTwist() {
return getRawAxis(m_axes[AxisType.kTwist.value]);
}
/**
* Get the throttle value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Throttle value of the joystick.
*/
public double getThrottle() {
return getRawAxis(m_axes[AxisType.kThrottle.value]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read, starting at 0.
* @return The value of the axis.
*/
public double getRawAxis(final int axis) {
return m_ds.getStickAxis(m_port, axis);
}
/**
* For the current joystick, return the axis determined by the argument.
*
* <p>This is for cases where the joystick axis is returned programatically, otherwise one of the
* previous functions would be preferable (for example getX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
public double getAxis(final AxisType axis) {
switch (axis) {
case kX:
return getX();
case kY:
return getY();
case kZ:
return getZ();
case kTwist:
return getTwist();
case kThrottle:
return getThrottle();
default:
return 0.0;
}
}
/**
* For the current joystick, return the number of axis.
*/
public int getAxisCount() {
return m_ds.getStickAxisCount(m_port);
}
/**
* Read the state of the trigger on the joystick.
*
* <p>Look up which button has been assigned to the trigger and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the trigger.
*/
public boolean getTrigger(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTrigger.value]);
}
/**
* Read the state of the top button on the joystick.
*
* <p>Look up which button has been assigned to the top and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the top button.
*/
public boolean getTop(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTop.value]);
}
/**
* This is not supported for the Joystick. This method is only here to complete the GenericHID
* interface.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the bumper (always false)
*/
public boolean getBumper(Hand hand) {
return false;
}
/**
* Get the button value (starting at button 1).
*
* <p>The appropriate button is returned as a boolean value.
*
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
public boolean getRawButton(final int button) {
return m_ds.getStickButton(m_port, (byte) button);
}
/**
* For the current joystick, return the number of buttons.
*/
public int getButtonCount() {
return m_ds.getStickButtonCount(m_port);
}
/**
* Get the angle in degrees of a POV on the joystick.
*
* <p>The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90,
* upper-left is 315).
*
* @param pov The index of the POV to read (starting at 0)
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public int getPOV(int pov) {
return m_ds.getStickPOV(m_port, pov);
}
/**
* For the current joystick, return the number of POVs.
*/
public int getPOVCount() {
return m_ds.getStickPOVCount(m_port);
}
/**
* Get buttons based on an enumerated type.
*
* <p>The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
public boolean getButton(ButtonType button) {
switch (button) {
case kTrigger:
return getTrigger();
case kTop:
return getTop();
default:
return false;
}
}
/**
* Get the magnitude of the direction vector formed by the joystick's current position relative to
* its origin.
*
* @return The magnitude of the direction vector
*/
public double getMagnitude() {
return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
/**
* Get the direction of the vector formed by the joystick and its origin in radians.
*
* @return The direction of the vector in radians
*/
public double getDirectionRadians() {
return Math.atan2(getX(), -getY());
}
/**
* Get the direction of the vector formed by the joystick and its origin in degrees.
*
* <p>Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++
*
* @return The direction of the vector in degrees
*/
public double getDirectionDegrees() {
return Math.toDegrees(getDirectionRadians());
}
/**
* Get the channel currently associated with the specified axis.
*
* @param axis The axis to look up the channel for.
* @return The channel fr the axis.
*/
public int getAxisChannel(AxisType axis) {
return m_axes[axis.value];
}
/**
* Set the channel associated with a specified axis.
*
* @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
public void setAxisChannel(AxisType axis, int channel) {
m_axes[axis.value] = (byte) channel;
}
/**
* Get the value of isXbox for the current joystick.
*
* @return A boolean that is true if the controller is an xbox controller.
*/
public boolean getIsXbox() {
return m_ds.getJoystickIsXbox(m_port);
}
/**
* Get the HID type of the current joystick.
*
* @return The HID type value of the current joystick.
*/
public int getType() {
return m_ds.getJoystickType(m_port);
}
/**
* Get the name of the current joystick.
*
* @return The name of the current joystick.
*/
public String getName() {
return m_ds.getJoystickName(m_port);
}
/**
* Get the port number of the joystick.
*
* @return The port number of the joystick.
*/
public int getPort() {
return m_port;
}
/**
* Get the axis type of a joystick axis.
*
* @return the axis type of a joystick axis.
*/
public int getAxisType(int axis) {
return m_ds.getJoystickAxisType(m_port, axis);
}
/**
* Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble
* and right rumble.
*
* @param type Which rumble value to set
* @param value The normalized value (0 to 1) to set the rumble to
*/
public void setRumble(RumbleType type, float value) {
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
if (type == RumbleType.kLeftRumble) {
m_leftRumble = (short) (value * 65535);
} else {
m_rightRumble = (short) (value * 65535);
}
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set a single HID output value for the joystick.
*
* @param outputNumber The index of the output to set (1-32)
* @param value The value to set the output to
*/
public void setOutput(int outputNumber, boolean value) {
m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1));
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set all HID output values for the joystick.
*
* @param value The 32 bit output value (1 bit for each output)
*/
public void setOutputs(int value) {
m_outputs = value;
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
}
| PeterMitrano/allwpilib | wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java | Java | bsd-3-clause | 12,635 |
package tools;
/*
* Extremely Compiler Collection
* Copyright (c) 2015-2020, Jianping Zeng.
*
* 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.
*/
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* This owns the files read by a parser, handles include stacks,
* and handles diagnostic wrangling.
*
* @author Jianping Zeng
* @version 0.4
*/
public final class SourceMgr {
public enum DiagKind {
DK_Error,
DK_Warning,
DK_Remark,
DK_Note
}
private DiagKind getDiagKindByName(String name) {
switch (name) {
case "error":
return DiagKind.DK_Error;
case "warning":
return DiagKind.DK_Warning;
case "remark":
return DiagKind.DK_Remark;
case "note":
return DiagKind.DK_Note;
default:
Util.assertion("Unknown diagnostic kind!");
return null;
}
}
public static class SMLoc {
private MemoryBuffer buffer;
private int startPos;
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (getClass() != obj.getClass())
return false;
SMLoc loc = (SMLoc) obj;
return loc.buffer.equals(buffer) && startPos == loc.startPos;
}
public static SMLoc get(MemoryBuffer buf, int start) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = start;
return loc;
}
public static SMLoc get(MemoryBuffer buf) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = buf.getBufferStart();
return loc;
}
public boolean isValid() {
return buffer != null;
}
public int getPointer() {
return startPos;
}
}
static class SrcBuffer {
MemoryBuffer buffer;
/**
* This is the location of the parent include, or
* null if it is in the top level.
*/
SMLoc includeLoc;
}
private static class LineNoCache {
int lastQueryBufferID;
MemoryBuffer lastQuery;
int lineNoOfQuery;
}
/**
* This is all of the buffers that we are reading from.
*/
private ArrayList<SrcBuffer> buffers = new ArrayList<>();
/**
* This is the list of directories we should search for
* include files in.
*/
private LinkedList<String> includeDirs;
/**
* This s cache for line number queries.
*/
private LineNoCache lineNoCache;
public void setIncludeDirs(List<String> dirs) {
includeDirs = new LinkedList<>(dirs);
}
public SrcBuffer getBufferInfo(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i);
}
public MemoryBuffer getMemoryBuffer(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).buffer;
}
public SMLoc getParentIncludeLoc(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).includeLoc;
}
public int addNewSourceBuffer(MemoryBuffer buf, SMLoc includeLoc) {
SrcBuffer buffer = new SrcBuffer();
buffer.buffer = buf;
buffer.includeLoc = includeLoc;
buffers.add(buffer);
return buffers.size() - 1;
}
/**
* Search for a file with the specified name in the current directory or
* in one of the {@linkplain #includeDirs}. If no such file found, this return
* ~0, otherwise it returns the buffer ID of the stacked file.
*
* @param filename
* @param includeLoc
* @return
*/
public int addIncludeFile(String filename, SMLoc includeLoc) {
MemoryBuffer newBuf = MemoryBuffer.getFile(filename);
for (int i = 0, e = includeDirs.size(); i < e && newBuf == null; i++) {
String incFile = includeDirs.get(i) + "/" + filename;
newBuf = MemoryBuffer.getFile(incFile);
}
if (newBuf == null)
return ~0;
return addNewSourceBuffer(newBuf, includeLoc);
}
/**
* Return the ID of the buffer containing the specified location, return -1
* if not found.
*
* @param loc
* @return
*/
public int findBufferContainingLoc(SMLoc loc) {
for (int i = 0, e = buffers.size(); i < e; i++) {
MemoryBuffer buf = buffers.get(i).buffer;
if (buf.contains(loc.buffer))
return i;
}
return ~0;
}
/**
* Find the line number for the specified location in the specified file.
*
* @param loc
* @param bufferID
* @return
*/
public int findLineNumber(SMLoc loc, int bufferID) {
if (bufferID == -1) bufferID = findBufferContainingLoc(loc);
Util.assertion(bufferID != -1, "Invalid location!");
int lineNo = 1;
MemoryBuffer buf = getBufferInfo(bufferID).buffer;
if (lineNoCache != null) {
if (lineNoCache.lastQueryBufferID == bufferID
&& lineNoCache.lastQuery.getCharBuffer().equals(buf.getCharBuffer())
&& lineNoCache.lastQuery.getBufferStart() <= buf.getBufferStart()) {
buf = lineNoCache.lastQuery;
lineNo = lineNoCache.lineNoOfQuery;
}
}
for (; !SMLoc.get(buf).equals(loc); buf.advance()) {
if (buf.getCurChar() == '\n')
++lineNo;
}
if (lineNoCache == null)
lineNoCache = new LineNoCache();
lineNoCache.lastQueryBufferID = bufferID;
lineNoCache.lastQuery = buf;
lineNoCache.lineNoOfQuery = lineNo;
return lineNo;
}
public int findLineNumber(SMLoc loc) {
return findLineNumber(loc, -1);
}
/**
* Emit a message about the specified location with the specified string.
* This method is deprecated, you should use {@linkplain Error#printMessage(SMLoc, String, DiagKind)} instead.
*
* @param loc
* @param msg
* @param type If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
*/
@Deprecated
public void printMessage(SMLoc loc, String msg, String type) {
Error.printMessage(loc, msg, getDiagKindByName(type));
}
/**
* Return an SMDiagnostic at the specified location with the specified string.
*
* @param loc
* @param msg
* @param kind If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
* @return
*/
public SMDiagnostic getMessage(SMLoc loc, String msg, DiagKind kind) {
int curBuf = findBufferContainingLoc(loc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
MemoryBuffer curMB = getBufferInfo(curBuf).buffer;
Util.assertion(curMB.getCharBuffer() == loc.buffer.getCharBuffer());
int columnStart = loc.getPointer();
while (columnStart >= curMB.getBufferStart()
&& curMB.getCharAt(columnStart) != '\n'
&& curMB.getCharAt(columnStart) != '\r')
--columnStart;
int columnEnd = loc.getPointer();
while (columnEnd < curMB.length()
&& curMB.getCharAt(columnEnd) != '\n'
&& curMB.getCharAt(columnEnd) != '\r')
++columnEnd;
String printedMsg = "";
switch (kind) {
case DK_Error:
printedMsg = "error: ";
break;
case DK_Remark:
printedMsg = "remark: ";
break;
case DK_Note:
printedMsg = "note: ";
break;
case DK_Warning:
printedMsg = "warning: ";
break;
}
printedMsg += msg;
return new SMDiagnostic(curMB.getBufferIdentifier(), findLineNumber(loc, curBuf),
curMB.getBufferStart() - columnStart, printedMsg,
curMB.getSubString(columnStart, columnEnd));
}
private void printIncludeStack(SMLoc includeLoc, PrintStream os) {
// Top stack.
if (includeLoc.buffer == null) return;
int curBuf = findBufferContainingLoc(includeLoc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
printIncludeStack(getBufferInfo(curBuf).includeLoc, os);
os.printf("Included from %s:%d:\n", getBufferInfo(curBuf).buffer.getBufferIdentifier(),
findLineNumber(includeLoc, curBuf));
}
}
| JianpingZeng/xcc | xcc/java/tools/SourceMgr.java | Java | bsd-3-clause | 8,511 |
package com.logicalpractice.collections;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.* ;
import org.junit.Test;
public class ExpressionTest {
@Test
public void script1() throws Exception {
Person billy = new Person("Billy", "Smith");
Expression<Person,String> testObject = new Expression<Person,String>(){{
each(Person.class).getFirstName();
}};
String result = testObject.apply(billy);
assertThat(result, equalTo("Billy"));
}
}
| tempredirect/lps-collections | src/test/java/com/logicalpractice/collections/ExpressionTest.java | Java | bsd-3-clause | 534 |
package com.btr.proxy.search.desktop.gnome;
import java.io.File;
import java.io.IOException;
import java.net.ProxySelector;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.btr.proxy.search.ProxySearchStrategy;
import com.btr.proxy.selector.direct.NoProxySelector;
import com.btr.proxy.selector.fixed.FixedProxySelector;
import com.btr.proxy.selector.misc.ProtocolDispatchSelector;
import com.btr.proxy.selector.whitelist.ProxyBypassListSelector;
import com.btr.proxy.util.EmptyXMLResolver;
import com.btr.proxy.util.Logger;
import com.btr.proxy.util.PlatformUtil;
import com.btr.proxy.util.ProxyException;
import com.btr.proxy.util.ProxyUtil;
import com.btr.proxy.util.Logger.LogLevel;
/*****************************************************************************
* Loads the Gnome proxy settings from the Gnome GConf settings.
* <p>
* The following settings are extracted from the configuration that is stored
* in <i>.gconf</i> folder found in the user's home directory:
* </p>
* <ul>
* <li><i>/system/http_proxy/use_http_proxy</i> -> bool used only by gnome-vfs </li>
* <li><i>/system/http_proxy/host</i> -> string "my-proxy.example.com" without "http://"</li>
* <li><i>/system/http_proxy/port</i> -> int</li>
* <li><i>/system/http_proxy/use_authentication</i> -> bool</li>
* <li><i>/system/http_proxy/authentication_user</i> -> string</li>
* <li><i>/system/http_proxy/authentication_password</i> -> string</li>
* <li><i>/system/http_proxy/ignore_hosts</i> -> list-of-string</li>
* <li><i>/system/proxy/mode</i> -> string THIS IS THE CANONICAL KEY; SEE BELOW</li>
* <li><i>/system/proxy/secure_host</i> -> string "proxy-for-https.example.com"</li>
* <li><i>/system/proxy/secure_port</i> -> int</li>
* <li><i>/system/proxy/ftp_host</i> -> string "proxy-for-ftp.example.com"</li>
* <li><i>/system/proxy/ftp_port</i> -> int</li>
* <li><i>/system/proxy/socks_host</i> -> string "proxy-for-socks.example.com"</li>
* <li><i>/system/proxy/socks_port</i> -> int</li>
* <li><i>/system/proxy/autoconfig_url</i> -> string "http://proxy-autoconfig.example.com"</li>
* </ul>
* <i>/system/proxy/mode</i> can be either:<br/>
* "none" -> No proxy is used<br/>
* "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/>
* "auto" -> The "/system/proxy/autoconfig_url" key is used <br/>
* <p>
* GNOME Proxy_configuration settings are explained
* <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail
* </p>
* @author Bernd Rosstauscher (proxyvole@rosstauscher.de) Copyright 2009
****************************************************************************/
public class GnomeProxySearchStrategy implements ProxySearchStrategy {
/*************************************************************************
* ProxySelector
* @see java.net.ProxySelector#ProxySelector()
************************************************************************/
public GnomeProxySearchStrategy() {
super();
}
/*************************************************************************
* Loads the proxy settings and initializes a proxy selector for the Gnome
* proxy settings.
* @return a configured ProxySelector, null if none is found.
* @throws ProxyException on file reading error.
************************************************************************/
public ProxySelector getProxySelector() throws ProxyException {
Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings");
Properties settings = readSettings();
String type = settings.getProperty("/system/proxy/mode");
ProxySelector result = null;
if (type == null) {
String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy");
if (useProxy == null) {
return null;
}
type = Boolean.parseBoolean(useProxy)?"manual":"none";
}
if ("none".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy");
result = NoProxySelector.getInstance();
}
if ("manual".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings");
result = setupFixedProxySelector(settings);
}
if ("auto".equals(type)) {
String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", "");
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl);
result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
}
// Wrap into white-list filter?
String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null);
if (result != null && noProxyList != null && noProxyList.trim().length() > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList);
result = new ProxyBypassListSelector(noProxyList, result);
}
return result;
}
/*************************************************************************
* Load the proxy settings from the gconf settings XML file.
* @return the loaded settings stored in a properties object.
* @throws ProxyException on processing error.
************************************************************************/
public Properties readSettings() throws ProxyException {
Properties settings = new Properties();
try {
parseSettings("/system/proxy/", settings);
parseSettings("/system/http_proxy/", settings);
} catch (IOException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e);
throw new ProxyException(e);
}
return settings;
}
/*************************************************************************
* Finds the Gnome GConf settings file.
* @param context the gconf context to parse.
* @return a file or null if does not exist.
************************************************************************/
private File findSettingsFile(String context) {
// Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is.
// But for normal systems this is always stored in .gconf folder in the user's home directory.
File userDir = new File(PlatformUtil.getUserHomeDir());
// Build directory path for context
StringBuilder path = new StringBuilder();
String[] parts = context.split("/");
for (String part : parts) {
path.append(part);
path.append(File.separator);
}
File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml");
if (!settingsFile.exists()) {
Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile);
return null;
}
return settingsFile;
}
/*************************************************************************
* Parse the fixed proxy settings and build an ProxySelector for this a
* chained configuration.
* @param settings the proxy settings to evaluate.
************************************************************************/
private ProxySelector setupFixedProxySelector(Properties settings) {
if (!hasProxySettings(settings)) {
return null;
}
ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
installHttpSelector(settings, ps);
if (useForAllProtocols(settings)) {
ps.setFallbackSelector(ps.getSelector("http"));
} else {
installSecureSelector(settings, ps);
installFtpSelector(settings, ps);
installSocksSelector(settings, ps);
}
return ps;
}
/*************************************************************************
* Check if the http proxy should also be used for all other protocols.
* @param settings to inspect.
* @return true if only one proxy is configured else false.
************************************************************************/
private boolean useForAllProtocols(Properties settings) {
return Boolean.parseBoolean(
settings.getProperty("/system/http_proxy/use_same_proxy", "false"));
}
/*************************************************************************
* Checks if we have Proxy configuration settings in the properties.
* @param settings to inspect.
* @return true if we have found Proxy settings.
************************************************************************/
private boolean hasProxySettings(Properties settings) {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
return proxyHost != null && proxyHost.length() > 0;
}
/*************************************************************************
* Install a http proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installHttpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Install a socks proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installSocksSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/socks_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installFtpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/ftp_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installSecureSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/secure_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort));
ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Parse the settings file and extract all network.proxy.* settings from it.
* @param context the gconf context to parse.
* @param settings the settings object to fill.
* @return the parsed properties.
* @throws IOException on read error.
************************************************************************/
private Properties parseSettings(String context, Properties settings) throws IOException {
// Read settings from file
File settingsFile = findSettingsFile(context);
if (settingsFile == null) {
return settings;
}
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
documentBuilder.setEntityResolver(new EmptyXMLResolver());
Document doc = documentBuilder.parse(settingsFile);
Element root = doc.getDocumentElement();
Node entry = root.getFirstChild();
while (entry != null) {
if ("entry".equals(entry.getNodeName()) && entry instanceof Element) {
String entryName = ((Element)entry).getAttribute("name");
settings.setProperty(context+entryName, getEntryValue((Element) entry));
}
entry = entry.getNextSibling();
}
} catch (SAXException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
} catch (ParserConfigurationException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
}
return settings;
}
/*************************************************************************
* Parse an entry value from a given entry node.
* @param entry the XML node to inspect.
* @return the value, null if it has no value.
************************************************************************/
private String getEntryValue(Element entry) {
String type = entry.getAttribute("type");
if ("int".equals(type) || "bool".equals(type)) {
return entry.getAttribute("value");
}
if ("string".equals(type)) {
NodeList list = entry.getElementsByTagName("stringvalue");
if (list.getLength() > 0) {
return list.item(0).getTextContent();
}
}
if ("list".equals(type)) {
StringBuilder result = new StringBuilder();
NodeList list = entry.getElementsByTagName("li");
// Build comma separated list of items
for (int i = 0; i < list.getLength(); i++) {
if (result.length() > 0) {
result.append(",");
}
result.append(getEntryValue((Element) list.item(i)));
}
return result.toString();
}
return null;
}
}
| brsanthu/proxy-vole | src/main/java/com/btr/proxy/search/desktop/gnome/GnomeProxySearchStrategy.java | Java | bsd-3-clause | 14,860 |
/*
* Copyright (C) 2014 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hbase.async.HBaseClient.ZKClient;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.junit.Before;
import org.junit.Ignore;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.reflect.Whitebox;
import com.stumbleupon.async.Deferred;
@PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class,
GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class,
Executors.class, HashedWheelTimer.class, NioClientBossPool.class,
NioWorkerPool.class })
@Ignore // ignore for test runners
public class BaseTestHBaseClient {
protected static final Charset CHARSET = Charset.forName("ASCII");
protected static final byte[] COMMA = { ',' };
protected static final byte[] TIMESTAMP = "1234567890".getBytes();
protected static final byte[] INFO = getStatic("INFO");
protected static final byte[] REGIONINFO = getStatic("REGIONINFO");
protected static final byte[] SERVER = getStatic("SERVER");
protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' };
protected static final byte[] KEY = { 'k', 'e', 'y' };
protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' };
protected static final byte[] FAMILY = { 'f' };
protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' };
protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' };
protected static final byte[] EMPTY_ARRAY = new byte[0];
protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE);
protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890");
protected static final RegionInfo region = mkregion("table", "table,,1234567890");
protected static final int RS_PORT = 50511;
protected static final String ROOT_IP = "192.168.0.1";
protected static final String META_IP = "192.168.0.2";
protected static final String REGION_CLIENT_IP = "192.168.0.3";
protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient";
protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient";
protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient";
protected HBaseClient client = null;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionInfo, RegionClient> region2client;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre;
/** Extracted from {@link #client}. */
protected HashMap<String, RegionClient> ip2client;
/** Extracted from {@link #client}. */
protected Counter num_nsre_rpcs;
/** Fake client supposedly connected to -ROOT-. */
protected RegionClient rootclient;
/** Fake client supposedly connected to .META.. */
protected RegionClient metaclient;
/** Fake client supposedly connected to our fake test table. */
protected RegionClient regionclient;
/** Each new region client is dumped here */
protected List<RegionClient> region_clients = new ArrayList<RegionClient>();
/** Fake Zookeeper client */
protected ZKClient zkclient;
/** Fake channel factory */
protected NioClientSocketChannelFactory channel_factory;
/** Fake channel returned from the factory */
protected SocketChannel chan;
/** Fake timer for testing */
protected FakeTimer timer;
@Before
public void before() throws Exception {
region_clients.clear();
rootclient = mock(RegionClient.class);
when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME);
metaclient = mock(RegionClient.class);
when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME);
regionclient = mock(RegionClient.class);
when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME);
zkclient = mock(ZKClient.class);
channel_factory = mock(NioClientSocketChannelFactory.class);
chan = mock(SocketChannel.class);
timer = new FakeTimer();
when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>());
PowerMockito.mockStatic(Executors.class);
PowerMockito.when(Executors.defaultThreadFactory())
.thenReturn(mock(ThreadFactory.class));
PowerMockito.when(Executors.newCachedThreadPool())
.thenReturn(mock(ExecutorService.class));
PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments()
.thenReturn(channel_factory);
PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments()
.thenReturn(timer);
PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments()
.thenReturn(mock(NioClientBossPool.class));
PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments()
.thenReturn(mock(NioWorkerPool.class));
client = PowerMockito.spy(new HBaseClient("test-quorum-spec"));
Whitebox.setInternalState(client, "zkclient", zkclient);
Whitebox.setInternalState(client, "rootregion", rootclient);
Whitebox.setInternalState(client, "jitter_percent", 0);
regions_cache = Whitebox.getInternalState(client, "regions_cache");
region2client = Whitebox.getInternalState(client, "region2client");
client2regions = Whitebox.getInternalState(client, "client2regions");
got_nsre = Whitebox.getInternalState(client, "got_nsre");
ip2client = Whitebox.getInternalState(client, "ip2client");
injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT);
injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT);
when(channel_factory.newChannel(any(ChannelPipeline.class)))
.thenReturn(chan);
when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class));
when(rootclient.toString()).thenReturn("Mock RootClient");
PowerMockito.doAnswer(new Answer<RegionClient>(){
@Override
public RegionClient answer(InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final String endpoint = (String)args[0] + ":" + (Integer)args[1];
final RegionClient rc = mock(RegionClient.class);
when(rc.getRemoteAddress()).thenReturn(endpoint);
client2regions.put(rc, new ArrayList<RegionInfo>());
region_clients.add(rc);
return rc;
}
}).when(client, "newClient", anyString(), anyInt());
}
/**
* Injects an entry in the local caches of the client.
*/
protected void injectRegionInCache(final RegionInfo region,
final RegionClient client,
final String ip) {
regions_cache.put(region.name(), region);
region2client.put(region, client);
ArrayList<RegionInfo> regions = client2regions.get(client);
if (regions == null) {
regions = new ArrayList<RegionInfo>(1);
client2regions.put(client, regions);
}
regions.add(region);
ip2client.put(ip, client);
}
// ----------------- //
// Helper functions. //
// ----------------- //
protected void clearCaches(){
regions_cache.clear();
region2client.clear();
client2regions.clear();
}
protected static <T> T getStatic(final String fieldname) {
return Whitebox.getInternalState(HBaseClient.class, fieldname);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for all keys of {@link #TABLE}.
*/
protected static ArrayList<KeyValue> metaRow() {
return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for {@link #TABLE}.
* @param start_key The start key of the region in this entry.
* @param stop_key The stop key of the region in this entry.
*/
protected static ArrayList<KeyValue> metaRow(final byte[] start_key,
final byte[] stop_key) {
final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);
row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));
row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));
return row;
}
protected static KeyValue metaRegionInfo( final byte[] start_key,
final byte[] stop_key, final boolean offline, final boolean splitting,
final byte[] table) {
final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);
final byte is_splitting = (byte) (splitting ? 1 : 0);
final byte[] regioninfo = concat(
new byte[] {
0, // version
(byte) stop_key.length, // vint: stop key length
},
stop_key,
offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline
Bytes.fromLong(name.hashCode()), // long: region ID (make it random)
new byte[] { (byte) name.length }, // vint: region name length
name, // region name
new byte[] {
is_splitting, // boolean: splitting
(byte) start_key.length, // vint: start key length
},
start_key
);
return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);
}
protected static RegionInfo mkregion(final String table, final String name) {
return new RegionInfo(table.getBytes(), name.getBytes(),
HBaseClient.EMPTY_ARRAY);
}
protected static byte[] anyBytes() {
return any(byte[].class);
}
/** Concatenates byte arrays together. */
protected static byte[] concat(final byte[]... arrays) {
int len = 0;
for (final byte[] array : arrays) {
len += array.length;
}
final byte[] result = new byte[len];
len = 0;
for (final byte[] array : arrays) {
System.arraycopy(array, 0, result, len, array.length);
len += array.length;
}
return result;
}
/** Creates a new Deferred that's already called back. */
protected static <T> Answer<Deferred<T>> newDeferred(final T result) {
return new Answer<Deferred<T>>() {
public Deferred<T> answer(final InvocationOnMock invocation) {
return Deferred.fromResult(result);
}
};
}
/**
* A fake {@link Timer} implementation that fires up tasks immediately.
* Tasks are called immediately from the current thread and a history of the
* various tasks is logged.
*/
static final class FakeTimer extends HashedWheelTimer {
final List<Map.Entry<TimerTask, Long>> tasks =
new ArrayList<Map.Entry<TimerTask, Long>>();
final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();
boolean run = true;
@Override
public Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
try {
tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));
if (run) {
task.run(null); // Argument never used in this code base.
}
final Timeout timeout = mock(Timeout.class);
timeouts.add(timeout);
return timeout; // Return value never used in this code base.
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + task, e);
}
}
@Override
public Set<Timeout> stop() {
run = false;
return new HashSet<Timeout>(timeouts);
}
}
/**
* A fake {@link org.jboss.netty.util.Timer} implementation.
* Instead of executing the task it will store that task in a internal state
* and provides a function to start the execution of the stored task.
* This implementation thus allows the flexibility of simulating the
* things that will be going on during the time out period of a TimerTask.
* This was mainly return to simulate the timeout period for
* alreadyNSREdRegion test, where the region will be in the NSREd mode only
* during this timeout period, which was difficult to simulate using the
* above {@link FakeTimer} implementation, as we don't get back the control
* during the timeout period
*
* Here it will hold at most two Tasks. We have two tasks here because when
* one is being executed, it may call for newTimeOut for another task.
*/
static final class FakeTaskTimer extends HashedWheelTimer {
protected TimerTask newPausedTask = null;
protected TimerTask pausedTask = null;
@Override
public synchronized Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
if (pausedTask == null) {
pausedTask = task;
} else if (newPausedTask == null) {
newPausedTask = task;
} else {
throw new IllegalStateException("Cannot Pause Two Timer Tasks");
}
return null;
}
@Override
public Set<Timeout> stop() {
return null;
}
public boolean continuePausedTask() {
if (pausedTask == null) {
return false;
}
try {
if (newPausedTask != null) {
throw new IllegalStateException("Cannot be in this state");
}
pausedTask.run(null); // Argument never used in this code base
pausedTask = newPausedTask;
newPausedTask = null;
return true;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + pausedTask, e);
}
}
}
/**
* Generate and return a mocked HBase RPC for testing purposes with a valid
* Deferred that can be called on execution.
* @param deferred A deferred to watch for results
* @return The RPC to pass through unit tests.
*/
protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) {
final HBaseRpc rpc = mock(HBaseRpc.class);
rpc.attempt = 0;
when(rpc.getDeferred()).thenReturn(deferred);
when(rpc.toString()).thenReturn("MockRPC");
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (deferred != null) {
deferred.callback(invocation.getArguments()[0]);
} else {
System.out.println("Deferred was null!!");
}
return null;
}
}).when(rpc).callback(Object.class);
return rpc;
}
}
| manolama/asynchbase | test/BaseTestHBaseClient.java | Java | bsd-3-clause | 17,282 |
package xcordion.impl.command;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Ignore;
public class ForEachCommandTest {
@Test
@Ignore
public void testPlaceholder() {
Assert.fail("WRITE ME");
}
}
| pobrelkey/xcordion | xcordion2/xcordion2-java/src/test/java/xcordion/impl/command/ForEachCommandTest.java | Java | bsd-3-clause | 282 |
/**
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms
*/
package visualoozie.api;
public class WorkflowNode {
public enum NodeType{
START
, KILL
, DECISION
, FORK
, JOIN
, END
, ACTION
}
private String name;
private NodeType type;
private String[] to;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public NodeType getType() { return type; }
public void setType(NodeType type) { this.type = type; }
public String[] getTo() { return to; }
public void setTo(String[] to) { this.to = to; }
}
| jaoki/visualoozie | src/main/java/visualoozie/api/WorkflowNode.java | Java | bsd-3-clause | 747 |
package com.navisens.pojostick.navishare;
import com.navisens.motiondnaapi.MotionDna;
import com.navisens.pojostick.navisenscore.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by Joseph on 11/30/17.
* <p>
* NaviShare provides functionality for communicating with other devices
* </p>
*/
@SuppressWarnings("unused")
public class NaviShare implements NavisensPlugin {
private static final long QUERY_INTERVAL = 500000000;
private String host, port, room;
private boolean changed;
private boolean configured;
private boolean connected;
private NavisensCore core;
private final Set<String> rooms;
private final Set<NaviShareListener> listeners;
private long roomsQueriedAt;
@SuppressWarnings("unused")
public NaviShare() {
this.rooms = new HashSet<>();
this.listeners = new HashSet<>();
this.roomsQueriedAt = System.nanoTime();
}
/**
* Configure a server. This does not connect to it yet, but is required before calling connect.
*
* @param host server ip
* @param port server port
* @return a reference to this NaviShare
*/
@SuppressWarnings("unused")
public NaviShare configure(String host, String port) {
core.getSettings().overrideHost(null, null);
this.host = host;
this.port = port;
this.changed = true;
this.configured = true;
return this;
}
/**
* Connect to a room in the server.
*
* @param room The room to connect to
* @return Whether this device connected to a server
*/
@SuppressWarnings("unused")
public boolean connect(String room) {
core.getSettings().overrideRoom(null);
if (configured) {
if (connected && !changed) {
core.getMotionDna().setUDPRoom(room);
} else {
this.disconnect();
core.getMotionDna().startUDP(room, host, port);
this.connected = true;
}
this.changed = false;
return true;
}
return false;
}
/**
* Disconnect from the server.
*/
@SuppressWarnings("unused")
public void disconnect() {
core.getMotionDna().stopUDP();
this.connected = false;
}
/**
* Connect to a public test server. Don't use this for official release, as it is public
* and can get filled up quickly. Each organization can claim one room, so if you need
* multiple independent servers within your organization, you should test on a private
* server instead, and use configure(host, port) to target that server instead.
*/
@SuppressWarnings("unused")
public boolean testConnect() {
if (!connected) {
this.disconnect();
core.getMotionDna().startUDP();
return this.connected = true;
}
return false;
}
/**
* Send a message to all other devices on the network
*
* @param msg A string to send, recommended web safe
*/
@SuppressWarnings("unused")
public void sendMessage(String msg) {
if (connected) {
core.getMotionDna().sendUDPPacket(msg);
}
}
/**
* Add a listener to receive network events
*
* @param listener The listener to receive events
* @return Whether the listener was added successfully
*/
@SuppressWarnings("unused")
public boolean addListener(NaviShareListener listener) {
return this.listeners.add(listener);
}
/**
* Remove a listener to stop receiving events
*
* @param listener Ths listener to remove
* @return Whether the listener was removed successfully
*/
@SuppressWarnings("unused")
public boolean removeListener(NaviShareListener listener) {
return this.listeners.remove(listener);
}
/**
* Track a room so you can query its status. Call refreshRoomStatus to
* receive a new roomStatus event
*
* @param room A room to track
* @return Whether the room was added to be tracked or not
*/
@SuppressWarnings("unused")
public boolean trackRoom(String room) {
return this.rooms.add(room);
}
/**
* Stop tracking a room. Call refreshRoomStatus to receive a new roomStatusEvent
*
* @param room A room to stop tracking
* @return Whether the room was removed from tracking or not
*/
@SuppressWarnings("unused")
public boolean untrackRoom(String room) {
return this.rooms.remove(room);
}
/**
* Refresh the status of any tracked rooms. Updates will be received from the
* roomOccupancyChanged event
* @return Whether a refresh request was sent or not
*/
@SuppressWarnings("unused")
public boolean refreshRoomStatus() {
final long now = System.nanoTime();
if (connected && now - roomsQueriedAt > QUERY_INTERVAL) {
roomsQueriedAt = now;
core.getMotionDna().sendUDPQueryRooms(rooms.toArray(new String[0]));
return true;
}
return false;
}
@Override
public boolean init(NavisensCore navisensCore, Object[] objects) {
this.core = navisensCore;
core.subscribe(this, NavisensCore.NETWORK_DATA);
core.getSettings().requestNetworkRate(100);
core.applySettings();
return true;
}
@Override
public boolean stop() {
this.disconnect();
core.remove(this);
return true;
}
@Override
public void receiveMotionDna(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna.NetworkCode networkCode, Map<String, ?> map) {
switch (networkCode) {
case RAW_NETWORK_DATA:
for (NaviShareListener listener : listeners)
listener.messageReceived((String) map.get("ID"), (String) map.get("payload"));
break;
case ROOM_CAPACITY_STATUS:
for (NaviShareListener listener : listeners)
listener.roomOccupancyChanged((Map<String, Integer>) map.get("payload"));
break;
case EXCEEDED_SERVER_ROOM_CAPACITY:
for (NaviShareListener listener : listeners)
listener.serverCapacityExceeded();
this.disconnect();
break;
case EXCEEDED_ROOM_CONNECTION_CAPACITY:
for (NaviShareListener listener : listeners)
listener.roomCapacityExceeded();
this.disconnect();
break;
}
}
@Override
public void receivePluginData(String id, int operator, Object... payload) {
}
@Override
public void reportError(MotionDna.ErrorCode errorCode, String s) {
}
}
| navisens/Android-Plugin | navishare/src/main/java/com/navisens/pojostick/navishare/NaviShare.java | Java | bsd-3-clause | 6,973 |
package org.mafagafogigante.dungeon.stats;
import org.mafagafogigante.dungeon.game.Id;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
/**
* CauseOfDeath class that defines what kind of death happened and the ID of the related Item or Spell.
*/
public class CauseOfDeath implements Serializable {
private static final CauseOfDeath UNARMED = new CauseOfDeath(TypeOfCauseOfDeath.UNARMED, new Id("UNARMED"));
private final TypeOfCauseOfDeath type;
private final Id id;
/**
* Constructs a CauseOfDeath with the specified TypeOfCauseOfDeath and ID.
*
* @param type a TypeOfCauseOfDeath
* @param id an ID
*/
public CauseOfDeath(@NotNull TypeOfCauseOfDeath type, @NotNull Id id) {
this.type = type;
this.id = id;
}
/**
* Convenience method that returns a CauseOfDeath that represents an unarmed kill.
*/
public static CauseOfDeath getUnarmedCauseOfDeath() {
return UNARMED;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
CauseOfDeath that = (CauseOfDeath) object;
return id.equals(that.id) && type == that.type;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + id.hashCode();
return result;
}
@Override
public String toString() {
return String.format("%s : %s", type, id);
}
}
| ffurkanhas/dungeon | src/main/java/org/mafagafogigante/dungeon/stats/CauseOfDeath.java | Java | bsd-3-clause | 1,483 |
package net.jloop.rejoice;
import net.jloop.rejoice.types.Symbol;
import net.jloop.rejoice.types.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MacroHelper {
public static List<Value> collect(Env env, Iterator<Value> input, Symbol terminator) {
List<Value> output = new ArrayList<>();
while (true) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Input stream ended before finding the terminating symbol '" + terminator.print() + "'");
}
Value next = input.next();
if (next instanceof Symbol) {
if (next.equals(terminator)) {
return output;
}
Function function = env.lookup((Symbol) next);
if (function instanceof Macro) {
env.trace().push((Symbol) next);
Iterator<Value> values = ((Macro) function).call(env, input);
while (values.hasNext()) {
output.add(values.next());
}
env.trace().pop();
} else {
output.add(next);
}
} else {
output.add(next);
}
}
}
@SuppressWarnings("unchecked")
public static <T extends Value> T match(Iterator<Value> input, Type type) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match " + type.print());
}
Value next = input.next();
if (type == next.type()) {
return (T) next;
} else {
throw new RuntimeError("MACRO", "Expecting to match " + type.print() + ", but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
public static void match(Iterator<Value> input, Symbol symbol) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match ^symbol '" + symbol.print() + "'");
}
Value next = input.next();
if (!next.equals(symbol)) {
throw new RuntimeError("MACRO", "Expecting to match symbol '" + symbol.print() + "' , but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
}
| jeremyheiler/rejoice | src/main/java/net/jloop/rejoice/MacroHelper.java | Java | bsd-3-clause | 2,365 |
/*
* Copyright Matt Palmer 2011-2013, All rights reserved.
*
* This code is licensed under a standard 3-clause BSD license:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * The names of its contributors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.byteseek.searcher.sequence.sunday;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import net.byteseek.io.reader.Window;
import net.byteseek.io.reader.WindowReader;
import net.byteseek.matcher.bytes.ByteMatcher;
import net.byteseek.matcher.sequence.SequenceMatcher;
import net.byteseek.object.factory.DoubleCheckImmutableLazyObject;
import net.byteseek.object.factory.LazyObject;
import net.byteseek.object.factory.ObjectFactory;
import net.byteseek.searcher.SearchResult;
import net.byteseek.searcher.SearchUtils;
import net.byteseek.searcher.sequence.AbstractSequenceSearcher;
/**
*
* @author Matt Palmer
*/
public final class SundayQuickSearcher extends AbstractSequenceSearcher {
private final LazyObject<int[]> forwardInfo;
private final LazyObject<int[]> backwardInfo;
/**
* Constructs a Sunday Quick searcher given a {@link SequenceMatcher}
* to search for.
*
* @param sequence The sequence to search for.
*/
public SundayQuickSearcher(final SequenceMatcher sequence) {
super(sequence);
forwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new ForwardInfoFactory());
backwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new BackwardInfoFactory());
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchForwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get the objects needed to search:
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int length = sequence.length();
final int finalPosition = bytes.length - length;
final int lastLoopPosition = finalPosition - 1;
final int lastPosition = toPosition < lastLoopPosition?
toPosition : lastLoopPosition;
int searchPosition = fromPosition > 0?
fromPosition : 0;
// Search forwards. The loop does not check for the final
// position, as we shift on the byte after the sequence.
while (searchPosition <= lastPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[bytes[searchPosition + length] & 0xFF];
}
// Check the final position if necessary:
if (searchPosition == finalPosition &&
toPosition >= finalPosition &&
sequence.matches(bytes, finalPosition)) {
return SearchUtils.singleResult(finalPosition, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchForwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
final int length = sequence.length();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately after the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition <= toPosition &&
(window = reader.getWindow(searchPosition + length)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition + length);
final int arrayEndPosition = window.length() - 1;
final long distanceToEnd = toPosition - window.getWindowPosition() + length ;
final int finalPosition = distanceToEnd < arrayEndPosition?
(int) distanceToEnd : arrayEndPosition;
int arraySearchPosition = arrayStartPosition;
// Search fowards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// after the sequence (so would get an IndexOutOfBoundsException in the final position).
while (arraySearchPosition < finalPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition += shift;
arraySearchPosition += shift;
}
// Check final position if necessary:
if (arraySearchPosition == finalPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchBackwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get objects needed to search:
final int[] safeShifts = backwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int lastLoopPosition = toPosition > 1?
toPosition : 1;
final int firstPossiblePosition = bytes.length - sequence.length();
int searchPosition = fromPosition < firstPossiblePosition ?
fromPosition : firstPossiblePosition;
// Search backwards. The loop does not check the
// first position in the array, because we shift on the byte
// immediately before the current search position.
while (searchPosition >= lastLoopPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[bytes[searchPosition - 1] & 0xFF];
}
// Check for first position if necessary:
if (searchPosition == 0 &&
toPosition < 1 &&
sequence.matches(bytes, 0)) {
return SearchUtils.singleResult(0, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchBackwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately before the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition >= toPosition &&
(window = reader.getWindow(searchPosition - 1)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition - 1);
// Search to the beginning of the array, or the final search position,
// whichver comes first.
final long endRelativeToWindow = toPosition - window.getWindowPosition();
final int arrayEndSearchPosition = endRelativeToWindow > 0?
(int) endRelativeToWindow : 0;
int arraySearchPosition = arrayStartPosition;
// Search backwards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// before it.
while (arraySearchPosition > arrayEndSearchPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition -= shift;
arraySearchPosition -= shift;
}
// Check final position if necessary:
if (arraySearchPosition == arrayEndSearchPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareForwards() {
forwardInfo.get();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareBackwards() {
backwardInfo.get();
}
@Override
public String toString() {
return getClass().getSimpleName() + "[sequence:" + matcher + ']';
}
private final class ForwardInfoFactory implements ObjectFactory<int[]> {
private ForwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching forwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the end of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence plus one.
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the end of the sequence, where the last position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = 0; sequenceByteIndex < numBytes; sequenceByteIndex++) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromEnd = numBytes - sequenceByteIndex;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromEnd;
}
}
return shifts;
}
}
private final class BackwardInfoFactory implements ObjectFactory<int[]> {
private BackwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching backwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the beginning of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence
// (negative if search direction is reversed)
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the start of the sequence, where the first position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = numBytes - 1; sequenceByteIndex >= 0; sequenceByteIndex--) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromStart = sequenceByteIndex + 1;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromStart;
}
}
return shifts;
}
}
} | uzen/byteseek | src/net/byteseek/searcher/sequence/sunday/SundayQuickSearcher.java | Java | bsd-3-clause | 14,817 |
/**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.system.procs;
/**
* Marker interface for dynamically loaded postgis data types, to be used by {@link ServiceLoader}.
*/
public interface OptionalProcProvider extends ProcProvider {
}
| frode-carlsen/pgjdbc-ng | src/main/java/com/impossibl/postgres/system/procs/OptionalProcProvider.java | Java | bsd-3-clause | 1,789 |
//
// $Id$
package org.ductilej.tests;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests handling of varags with parameterized variable argument. Edge case extraordinaire!
*/
public class ParamVarArgsTest
{
public static interface Predicate<T> {
boolean apply (T arg);
}
public static <T> Predicate<T> or (final Predicate<? super T>... preds) {
return new Predicate<T>() {
public boolean apply (T arg) {
for (Predicate<? super T> pred : preds) {
if (pred.apply(arg)) {
return true;
}
}
return false;
}
};
}
@SuppressWarnings("unchecked") // this use of parameterized varargs is safe
@Test public void testParamVarArgs () {
Predicate<Integer> test = or(FALSE);
assertEquals(false, test.apply(1));
}
protected static final Predicate<Integer> FALSE = new Predicate<Integer>() {
public boolean apply (Integer arg) {
return false;
}
};
}
| scaladyno/ductilej | src/test/java/org/ductilej/tests/ParamVarArgsTest.java | Java | bsd-3-clause | 1,100 |
package ga;
import engine.*;
import java.util.*;
public class GAPopulation {
/* Evolutionary parameters: */
public int size; // size of the population
public int ngens; // total number of generations
public int currgen; // current generation
/* Crossover parameters */
int tournamentK; // size of tournament
int elite; // size of elite
int immigrant; // number of new random individuals
double mutrate; // chance that a mutation will occur
double xoverrate; // chance that the xover will occur
/* Containers */
public ArrayList<Genome> individual;
Genome parent;
Trainer T;
/* Progress data */
public double[] max_fitness;
public double[] avg_fitness;
public double[] terminals; // average total number of terminals
public double[] bigterminals; // average total number of sig. terminals
/**
* Initialize and load parameters.
* Parameter comp is a node from a previous
* scenario, which is used for distance calculations.
*/
public GAPopulation(Genome comp)
{
individual = new ArrayList<Genome>();
parent = comp;
// reading parameters
Parameter param = Parameter.getInstance();
String paramval;
paramval = param.getParam("population size");
if (paramval != null)
size = Integer.valueOf(paramval);
else
{
System.err.println("\"population size\" not defined on parameter file.");
size = 10;
}
paramval = param.getParam("generation number");
if (paramval != null)
ngens = Integer.valueOf(paramval);
else
{
System.err.println("\"generation number\" not defined on parameter file.");
ngens = 10;
}
paramval = param.getParam("tournament K");
if (paramval != null)
tournamentK = Integer.valueOf(paramval);
else
{
System.err.println("\"tournament K\" not defined on parameter file.");
tournamentK = 5;
}
paramval = param.getParam("elite size");
if (paramval != null)
elite = Integer.valueOf(paramval);
else
{
System.err.println("\"elite size\" not defined on parameter file.");
elite = 1;
}
paramval = param.getParam("immigrant size");
if (paramval != null)
immigrant = Integer.valueOf(paramval);
else
{
System.err.println("\"immigrant size\" not defined on parameter file.");
immigrant = 0;;
}
paramval = param.getParam("mutation rate");
if (paramval != null)
mutrate = Double.valueOf(paramval);
else
{
System.err.println("\"mutation rate\" not defined on parameter file.");
mutrate = 0.01;
}
paramval = param.getParam("crossover rate");
if (paramval != null)
xoverrate = Double.valueOf(paramval);
else
{
System.err.println("\"crossover rate\" not defined on parameter file.");
xoverrate = 0.9;
}
}
/**
* Initialize the new population and the local
* variables. Startd is the target date for the
* @param startd
*/
public void initPopulation(Date startd)
{
T = new Trainer(startd);
currgen = 0;
for (int i = 0; i < size; i++)
{
Genome n = new Genome();
n.init();
individual.add(n);
}
max_fitness = new double[ngens];
avg_fitness = new double[ngens];
terminals = new double[ngens];
bigterminals = new double[ngens];
}
/**
* Runs one generation loop
*
*/
public void runGeneration()
{
eval();
breed();
currgen++;
}
/**
* update the values of the maxfitness/avg fitness/etc
* public arrays;
*/
public void updateStatus()
{
Parameter p = Parameter.getInstance();
String param = p.getParam("asset treshold");
double tresh = Double.valueOf(param);
avg_fitness[currgen-1] = 0;
terminals[currgen-1] = 0;
bigterminals[currgen-1] = 0;
for (int i = 0; i < individual.size(); i++)
{
avg_fitness[currgen-1] += individual.get(i).fitness;
terminals[currgen-1] += individual.get(i).countAsset(0.0);
bigterminals[currgen-1] += individual.get(i).countAsset(tresh);
}
max_fitness[currgen-1] = individual.get(0).fitness;
avg_fitness[currgen-1] /= size;
terminals[currgen-1] /= size;
bigterminals[currgen-1] /= size;
}
/**
* Calculates the fitness value for each individual
* in the population.
*/
public void eval()
{
for (int i = 0; i < size; i++)
{
individual.get(i).eval(T);
}
Collections.sort(individual);
}
/**
* Perform selection, crossover, mutation in
* order to create a new population.
*
* Assumes the eval function has already been
* performed.
*
*/
public void breed()
{
RNG d = RNG.getInstance();
ArrayList<Genome> nextGen = new ArrayList<Genome>();
Genome p1,p2;
// elite: (few copied individuals)
for (int i = 0; i < elite; i++)
{
nextGen.add(individual.get(i).copy());
}
// immigrant: (usually 0)
for (int i = 0; i < immigrant; i++)
{
Genome n = new Genome();
n.init();
nextGen.add(n);
}
// crossover:
for (int i = 0; i < size - (immigrant + elite); i+=2)
{
// selection - the selection function should
// return copies already.
p1 = Tournament();
p2 = Tournament();
// rolls for xover
if (d.nextDouble() < xoverrate)
{
p1.crossover(p2);
}
// rolls for mutation
if (d.nextDouble() < mutrate)
p1.mutation();
if (d.nextDouble() < mutrate)
p2.mutation();
nextGen.add(p1);
nextGen.add(p2);
}
individual = nextGen;
}
/**
* Select one parent from the population by using
* fitness-proportional tournament selection
* (eat candidate has a chance proportional to his
* fitness of being chosen).
*
* The function copy the chosen candidate and send
* him back.
* @return
*/
public Genome Tournament()
{
RNG d = RNG.getInstance();
Genome[] list = new Genome[tournamentK];
double[] rank = new double[tournamentK];
double sum = 0.0;
double ticket = 0.0;
double min = 0.0;
/* Selects individuals and removes negative fitness */
for (int i = 0; i < tournamentK; i++)
{
list[i] = individual.get(d.nextInt(size));
if (list[i].fitness < min)
min = list[i].fitness;
}
/* I'm not sure if this is the best way to
* make the proportion between the fitnesses.
* Some sort of scaling factor should be put here
* to avoit high fitnesses from superdominating.
*
* But maybe the tournament proccess already guarantees this?
*/
for (int i = 0; i < tournamentK; i++)
{
sum += list[i].fitness - min;
rank[i] = sum;
}
ticket = d.nextDouble()*sum;
for (int i = 0; i < tournamentK; i++)
{
if ((ticket) <= rank[i])
return list[i].copy();
}
// should never get here
System.err.println("x" + ticket + " + " + sum);
System.err.println("Warning: MemeTournament - reached unreachable line");
return list[0].copy();
}
}
| caranha/MTGA-old | code/ga/GAPopulation.java | Java | bsd-3-clause | 6,710 |
/**
* (c) 2017 TIBCO Software Inc. All rights reserved.
*
* Except as specified below, this software is licensed pursuant to the Eclipse Public License v. 1.0.
* The details can be found in the file LICENSE.
*
* The following proprietary files are included as a convenience, and may not be used except pursuant
* to valid license to Composite Information Server or TIBCO(R) Data Virtualization Server:
* csadmin-XXXX.jar, csarchive-XXXX.jar, csbase-XXXX.jar, csclient-XXXX.jar, cscommon-XXXX.jar,
* csext-XXXX.jar, csjdbc-XXXX.jar, csserverutil-XXXX.jar, csserver-XXXX.jar, cswebapi-XXXX.jar,
* and customproc-XXXX.jar (where -XXXX is an optional version number). Any included third party files
* are licensed under the terms contained in their own accompanying LICENSE files, generally named .LICENSE.txt.
*
* This software is licensed AS-IS. Support for this software is not covered by standard maintenance agreements with TIBCO.
* If you would like to obtain assistance with this software, such assistance may be obtained through a separate paid consulting
* agreement with TIBCO.
*
*/
package com.tibco.ps.deploytool.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextException;
import com.tibco.ps.common.CommonConstants;
import com.tibco.ps.common.exception.CompositeException;
import com.tibco.ps.common.util.CommonUtils;
import com.tibco.ps.deploytool.dao.ServerDAO;
import com.tibco.ps.deploytool.dao.wsapi.ServerWSDAOImpl;
public class ServerManagerImpl implements ServerManager {
private ServerDAO serverDAO = null;
// Get the configuration property file set in the environment with a default of deploy.properties
String propertyFile = CommonUtils.getFileOrSystemPropertyValue(CommonConstants.propertyFile, "CONFIG_PROPERTY_FILE");
private static Log logger = LogFactory.getLog(ServerManagerImpl.class);
// @Override
public void startServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "startServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.START.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while starting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void stopServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "stopServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.STOP.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while stopping server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void restartServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "restartServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.RESTART.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while restarting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
private void serverManagerAction(String actionName, String serverId, String pathToServersXML) throws CompositeException {
String prefix = "serverManagerAction";
String processedIds = null;
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
// Set the Module Action Objective
String s1 = (serverId == null) ? "no_serverId" : "Ids="+serverId;
System.setProperty("MODULE_ACTION_OBJECTIVE", actionName+" : "+s1);
// Validate whether the files exist or not
if (!CommonUtils.fileExists(pathToServersXML)) {
throw new CompositeException("File ["+pathToServersXML+"] does not exist.");
}
try {
if(logger.isInfoEnabled()){
logger.info("processing action "+ actionName + " on server "+ serverId);
}
getServerDAO().takeServerManagerAction(actionName, serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error on server action (" + actionName + "): ", e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
/**
* @return serverDAO
*/
public ServerDAO getServerDAO() {
if(this.serverDAO == null){
this.serverDAO = new ServerWSDAOImpl();
}
return serverDAO;
}
/**
* @param set serverDAO
*/
public void setServerDAO(ServerDAO serverDAO) {
this.serverDAO = serverDAO;
}
}
| cisco/PDTool | src/com/tibco/ps/deploytool/services/ServerManagerImpl.java | Java | bsd-3-clause | 5,374 |
/*
* Created on Oct 18, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.tolweb.tapestry;
import java.util.Collection;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.IRequestCycle;
import org.tolweb.hibernate.TitleIllustration;
import org.tolweb.tapestry.injections.BaseInjectable;
import org.tolweb.tapestry.injections.ImageInjectable;
import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.ImageVersion;
import org.tolweb.treegrow.main.NodeImage;
import org.tolweb.treegrow.main.StringUtils;
/**
* @author dmandel
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class TitleIllustrations extends BaseComponent implements
ImageInjectable, BaseInjectable {
@SuppressWarnings("unchecked")
public abstract Collection getIllustrations();
public abstract TitleIllustration getCurrentIllustration();
public abstract void setCurrentIllustration(TitleIllustration value);
public abstract void setIsSingleIllustration(boolean value);
public abstract boolean getIsSingleIllustration();
public abstract int getIndex();
public abstract void setContributor(Contributor contributor);
public String getAltText() {
if (getCurrentIllustration().getImage() != null) {
NodeImage img = getCurrentIllustration().getImage();
if (StringUtils.notEmpty(img.getAltText())) {
return img.getAltText();
} else {
return " ";
}
} else {
return " ";
}
}
public void prepareForRender(IRequestCycle cycle) {
super.prepareForRender(cycle);
if (getIllustrations() != null && getIllustrations().size() == 1) {
setIsSingleIllustration(true);
} else {
setIsSingleIllustration(false);
}
}
public String getCurrentImageLocation() {
TitleIllustration currentIllustration = getCurrentIllustration();
ImageVersion version = currentIllustration.getVersion();
String url;
if (StringUtils.isEmpty(version.getFileName())) {
url = getImageDAO().generateAndSaveVersion(version);
} else {
url = getImageUtils().getVersionUrl(currentIllustration.getVersion());
}
return url;
}
public String getCurrentImageClass() {
if (getIsSingleIllustration()) {
return "singletillus";
} else {
return null;
}
}
}
| tolweb/tolweb-app | OnlineContributors/src/org/tolweb/tapestry/TitleIllustrations.java | Java | bsd-3-clause | 2,683 |
/*
* GaussianKernel.java
*
* Created on September 25, 2004, 4:52 PM
*/
package jpview.graphics;
/**
* This class creates a kernel for use by an AffineTransformOp
*
* @author clyon
*/
public class GaussianKernel {
private int radius = 5;
private float sigma = 1;
private float[] kernel;
/** Creates a new instance of GaussianKernel */
public GaussianKernel() {
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius
*
* @param r
* the radius for the gaussian kernel
*/
public GaussianKernel(int r) {
radius = r;
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius and sigma value
*
* @param r
* the radius of the blur
* @param s
* the sigma value for the kernel
*/
public GaussianKernel(int r, float s) {
radius = r;
sigma = s;
kernel = makeKernel();
}
private float[] makeKernel() {
kernel = new float[radius * radius];
float sum = 0;
for (int y = 0; y < radius; y++) {
for (int x = 0; x < radius; x++) {
int off = y * radius + x;
int xx = x - radius / 2;
int yy = y - radius / 2;
kernel[off] = (float) Math.pow(Math.E, -(xx * xx + yy * yy)
/ (2 * (sigma * sigma)));
sum += kernel[off];
}
}
for (int i = 0; i < kernel.length; i++)
kernel[i] /= sum;
return kernel;
}
/**
* Dumps a string representation of the kernel to standard out
*/
public void dump() {
for (int x = 0; x < radius; x++) {
for (int y = 0; y < radius; y++) {
System.out.print(kernel[y * radius + x] + "\t");
}
System.out.println();
}
}
/**
* returns the kernel as a float [] suitable for use with an affine
* transform
*
* @return the kernel values
*/
public float[] getKernel() {
return kernel;
}
public static void main(String args[]) {
GaussianKernel gk = new GaussianKernel(5, 100f);
gk.dump();
}
}
| synergynet/synergynet3 | synergynet3-museum-parent/synergynet3-museum-table/src/main/java/jpview/graphics/GaussianKernel.java | Java | bsd-3-clause | 2,024 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeClassQualifiedName;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.CronetEngine;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.urlconnection.CronetHttpURLConnection;
import org.chromium.net.urlconnection.CronetURLStreamHandlerFactory;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.GuardedBy;
/**
* CronetEngine using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
@UsedByReflection("CronetEngine.java")
@VisibleForTesting
public class CronetUrlRequestContext extends CronetEngine {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long mUrlRequestContextAdapter = 0;
private Thread mNetworkThread;
private boolean mNetworkQualityEstimatorEnabled;
/**
* Locks operations on network quality listeners, because listener
* addition and removal may occur on a different thread from notification.
*/
private final Object mNetworkQualityLock = new Object();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityRttListener> mRttListenerList =
new ObserverList<NetworkQualityRttListener>();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityThroughputListener> mThroughputListenerList =
new ObserverList<NetworkQualityThroughputListener>();
@GuardedBy("mFinishedListenerLock")
private final List<RequestFinishedInfo.Listener> mFinishedListenerList =
new ArrayList<RequestFinishedInfo.Listener>();
/**
* Synchronize access to mCertVerifierData.
*/
private ConditionVariable mWaitGetCertVerifierDataComplete = new ConditionVariable();
/** Holds CertVerifier data. */
private String mCertVerifierData;
@UsedByReflection("CronetEngine.java")
public CronetUrlRequestContext(final CronetEngine.Builder builder) {
CronetLibraryLoader.ensureInitialized(builder.getContext(), builder);
nativeSetMinLogLevel(getLoggingLevel());
synchronized (mLock) {
mUrlRequestContextAdapter = nativeCreateRequestContextAdapter(
createNativeUrlRequestContextConfig(builder.getContext(), builder));
if (mUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed.");
}
mNetworkQualityEstimatorEnabled = builder.networkQualityEstimatorEnabled();
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
CronetLibraryLoader.ensureInitializedOnMainThread(builder.getContext());
synchronized (mLock) {
// mUrlRequestContextAdapter is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
nativeInitRequestContextOnMainThread(mUrlRequestContextAdapter);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@VisibleForTesting
public static long createNativeUrlRequestContextConfig(
final Context context, CronetEngine.Builder builder) {
final long urlRequestContextConfig = nativeCreateRequestContextConfig(
builder.getUserAgent(), builder.storagePath(), builder.quicEnabled(),
builder.getDefaultQuicUserAgentId(context), builder.http2Enabled(),
builder.sdchEnabled(), builder.dataReductionProxyKey(),
builder.dataReductionProxyPrimaryProxy(), builder.dataReductionProxyFallbackProxy(),
builder.dataReductionProxySecureProxyCheckUrl(), builder.cacheDisabled(),
builder.httpCacheMode(), builder.httpCacheMaxSize(), builder.experimentalOptions(),
builder.mockCertVerifier(), builder.networkQualityEstimatorEnabled(),
builder.publicKeyPinningBypassForLocalTrustAnchorsEnabled(),
builder.certVerifierData());
for (Builder.QuicHint quicHint : builder.quicHints()) {
nativeAddQuicHint(urlRequestContextConfig, quicHint.mHost, quicHint.mPort,
quicHint.mAlternatePort);
}
for (Builder.Pkp pkp : builder.publicKeyPins()) {
nativeAddPkp(urlRequestContextConfig, pkp.mHost, pkp.mHashes, pkp.mIncludeSubdomains,
pkp.mExpirationDate.getTime());
}
return urlRequestContextConfig;
}
@Override
public UrlRequest createRequest(String url, UrlRequest.Callback callback, Executor executor,
int priority, Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration) {
synchronized (mLock) {
checkHaveAdapter();
boolean metricsCollectionEnabled = false;
synchronized (mFinishedListenerLock) {
metricsCollectionEnabled = !mFinishedListenerList.isEmpty();
}
return new CronetUrlRequest(this, url, priority, callback, executor, requestAnnotations,
metricsCollectionEnabled, disableCache, disableConnectionMigration);
}
}
@Override
public BidirectionalStream createBidirectionalStream(String url,
BidirectionalStream.Callback callback, Executor executor, String httpMethod,
List<Map.Entry<String, String>> requestHeaders,
@BidirectionalStream.Builder.StreamPriority int priority, boolean disableAutoFlush,
boolean delayRequestHeadersUntilFirstFlush) {
synchronized (mLock) {
checkHaveAdapter();
return new CronetBidirectionalStream(this, url, priority, callback, executor,
httpMethod, requestHeaders, disableAutoFlush,
delayRequestHeadersUntilFirstFlush);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getVersionString() {
return "Cronet/" + ImplVersion.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
nativeDestroy(mUrlRequestContextAdapter);
mUrlRequestContextAdapter = 0;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
synchronized (mLock) {
checkHaveAdapter();
nativeStartNetLogToFile(mUrlRequestContextAdapter, fileName, logAll);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(mUrlRequestContextAdapter);
}
}
@Override
public String getCertVerifierData(long timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be a positive value");
} else if (timeout == 0) {
timeout = 100;
}
mWaitGetCertVerifierDataComplete.close();
synchronized (mLock) {
checkHaveAdapter();
nativeGetCertVerifierData(mUrlRequestContextAdapter);
}
mWaitGetCertVerifierDataComplete.block(timeout);
return mCertVerifierData;
}
// This method is intentionally non-static to ensure Cronet native library
// is loaded by class constructor.
@Override
public byte[] getGlobalMetricsDeltas() {
return nativeGetHistogramDeltas();
}
@VisibleForTesting
@Override
public void configureNetworkQualityEstimatorForTesting(
boolean useLocalHostRequests, boolean useSmallerResponses) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mLock) {
checkHaveAdapter();
nativeConfigureNetworkQualityEstimatorForTesting(
mUrlRequestContextAdapter, useLocalHostRequests, useSmallerResponses);
}
}
@Override
public void addRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, true);
}
}
mRttListenerList.addObserver(listener);
}
}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mRttListenerList.removeObserver(listener);
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, true);
}
}
mThroughputListenerList.addObserver(listener);
}
}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mThroughputListenerList.removeObserver(listener);
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.add(listener);
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.remove(listener);
}
}
@Override
public URLConnection openConnection(URL url) {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronetHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronetURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() {
mActiveRequestCount.decrementAndGet();
}
@VisibleForTesting
public long getUrlRequestContextAdapter() {
synchronized (mLock) {
checkHaveAdapter();
return mUrlRequestContextAdapter;
}
}
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
private boolean haveRequestContextAdapter() {
return mUrlRequestContextAdapter != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityRttListener listener : mRttListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRttObservation(rttMs, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onThroughputObservation(
final int throughputKbps, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityThroughputListener listener : mThroughputListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onThroughputObservation(throughputKbps, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onGetCertVerifierData(String certVerifierData) {
mCertVerifierData = certVerifierData;
mWaitGetCertVerifierDataComplete.open();
}
void reportFinished(final CronetUrlRequest request) {
final RequestFinishedInfo requestInfo = request.getRequestFinishedInfo();
ArrayList<RequestFinishedInfo.Listener> currentListeners;
synchronized (mFinishedListenerLock) {
currentListeners = new ArrayList<RequestFinishedInfo.Listener>(mFinishedListenerList);
}
for (final RequestFinishedInfo.Listener listener : currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
// Native methods are implemented in cronet_url_request_context_adapter.cc.
private static native long nativeCreateRequestContextConfig(String userAgent,
String storagePath, boolean quicEnabled, String quicUserAgentId, boolean http2Enabled,
boolean sdchEnabled, String dataReductionProxyKey,
String dataReductionProxyPrimaryProxy, String dataReductionProxyFallbackProxy,
String dataReductionProxySecureProxyCheckUrl, boolean disableCache, int httpCacheMode,
long httpCacheMaxSize, String experimentalOptions, long mockCertVerifier,
boolean enableNetworkQualityEstimator,
boolean bypassPublicKeyPinningForLocalTrustAnchors, String certVerifierData);
private static native void nativeAddQuicHint(
long urlRequestContextConfig, String host, int port, int alternatePort);
private static native void nativeAddPkp(long urlRequestContextConfig, String host,
byte[][] hashes, boolean includeSubdomains, long expirationTime);
private static native long nativeCreateRequestContextAdapter(long urlRequestContextConfig);
private static native int nativeSetMinLogLevel(int loggingLevel);
private static native byte[] nativeGetHistogramDeltas();
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeDestroy(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStartNetLogToFile(long nativePtr, String fileName, boolean logAll);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStopNetLog(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeGetCertVerifierData(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeInitRequestContextOnMainThread(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeConfigureNetworkQualityEstimatorForTesting(
long nativePtr, boolean useLocalHostRequests, boolean useSmallerResponses);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideRTTObservations(long nativePtr, boolean should);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideThroughputObservations(long nativePtr, boolean should);
}
| danakj/chromium | components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java | Java | bsd-3-clause | 21,435 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* This program 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
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class RemoveValueLoggable extends AbstractBFileLoggable {
protected long page;
protected short tid;
protected byte[] oldData;
protected int offset = 0;
protected int len;
/**
*
*
* @param page
* @param tid
* @param oldData
* @param offset
* @param len
* @param fileId
* @param transaction
*/
public RemoveValueLoggable(Txn transaction, byte fileId, long page, short tid, byte[] oldData, int offset, int len) {
super(BFile.LOG_REMOVE_VALUE, fileId, transaction);
this.page = page;
this.tid = tid;
this.oldData = oldData;
this.offset = offset;
this.len = len;
}
/**
* @param broker
* @param transactionId
*/
public RemoveValueLoggable(DBBroker broker, long transactionId) {
super(broker, transactionId);
}
public void write(ByteBuffer out) {
super.write(out);
out.putInt((int) page);
out.putShort(tid);
out.putShort((short) len);
out.put(oldData, offset, len);
}
public void read(ByteBuffer in) {
super.read(in);
page = in.getInt();
tid = in.getShort();
len = in.getShort();
oldData = new byte[len];
in.get(oldData);
}
public int getLogSize() {
return super.getLogSize() + len + 8;
}
public void redo() throws LogException {
getIndexFile().redoRemoveValue(this);
}
public void undo() throws LogException {
getIndexFile().undoRemoveValue(this);
}
public String dump() {
return super.dump() + " - remove value with tid " + tid + " from page " + page;
}
}
| NCIP/cadsr-cgmdr-nci-uk | src/org/exist/storage/index/RemoveValueLoggable.java | Java | bsd-3-clause | 3,088 |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemAssert;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* COUNT, GROUP, UNION.
*
* @author rzhang
*/
public class MetricUnionTransform implements Transform {
//~ Static fields/initializers *******************************************************************************************************************
/** The metric name for this transform is result. */
public static final String RESULT_METRIC_NAME = "result";
//~ Instance fields ******************************************************************************************************************************
private final ValueReducer valueUnionReducer;
private final String defaultScope;
private final String defaultMetricName;
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new ReduceTransform object.
*
* @param valueUnionReducer valueReducerOrMapping The valueMapping.
*/
protected MetricUnionTransform(ValueReducer valueUnionReducer) {
this.defaultScope = TransformFactory.Function.UNION.name();
this.defaultMetricName = TransformFactory.DEFAULT_METRIC_NAME;
this.valueUnionReducer = valueUnionReducer;
}
//~ Methods **************************************************************************************************************************************
@Override
public String getResultScopeName() {
return defaultScope;
}
/**
* If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
*
* @param metrics The metrics to transform.
*
* @return The transformed metrics.
*/
@Override
public List<Metric> transform(List<Metric> metrics) {
return union(metrics);
}
/**
* Performs a columnar union of metrics.
*
* @param metrics The metrics to merge.
*
* @return The merged metrics.
*/
public List<Metric> union(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
if (metrics.isEmpty()) {
return metrics;
}
Metric newMetric = reduce(metrics);
Map<Long, String> reducedDatapoints = newMetric.getDatapoints();
Set<Long> sharedTimestamps = reducedDatapoints.keySet();
Map<Long, String> unionDatapoints = new TreeMap<Long, String>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> entry : metric.getDatapoints().entrySet()) {
if (!sharedTimestamps.contains(entry.getKey())) {
unionDatapoints.put(entry.getKey(), entry.getValue());
}
}
}
newMetric.addDatapoints(unionDatapoints);
return Arrays.asList(newMetric);
}
/**
* Reduce transform for the list of metrics.
*
* @param metrics The list of metrics to reduce.
*
* @return The reduced metric.
*/
protected Metric reduce(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
/*
* if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
*/
MetricDistiller distiller = new MetricDistiller();
distiller.distill(metrics);
Map<Long, List<String>> collated = collate(metrics);
Map<Long, String> minDatapoints = reduce(collated, metrics);
String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
Metric newMetric = new Metric(defaultScope, newMetricName);
newMetric.setDisplayName(distiller.getDisplayName());
newMetric.setUnits(distiller.getUnits());
newMetric.setTags(distiller.getTags());
newMetric.setDatapoints(minDatapoints);
return newMetric;
}
private Map<Long, List<String>> collate(List<Metric> metrics) {
Map<Long, List<String>> collated = new HashMap<Long, List<String>>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> point : metric.getDatapoints().entrySet()) {
if (!collated.containsKey(point.getKey())) {
collated.put(point.getKey(), new ArrayList<String>());
}
collated.get(point.getKey()).add(point.getValue());
}
}
return collated;
}
private Map<Long, String> reduce(Map<Long, List<String>> collated, List<Metric> metrics) {
Map<Long, String> reducedDatapoints = new HashMap<>();
for (Map.Entry<Long, List<String>> entry : collated.entrySet()) {
if (entry.getValue().size() < metrics.size()) {
continue;
}
reducedDatapoints.put(entry.getKey(), this.valueUnionReducer.reduce(entry.getValue()));
}
return reducedDatapoints;
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
throw new UnsupportedOperationException("Union transform can't be used with constants!");
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new UnsupportedOperationException("Union doesn't need list of list");
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| rmelick/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/MetricUnionTransform.java | Java | bsd-3-clause | 7,287 |
package org.cagrid.gme.common.exceptions;
import java.io.IOException;
@SuppressWarnings("serial")
public class SchemaParsingException extends IOException {
public SchemaParsingException() {
super();
}
public SchemaParsingException(String s) {
super(s);
}
}
| NCIP/cagrid | cagrid/Software/core/caGrid/projects/globalModelExchange/src/org/cagrid/gme/common/exceptions/SchemaParsingException.java | Java | bsd-3-clause | 296 |
/* Copyright (c) 2009, University of Oslo, Norway
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the University of Oslo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package vtk.text.tl.expr;
import java.math.BigDecimal;
import vtk.text.tl.Symbol;
public class Multiply extends NumericOperator {
public Multiply(Symbol symbol) {
super(symbol);
}
@Override
protected Object evalNumeric(BigDecimal n1, BigDecimal n2) {
return n1.multiply(n2);
}
}
| vtkio/vtk | src/main/java/vtk/text/tl/expr/Multiply.java | Java | bsd-3-clause | 1,929 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends SimpleRobot {
private Joystick joystick = new Joystick(1);
private Drivetrain drivetrain;
private BowlerArm arm;
Compressor compressor;
Pan pan;
//int port_1 = 7; //these ports were placeholders, no longer applicable
//int port_2 = 7;
public RobotTemplate() {
drivetrain = new Drivetrain();
arm = new BowlerArm();
pan = new Pan();
compressor = new Compressor(7, 7);//7 for the switch, 7 for the relay
}
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
drivetrain.set(1, 1);
sleep(5000);
drivetrain.set(0,0);
// arm.auto();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
compressor.start();
arm.setSolenoid(-1);
while (isOperatorControl()) {
//drivetrain updates
double lstick = -joystick.getRawAxis(2);
double rstick = -joystick.getRawAxis(4);
drivetrain.set(Math.abs(lstick) * lstick, Math.abs(rstick) * rstick); //If I'm not mistaken, this is the most convenient way to square in Java?
//pan updates version 2 (Amita); this is basic and can be used for backup
if(joystick.getRawButton(10)){
pan.endGame();
}
else{
pan.resetServo();
}
//bowler arm updates
if (joystick.getRawButton(7)) {
arm.rampDown();
} else if (joystick.getRawButton(5)) {
arm.rampUp();
} else {
arm.setRamp(0);
}
arm.setSolenoid((int) joystick.getRawAxis(6));
}
}
/*
*changes the servo state based on the button being pressed.
*once it is pressed, it is set to the opposite of what is was at the start, ditto for release.
*/
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
public void updateDrivetrain(){
}
public void updateArm(){
}
public void updatePan(){
}
public static void sleep(long ms){
long t=System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<t){
//do nothing!
}
}
}
| 2374/chris | src/edu/wpi/first/wpilibj/templates/RobotTemplate.java | Java | bsd-3-clause | 3,586 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.BuildConfig;
import java.lang.ref.WeakReference;
/**
* An {@link OptimizedFrameLayout} that increases the speed of frequent view lookup by ID by caching
* the result of the lookup. Adding or removing a view with the same ID as a cached version will
* cause the cache to be invalidated for that view and cause a re-lookup the next time it is
* queried. The goal of this view type is to be used in cases where child views are frequently
* accessed or reused, for example as part of a {@link androidx.recyclerview.widget.RecyclerView}.
* The logic in the {@link #fastFindViewById(int)} method would be in {@link #findViewById(int)} if
* it weren't final on the {@link View} class.
*
* {@link android.view.ViewGroup.OnHierarchyChangeListener}s cannot be used on ViewGroups that are
* children of this group since they would overwrite the listeners that are critical to this class'
* functionality.
*
* Usage:
* Use the same way that you would use a normal {@link android.widget.FrameLayout}, but instead
* of using {@link #findViewById(int)} to access views, use {@link #fastFindViewById(int)}.
*/
public class ViewLookupCachingFrameLayout extends OptimizedFrameLayout {
/** A map containing views that have had lookup performed on them for quicker access. */
private final SparseArray<WeakReference<View>> mCachedViews = new SparseArray<>();
/** The hierarchy listener responsible for notifying the cache that the tree has changed. */
@VisibleForTesting
final OnHierarchyChangeListener mListener = new OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, this);
}
@Override
public void onChildViewRemoved(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, null);
}
};
/** Default constructor for use in XML. */
public ViewLookupCachingFrameLayout(Context context, AttributeSet atts) {
super(context, atts);
setOnHierarchyChangeListener(mListener);
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
assert listener == mListener : "Hierarchy change listeners cannot be set for this group!";
super.setOnHierarchyChangeListener(listener);
}
/**
* Set the hierarchy listener that invalidates relevant parts of the cache when subtrees change.
* @param view The root of the tree to attach listeners to.
* @param listener The listener to attach (null to unset).
*/
private void setHierarchyListenerOnTree(View view, OnHierarchyChangeListener listener) {
if (!(view instanceof ViewGroup)) return;
ViewGroup group = (ViewGroup) view;
group.setOnHierarchyChangeListener(listener);
for (int i = 0; i < group.getChildCount(); i++) {
setHierarchyListenerOnTree(group.getChildAt(i), listener);
}
}
/**
* Does the same thing as {@link #findViewById(int)} but caches the result if not null.
* Subsequent lookups are cheaper as a result. Adding or removing a child view invalidates
* the cache for the ID of the view removed and causes a re-lookup.
* @param id The ID of the view to lookup.
* @return The view if it exists.
*/
@Nullable
public View fastFindViewById(@IdRes int id) {
WeakReference<View> ref = mCachedViews.get(id);
View view = null;
if (ref != null) view = ref.get();
if (view == null) view = findViewById(id);
if (BuildConfig.DCHECK_IS_ON) {
assert view == findViewById(id) : "View caching logic is broken!";
assert ref == null
|| ref.get() != null : "Cache held reference to garbage collected view!";
}
if (view != null) mCachedViews.put(id, new WeakReference<>(view));
return view;
}
@VisibleForTesting
SparseArray<WeakReference<View>> getCache() {
return mCachedViews;
}
}
| endlessm/chromium-browser | ui/android/java/src/org/chromium/ui/widget/ViewLookupCachingFrameLayout.java | Java | bsd-3-clause | 4,641 |
/*
* Copyright (c) 2016, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.groupon.lex.metrics;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
*
* @author ariane
*/
public class SimpleMetricTest {
@Test
public void constructor_number() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), (short)7);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 7, m.getValue());
}
@Test
public void constructor_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), "chocoladevla");
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateString("chocoladevla", m.getValue());
}
@Test
public void constructor_bool() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), true);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateBoolean(true, m.getValue());
}
@Test
public void constructor_metric() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromNumberValue(9000));
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 9000, m.getValue());
}
@Test
public void constructor_empty() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.EMPTY);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateEmpty(m.getValue());
}
@Test
public void to_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertThat(m.toString(), Matchers.allOf(containsString("foobar"), containsString("19")));
}
@Test
public void equality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertEquals(m0, m1);
assertEquals(m0.hashCode(), m1.hashCode());
}
@Test
public void inequality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(17));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m2 = new SimpleMetric(MetricName.valueOf("fizzbuzz"), MetricValue.fromIntValue(19));
assertNotEquals(m0, m1);
assertNotEquals(m0, m2);
assertNotEquals(m1, m0);
assertNotEquals(m1, m2);
assertNotEquals(m2, m0);
assertNotEquals(m2, m1);
}
@Test
public void equal_across_types() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertFalse(m.equals(null));
assertFalse(m.equals(new Object()));
}
}
| groupon/monsoon | intf/src/test/java/com/groupon/lex/metrics/SimpleMetricTest.java | Java | bsd-3-clause | 4,854 |
/*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.patientdiscovery.inbound.deferred.request;
import gov.hhs.fha.nhinc.aspect.InboundProcessingEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.patientdiscovery.PatientDiscoveryAuditor;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.AdapterPatientDiscoveryDeferredReqProxy;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.AdapterPatientDiscoveryDeferredReqProxyObjectFactory;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.MCCIIN000002UV01EventDescriptionBuilder;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.PRPAIN201305UV02EventDescriptionBuilder;
import org.hl7.v3.MCCIIN000002UV01;
import org.hl7.v3.PRPAIN201305UV02;
public abstract class AbstractInboundPatientDiscoveryDeferredRequest implements InboundPatientDiscoveryDeferredRequest {
private final AdapterPatientDiscoveryDeferredReqProxyObjectFactory adapterFactory;
public AbstractInboundPatientDiscoveryDeferredRequest(AdapterPatientDiscoveryDeferredReqProxyObjectFactory factory) {
adapterFactory = factory;
}
abstract MCCIIN000002UV01 process(PRPAIN201305UV02 request, AssertionType assertion);
abstract PatientDiscoveryAuditor getAuditLogger();
/**
* Processes the PD Deferred request message. This call will audit the message and send it to the Nhin.
*
* @param request
* @param assertion
* @return MCCIIN000002UV01
*/
@InboundProcessingEvent(beforeBuilder = PRPAIN201305UV02EventDescriptionBuilder.class,
afterReturningBuilder = MCCIIN000002UV01EventDescriptionBuilder.class,
serviceType = "Patient Discovery Deferred Request",
version = "1.0")
public MCCIIN000002UV01 respondingGatewayPRPAIN201305UV02(PRPAIN201305UV02 request, AssertionType assertion) {
auditRequestFromNhin(request, assertion);
MCCIIN000002UV01 response = process(request, assertion);
auditResponseToNhin(response, assertion);
return response;
}
protected MCCIIN000002UV01 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) {
AdapterPatientDiscoveryDeferredReqProxy proxy = adapterFactory.getAdapterPatientDiscoveryDeferredReqProxy();
return proxy.processPatientDiscoveryAsyncReq(request, assertion);
}
private void auditRequestFromNhin(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().auditNhinDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION);
}
private void auditResponseToNhin(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION,
NhincConstants.AUDIT_LOG_NHIN_INTERFACE);
}
protected void auditRequestToAdapter(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().auditAdapterDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION);
}
protected void auditResponseFromAdapter(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION,
NhincConstants.AUDIT_LOG_ADAPTER_INTERFACE);
}
}
| sailajaa/CONNECT | Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/inbound/deferred/request/AbstractInboundPatientDiscoveryDeferredRequest.java | Java | bsd-3-clause | 5,048 |
package com.mistraltech.smogen.codegenerator.javabuilder;
public class InterfaceMethodBuilder extends MethodSignatureBuilder<InterfaceMethodBuilder> {
private InterfaceMethodBuilder() {
}
public static InterfaceMethodBuilder anInterfaceMethod() {
return new InterfaceMethodBuilder();
}
@Override
public String build(JavaBuilderContext context) {
return super.build(context) + ";";
}
}
| mistraltechnologies/smogen | src/main/java/com/mistraltech/smogen/codegenerator/javabuilder/InterfaceMethodBuilder.java | Java | bsd-3-clause | 432 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.sync;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Pair;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.test.util.browser.sync.SyncTestUtil;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.sync.protocol.EntitySpecifics;
import org.chromium.sync.protocol.SessionHeader;
import org.chromium.sync.protocol.SessionSpecifics;
import org.chromium.sync.protocol.SessionTab;
import org.chromium.sync.protocol.SessionWindow;
import org.chromium.sync.protocol.SyncEnums;
import org.chromium.sync.protocol.TabNavigation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Test suite for the open tabs (sessions) sync data type.
*/
public class OpenTabsTest extends SyncTestBase {
private static final String TAG = "OpenTabsTest";
private static final String OPEN_TABS_TYPE = "Sessions";
// EmbeddedTestServer is preferred here but it can't be used. The test server
// serves pages on localhost and Chrome doesn't sync localhost URLs as typed URLs.
// This type of URL requires no external data connection or resources.
private static final String URL = "data:text,OpenTabsTestURL";
private static final String URL2 = "data:text,OpenTabsTestURL2";
private static final String URL3 = "data:text,OpenTabsTestURL3";
private static final String SESSION_TAG_PREFIX = "FakeSessionTag";
private static final String FAKE_CLIENT = "FakeClient";
// The client name for tabs generated locally will vary based on the device the test is
// running on, so it is determined once in the setUp() method and cached here.
private String mClientName;
// A counter used for generating unique session tags. Resets to 0 in setUp().
private int mSessionTagCounter;
// A container to store OpenTabs information for data verification.
private static class OpenTabs {
public final String headerId;
public final List<String> tabIds;
public final List<String> urls;
private OpenTabs(String headerId, List<String> tabIds, List<String> urls) {
this.headerId = headerId;
this.tabIds = tabIds;
this.urls = urls;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
setUpTestAccountAndSignInToSync();
mClientName = getClientName();
mSessionTagCounter = 0;
}
// Test syncing an open tab from client to server.
@LargeTest
@Feature({"Sync"})
public void testUploadOpenTab() throws Exception {
loadUrl(URL);
waitForLocalTabsForClient(mClientName, URL);
waitForServerTabs(URL);
}
/*
// Test syncing multiple open tabs from client to server.
@LargeTest
@Feature({"Sync"})
https://crbug.com/592437
*/
@FlakyTest
public void testUploadMultipleOpenTabs() throws Exception {
loadUrl(URL);
loadUrlInNewTab(URL2);
loadUrlInNewTab(URL3);
waitForLocalTabsForClient(mClientName, URL, URL2, URL3);
waitForServerTabs(URL, URL2, URL3);
}
/*
// Test syncing an open tab from client to server.
@LargeTest
@Feature({"Sync"})
https://crbug.com/592437
*/
@FlakyTest
public void testUploadAndCloseOpenTab() throws Exception {
loadUrl(URL);
// Can't have zero tabs, so we have to open two to test closing one.
loadUrlInNewTab(URL2);
waitForLocalTabsForClient(mClientName, URL, URL2);
waitForServerTabs(URL, URL2);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
TabModelSelector selector = FeatureUtilities.isDocumentMode(getActivity())
? ChromeApplication.getDocumentTabModelSelector()
: getActivity().getTabModelSelector();
assertTrue(TabModelUtils.closeCurrentTab(selector.getCurrentModel()));
}
});
waitForLocalTabsForClient(mClientName, URL);
waitForServerTabs(URL);
}
// Test syncing an open tab from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadOpenTab() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL);
}
// Test syncing multiple open tabs from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadMultipleOpenTabs() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3);
}
// Test syncing a tab deletion from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadDeletedOpenTab() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL);
// Delete on server, sync, and verify deleted locally.
deleteServerTabsForClient(FAKE_CLIENT);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT);
}
// Test syncing multiple tab deletions from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadMultipleDeletedOpenTabs() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3);
// Delete on server, sync, and verify deleted locally.
deleteServerTabsForClient(FAKE_CLIENT);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT);
}
private String makeSessionTag() {
return SESSION_TAG_PREFIX + (mSessionTagCounter++);
}
private void addFakeServerTabs(String clientName, String... urls)
throws InterruptedException {
String tag = makeSessionTag();
EntitySpecifics header = makeSessionEntity(tag, clientName, urls.length);
mFakeServerHelper.injectUniqueClientEntity(tag, header);
for (int i = 0; i < urls.length; i++) {
EntitySpecifics tab = makeTabEntity(tag, urls[i], i);
// It is critical that the name here is "<tag> <tabNodeId>", otherwise sync crashes
// when it tries to sync due to the use of TabIdToTag in sessions_sync_manager.cc.
mFakeServerHelper.injectUniqueClientEntity(tag + " " + i, tab);
}
}
private EntitySpecifics makeSessionEntity(String tag, String clientName, int numTabs) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.header = new SessionHeader();
specifics.session.header.clientName = clientName;
specifics.session.header.deviceType = SyncEnums.TYPE_PHONE;
SessionWindow window = new SessionWindow();
window.windowId = 0;
window.selectedTabIndex = 0;
window.tab = new int[numTabs];
for (int i = 0; i < numTabs; i++) {
window.tab[i] = i;
}
specifics.session.header.window = new SessionWindow[] { window };
return specifics;
}
private EntitySpecifics makeTabEntity(String tag, String url, int id) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.tabNodeId = id;
SessionTab tab = new SessionTab();
tab.tabId = id;
tab.currentNavigationIndex = 0;
TabNavigation nav = new TabNavigation();
nav.virtualUrl = url;
tab.navigation = new TabNavigation[] { nav };
specifics.session.tab = tab;
return specifics;
}
private void deleteServerTabsForClient(String clientName) throws JSONException {
OpenTabs openTabs = getLocalTabsForClient(clientName);
mFakeServerHelper.deleteEntity(openTabs.headerId);
for (String tabId : openTabs.tabIds) {
mFakeServerHelper.deleteEntity(tabId);
}
}
private void waitForLocalTabsForClient(final String clientName, String... urls)
throws InterruptedException {
final List<String> urlList = new ArrayList<String>(urls.length);
for (String url : urls) urlList.add(url);
pollInstrumentationThread(Criteria.equals(urlList, new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
return getLocalTabsForClient(clientName).urls;
}
}));
}
private void waitForServerTabs(final String... urls)
throws InterruptedException {
pollInstrumentationThread(
new Criteria("Expected server open tabs: " + Arrays.toString(urls)) {
@Override
public boolean isSatisfied() {
try {
return mFakeServerHelper.verifySessions(urls);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
private String getClientName() throws Exception {
pollInstrumentationThread(Criteria.equals(2, new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return SyncTestUtil.getLocalData(mContext, OPEN_TABS_TYPE).size();
}
}));
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
for (Pair<String, JSONObject> tabEntity : tabEntities) {
if (tabEntity.second.has("header")) {
return tabEntity.second.getJSONObject("header").getString("client_name");
}
}
throw new IllegalStateException("No client name found.");
}
private static class HeaderInfo {
public final String sessionTag;
public final String headerId;
public final List<String> tabIds;
public HeaderInfo(String sessionTag, String headerId, List<String> tabIds) {
this.sessionTag = sessionTag;
this.headerId = headerId;
this.tabIds = tabIds;
}
}
// Distills the local session data into a simple data object for the given client.
private OpenTabs getLocalTabsForClient(String clientName) throws JSONException {
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
// Output lists.
List<String> urls = new ArrayList<String>();
List<String> tabEntityIds = new ArrayList<String>();
HeaderInfo info = findHeaderInfoForClient(clientName, tabEntities);
if (info.sessionTag == null) {
// No client was found. Here we still want to return an empty list of urls.
return new OpenTabs("", tabEntityIds, urls);
}
Map<String, String> tabIdsToUrls = new HashMap<String, String>();
Map<String, String> tabIdsToEntityIds = new HashMap<String, String>();
findTabMappings(info.sessionTag, tabEntities, tabIdsToUrls, tabIdsToEntityIds);
// Convert the tabId list to the url list.
for (String tabId : info.tabIds) {
urls.add(tabIdsToUrls.get(tabId));
tabEntityIds.add(tabIdsToEntityIds.get(tabId));
}
return new OpenTabs(info.headerId, tabEntityIds, urls);
}
// Find the header entity for clientName and extract its sessionTag and tabId list.
private HeaderInfo findHeaderInfoForClient(
String clientName, List<Pair<String, JSONObject>> tabEntities) throws JSONException {
String sessionTag = null;
String headerId = null;
List<String> tabIds = new ArrayList<String>();
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject header = tabEntity.second.optJSONObject("header");
if (header != null && header.getString("client_name").equals(clientName)) {
sessionTag = tabEntity.second.getString("session_tag");
headerId = tabEntity.first;
JSONArray windows = header.getJSONArray("window");
if (windows.length() == 0) {
// The client was found but there are no tabs.
break;
}
assertEquals("Only single windows are supported.", 1, windows.length());
JSONArray tabs = windows.getJSONObject(0).getJSONArray("tab");
for (int i = 0; i < tabs.length(); i++) {
tabIds.add(tabs.getString(i));
}
break;
}
}
return new HeaderInfo(sessionTag, headerId, tabIds);
}
// Find the associated tabs and record their tabId -> url and entityId mappings.
private void findTabMappings(String sessionTag, List<Pair<String, JSONObject>> tabEntities,
// Populating these maps is the output of this function.
Map<String, String> tabIdsToUrls, Map<String, String> tabIdsToEntityIds)
throws JSONException {
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject json = tabEntity.second;
if (json.has("tab") && json.getString("session_tag").equals(sessionTag)) {
JSONObject tab = json.getJSONObject("tab");
int i = tab.getInt("current_navigation_index");
String tabId = tab.getString("tab_id");
String url = tab.getJSONArray("navigation")
.getJSONObject(i).getString("virtual_url");
tabIdsToUrls.put(tabId, url);
tabIdsToEntityIds.put(tabId, tabEntity.first);
}
}
}
}
| was4444/chromium.src | chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java | Java | bsd-3-clause | 14,827 |
//To Test:http://localhost:8080/nbia-auth/services/v3/getProtectionGrpList?format=html
package gov.nih.nci.nbia.restAPI;
import gov.nih.nci.nbia.dao.TrialDataProvenanceDAO;
import gov.nih.nci.nbia.util.SpringApplicationContext;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.dao.RoleSearchCriteria;
import gov.nih.nci.security.dao.SearchCriteria;
import gov.nih.nci.security.exceptions.CSConfigurationException;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.dao.DataAccessException;
@Path("/v3/getProtectionGrpList")
public class V3_getProtectionGrpList extends getData{
private static final String[] columns={"pgName", "description", "dataSetName"};
public final static String TEXT_CSV = "text/csv";
@Context private HttpServletRequest httpRequest;
/**
* This method get a list of names of protection group
*
* @return String - list of names of protection group
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML, TEXT_CSV})
public Response constructResponse(@QueryParam("format") String format) {
List<Object[]> data = null;
try {
UserProvisioningManager upm = getUpm();
java.util.List<ProtectionGroup> protectionGrpLst = upm.getProtectionGroups();
if ( protectionGrpLst != null) {
data = new ArrayList<Object []>();
for(ProtectionGroup pg : protectionGrpLst) {
List<ProtectionElement> pes = new ArrayList<ProtectionElement>(upm.getProtectionElements(pg.getProtectionGroupId().toString()));
for (ProtectionElement pe : pes) {
Object [] objs = {pg.getProtectionGroupName(),
pg.getProtectionGroupDescription(),
pe.getProtectionElementName()};
data.add(objs);
}
}
}
else {
Object [] objs = {"Warning: No Protection Group has defined yet!", "NA", "NA"};
data.add(objs);
}
} catch (CSConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formatResponse(format, data, columns);
}
}
| NCIP/national-biomedical-image-archive | software/nbia-api/src/gov/nih/nci/nbia/restAPI/V3_getProtectionGrpList.java | Java | bsd-3-clause | 2,741 |
/*
* Copyright (c) 2013-2013, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.service.repositorymanager;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.repository.Repository;
public class RepositoryInfo implements Comparable<RepositoryInfo> {
final private long id;
final private int rank;
final ServiceReference<Repository> sr;
public RepositoryInfo(ServiceReference<Repository> sr) {
this.id = ((Long)sr.getProperty(Constants.SERVICE_ID)).longValue();
Object r = sr.getProperty(Constants.SERVICE_RANKING);
if (r != null && r instanceof Integer) {
this.rank = ((Integer)r).intValue();
} else {
this.rank = 0;
}
this.sr = sr;
}
public RepositoryInfo(RepositoryInfo old, int rank) {
this.id = old.id;
this.rank = rank;
this.sr = old.sr;
}
public long getId() {
return id;
}
public int getRank() {
return rank;
}
public Object getProperty(String prop) {
return sr.getProperty(prop);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
RepositoryInfo rio = (RepositoryInfo) o;
if (id != rio.id || rank != rio.rank)
return false;
return true;
}
@Override
public int compareTo(RepositoryInfo o) {
if (equals(o)) {
return 0;
}
if (rank != o.rank) {
return o.rank - rank;
} else {
return id < o.id ? -1 : 1;
}
}
public ServiceReference<Repository> getServiceReference() {
return sr;
}
@Override
public String toString() {
return "RepositoryInfo [id=" + id + ", rank=" + rank + "]";
}
}
| knopflerfish/knopflerfish.org | osgi/bundles/repository/repositorymanager/src/org/knopflerfish/service/repositorymanager/RepositoryInfo.java | Java | bsd-3-clause | 3,464 |
package org.chasen.mecab.wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
public class NodeIteratorTest {
@Test
public void threads() throws InterruptedException {
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("本日は晴天なり")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("本日は雨です")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("昨日は曇りでした")){
System.out.println(node.getSurface());
}
}
});
for(Thread th: threads){
th.start();
}
for(Thread th: threads){
th.join();
}
}
@Test
public void executors() throws InterruptedException, ExecutionException {
class Hoge {
public void parse(String str){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
final Hoge hoge = new Hoge();
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("本日は晴天なり");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("本日は雨です");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("昨日は曇りでした");
return null;
}
}));
for(Future<?> f: futures){
f.get();
}
}
@Test
public void executors_runnable() throws InterruptedException, ExecutionException {
class Hoge implements Runnable {
String str;
Hoge(String str){
this.str = str;
}
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Hoge("本日は晴天なり")));
futures.add(executors.submit(new Hoge("本日は雨です")));
futures.add(executors.submit(new Hoge("昨日は曇りでした")));
for(Future<?> f: futures){
f.get();
}
}
}
| nowelium/jna-libmecab | test/org/chasen/mecab/wrapper/NodeIteratorTest.java | Java | bsd-3-clause | 3,838 |
/*
* Copyright (c) 2006, 2007 ThoughtWorks, Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.thoughtworks.cozmos;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.StringTokenizer;
public class ModDavSvnProxyServlet2 extends HttpServlet {
private String targetURL;
private String newPageTemplate;
public void init(ServletConfig servletConfig) throws ServletException {
targetURL = servletConfig.getInitParameter("mod_dav_svn_url");
newPageTemplate = servletConfig.getInitParameter("new_page_template_file");
super.init(servletConfig);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletPath();
Socket socket = startGet(new URL(targetURL + path));
InputStream is = socket.getInputStream();
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
boolean ok = isOk(lnr);
if (!ok) {
socket = startGet(new URL(targetURL + newPageTemplate));
lnr = new LineNumberReader(new InputStreamReader(is));
ok = isOk(lnr);
}
if (ok) {
lnr.readLine(); // Date:
lnr.readLine(); // Server:
lnr.readLine(); // ETag:
lnr.readLine(); // Accept-Ranges:
int contentLength = getContentLen(lnr.readLine());
lnr.readLine(); // Content-Type:
lnr.readLine(); // end of header
resp.setContentType(getServletContext().getMimeType(path));
OutputStream os = resp.getOutputStream();
int done = 0;
while (done < contentLength) {
int i = lnr.read();
done++;
os.write(i);
}
socket.close();
}
}
private int getContentLen(String s) {
StringTokenizer st = new StringTokenizer(s);
st.nextToken();
return Integer.parseInt(st.nextToken());
}
private boolean isOk(LineNumberReader lnr) throws IOException {
return "HTTP/1.1 200 OK".equals(lnr.readLine());
}
private Socket startGet(URL url) throws IOException {
Socket socket = new Socket(url.getHost(), 80);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("GET " + url.getPath() + " HTTP/1.1");
pw.println("Host: " + url.getHost());
pw.println();
return socket;
}
}
| codehaus/cozmos | src/main/java/com/thoughtworks/cozmos/ModDavSvnProxyServlet2.java | Java | isc | 3,638 |
package schoolprojects;
import java.util.Random;
import java.util.Scanner;
/**
* Piedra, papel o tijera es un juego infantil.
* Un juego de manos en el cual existen tres elementos.
* La piedra que vence a la tijera rompiéndola; la tijera que vencen al papel cortándolo;
* y el papel que vence a la piedra envolviéndola. Esto representa un ciclo, el cual
* le da su esencia al juego. Este juego es muy utilizado para decidir quien de dos
* personas hará algo, tal y como a veces se hace usando una moneda, o para dirimir algún asunto.
*
* En esta version del juego habra un Jugador Humano y un jugador artificial ( es decir el ordenador )
*
* @author Velik Georgiev Chelebiev
* @version 0.0.1
*/
public class Juego {
/**
* @param args Argumentos de la linea de comandos
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
/**
* Movimientos disponibles en forma de cadena.
*/
String[] movimientos = {"Piedra", "Papel", "Tijera"};
/**
* Moviemiento elegido por el usuario en forma de numero entero.
*/
int entradaUsuario = 0;
/**
* Un numero aleatorio que representara el movimiento del ordenador.
*/
int movimientoAleatorio = 0;
/**
* Los resultados posibles de la partida. 0 EMPATE 1 El jugador gana 2
* El jugador pierde
*/
String[] resultados = {"Empate", "Ganas", "Pierdes"};
/**
* El resultado de la partida respecto el jugador.
*/
int resultadoJugador = -1;
/**
* Aqui es donde epieza el juego.
*
* Pedimos al usuario que elija uno de los movimientos disponibles
* y generamos un movimiento aleatorio, que sera el movimiento del ordenador.
* Despues comptrobamos si el jugador gana al ordenador , si pierde o si hay un empate.
* Mostramos el resultado en la pantalla y el bucle se repite hasta que
* el jugador no introduce -1 como movimiento.
*/
do {
// Mostramos informacion sobre los movimientos validos y
// los numeros que le corresponden.
for (int i = 0; i < movimientos.length; i++) {
System.out.print("(" + (i + 1) + ") " + movimientos[i] + "\n");
}
// Valor predeterminado ( o entrada no valida, por si el usuario no introduce ningun valor )
entradaUsuario = 0;
// Leemos la entrada ( el moviemiento ) del usuario
try {
System.out.print("Movimiento: ");
entradaUsuario = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException ex) {
// Si la entrada no tiene un formato valido, mostraremos un mensaje de error
// y le pediremos al usuario que introduzca un movimiento nuevamente.
entradaUsuario = 0;
}
// Si la opcion elegida por el usuario no es valida imprimimos un
// mensaje de error y le volvemos a pedir que introduzca una opcion
if (entradaUsuario < 1 || entradaUsuario > 3) {
System.out.println("\n*** El movimiento elegido no es valido. ***");
continue;
}
// Restamos 1 a la entrada del usuario.
// Esto lo hacemos para que sea un indice de vector valido.
entradaUsuario -= 1;
// Generamos un movimiento aleatorio
movimientoAleatorio = rand.nextInt(movimientos.length);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
// Imprimimos las jugadas del jugador y del ordenador
System.out.println("Tu: (" + movimientos[entradaUsuario] + ") [VS] PC: (" + movimientos[movimientoAleatorio] + ")");
// Comprobamos si el jugador gana
if ((entradaUsuario == 0 && movimientoAleatorio == 2) ||
(entradaUsuario == 1 && movimientoAleatorio == 0) ||
(entradaUsuario == 2 && movimientoAleatorio == 1)) {
resultadoJugador = 1;
} else if(entradaUsuario == movimientoAleatorio) { // Comprobamos si es un empate
resultadoJugador = 0;
} else { // en el resto de los casos el jugador pierde
resultadoJugador = 2;
}
// Imprimimos el resultado de la partida
System.out.println("Resultado: " + resultados[resultadoJugador]);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
} while (entradaUsuario != -1);
}
}
| velikGeorgiev/School | PRG/PiedraPapelTijera/Juego.java | Java | mit | 5,080 |
package PracticeLeetCode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _127WordLadder {
psvm
}
| darshanhs90/Java-InterviewPrep | src/PracticeLeetCode/_127WordLadder.java | Java | mit | 169 |
package de.hilling.maven.release.testprojects.versioninheritor;
public class App {
public static void main(String[] args) {
System.out.println("1 + 2 = 3");
}
}
| guhilling/smart-release-plugin | test-projects/ear-project/project-lib/src/main/java/de/hilling/maven/release/testprojects/versioninheritor/App.java | Java | mit | 178 |
package uk.org.fyodor.generators;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.junit.Test;
import uk.org.fyodor.BaseTest;
public class PercentageChanceGeneratorTest extends BaseTest {
Multiset<Boolean> results = HashMultiset.create();
@Test
public void percentageChances(){
for (int p = 1; p < 100; p++) {
Generator<Boolean> percentageChance = RDG.percentageChanceOf(p);
for (int i = 0; i < 10000; i++) {
results.add(percentageChance.next());
}
print(p);
print("True: " + results.count(Boolean.TRUE));
print("False: " + results.count(Boolean.FALSE));
results.clear();
}
}
}
| KarlWalsh/fyodor | fyodor-core/src/test/java/uk/org/fyodor/generators/PercentageChanceGeneratorTest.java | Java | mit | 766 |
/*
Copyright 2006 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.parity.func;
import ec.*;
import ec.app.parity.*;
import ec.gp.*;
import ec.util.*;
/*
* D31.java
*
* Created: Wed Nov 3 18:31:38 1999
* By: Sean Luke
*/
/**
* @author Sean Luke
* @version 1.0
*/
public class D31 extends GPNode
{
public String toString() { return "D31"; }
/*
public void checkConstraints(final EvolutionState state,
final int tree,
final GPIndividual typicalIndividual,
final Parameter individualBase)
{
super.checkConstraints(state,tree,typicalIndividual,individualBase);
if (children.length!=0)
state.output.error("Incorrect number of children for node " +
toStringForError() + " at " +
individualBase);
}
*/
public int expectedChildren() { return 0; }
public void eval(final EvolutionState state,
final int thread,
final GPData input,
final ADFStack stack,
final GPIndividual individual,
final Problem problem)
{
((ParityData)input).x =
((((Parity)problem).bits >>> 31 ) & 1);
}
}
| meiyi1986/GPJSS | src/ec/app/parity/func/D31.java | Java | mit | 1,195 |
package mahout;
/**
* Date: 12/11/14
* Time: 8:33 PM
* To change this template use File | Settings | File Templates.
*/
public class AppConstants {
public static final String TEST_FILE = "dataset.csv";
}
| syednasar/datascience | recommendations/mahoutrecommender/src/main/java/mahout/AppConstants.java | Java | mit | 213 |
package org.jinstagram.auth.model;
import org.jinstagram.http.Request;
import org.jinstagram.http.Verbs;
import java.util.HashMap;
import java.util.Map;
/**
* The representation of an OAuth HttpRequest.
*
* Adds OAuth-related functionality to the {@link Request}
*/
public class OAuthRequest extends Request {
private static final String OAUTH_PREFIX = "oauth_";
private Map<String, String> oauthParameters;
/**
* Default constructor.
*
* @param verb Http verb/method
* @param url resource URL
*/
public OAuthRequest(Verbs verb, String url) {
super(verb, url);
this.oauthParameters = new HashMap<String, String>();
}
/**
* Adds an OAuth parameter.
*
* @param key name of the parameter
* @param value value of the parameter
*
* @throws IllegalArgumentException if the parameter is not an OAuth
* parameter
*/
public void addOAuthParameter(String key, String value) {
oauthParameters.put(checkKey(key), value);
}
private static String checkKey(String key) {
if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) {
return key;
}
else {
throw new IllegalArgumentException(String.format(
"OAuth parameters must either be '%s' or start with '%s'",
OAuthConstants.SCOPE, OAUTH_PREFIX));
}
}
/**
* Returns the {@link Map} containing the key-value pair of parameters.
*
* @return parameters as map
*/
public Map<String, String> getOauthParameters() {
return oauthParameters;
}
@Override
public String toString() {
return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl());
}
}
| zauberlabs/jInstagram | src/main/java/org/jinstagram/auth/model/OAuthRequest.java | Java | mit | 1,596 |
package tracker.message.handlers;
import elasta.composer.message.handlers.MessageHandler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
/**
* Created by sohan on 2017-07-26.
*/
public interface ReplayMessageHandler extends MessageHandler<JsonObject> {
@Override
void handle(Message<JsonObject> event);
}
| codefacts/Elastic-Components | tracker/src/main/java/tracker/message/handlers/ReplayMessageHandler.java | Java | mit | 347 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation;
import java.util.List;
import org.joda.time.DateTime;
import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus;
import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;
/**
* Single item in List or Get Event Hub operation.
*/
@JsonFlatten
public class EventhubInner extends ProxyResource {
/**
* Current number of shards on the Event Hub.
*/
@JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY)
private List<String> partitionIds;
/**
* Exact time the Event Hub was created.
*/
@JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY)
private DateTime createdAt;
/**
* The exact time the message was updated.
*/
@JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY)
private DateTime updatedAt;
/**
* Number of days to retain the events for this Event Hub, value should be
* 1 to 7 days.
*/
@JsonProperty(value = "properties.messageRetentionInDays")
private Long messageRetentionInDays;
/**
* Number of partitions created for the Event Hub, allowed values are from
* 1 to 32 partitions.
*/
@JsonProperty(value = "properties.partitionCount")
private Long partitionCount;
/**
* Enumerates the possible values for the status of the Event Hub. Possible
* values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled',
* 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*/
@JsonProperty(value = "properties.status")
private EntityStatus status;
/**
* Properties of capture description.
*/
@JsonProperty(value = "properties.captureDescription")
private CaptureDescription captureDescription;
/**
* Get current number of shards on the Event Hub.
*
* @return the partitionIds value
*/
public List<String> partitionIds() {
return this.partitionIds;
}
/**
* Get exact time the Event Hub was created.
*
* @return the createdAt value
*/
public DateTime createdAt() {
return this.createdAt;
}
/**
* Get the exact time the message was updated.
*
* @return the updatedAt value
*/
public DateTime updatedAt() {
return this.updatedAt;
}
/**
* Get number of days to retain the events for this Event Hub, value should be 1 to 7 days.
*
* @return the messageRetentionInDays value
*/
public Long messageRetentionInDays() {
return this.messageRetentionInDays;
}
/**
* Set number of days to retain the events for this Event Hub, value should be 1 to 7 days.
*
* @param messageRetentionInDays the messageRetentionInDays value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withMessageRetentionInDays(Long messageRetentionInDays) {
this.messageRetentionInDays = messageRetentionInDays;
return this;
}
/**
* Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions.
*
* @return the partitionCount value
*/
public Long partitionCount() {
return this.partitionCount;
}
/**
* Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions.
*
* @param partitionCount the partitionCount value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withPartitionCount(Long partitionCount) {
this.partitionCount = partitionCount;
return this;
}
/**
* Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*
* @return the status value
*/
public EntityStatus status() {
return this.status;
}
/**
* Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*
* @param status the status value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get properties of capture description.
*
* @return the captureDescription value
*/
public CaptureDescription captureDescription() {
return this.captureDescription;
}
/**
* Set properties of capture description.
*
* @param captureDescription the captureDescription value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withCaptureDescription(CaptureDescription captureDescription) {
this.captureDescription = captureDescription;
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/eventhubs/mgmt-v2017_04_01/src/main/java/com/microsoft/azure/management/eventhubs/v2017_04_01/implementation/EventhubInner.java | Java | mit | 5,503 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.advisor.v2017_04_19;
import com.microsoft.azure.arm.collection.SupportsCreating;
import rx.Completable;
import rx.Observable;
import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing Suppressions.
*/
public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> {
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<SuppressionContract> listAsync();
/**
* Obtains the details of a suppression.
*
* @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies.
* @param recommendationId The recommendation ID.
* @param name The name of the suppression.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name);
/**
* Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression.
*
* @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies.
* @param recommendationId The recommendation ID.
* @param name The name of the suppression.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable deleteAsync(String resourceUri, String recommendationId, String name);
}
| selvasingh/azure-sdk-for-java | sdk/advisor/mgmt-v2017_04_19/src/main/java/com/microsoft/azure/management/advisor/v2017_04_19/Suppressions.java | Java | mit | 2,252 |
package com.xeiam.xchange.anx.v2.account.polling;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWalletHistoryWrapper;
//import static org.fest.assertions.api.Assertions.assertThat;
/**
* Test ANXWalletHistory JSON parsing
*/
public class WalletHistoryJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = WalletHistoryJSONTest.class.getResourceAsStream("/v2/account/example-wallethistory-response.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ANXWalletHistoryWrapper anxWalletHistoryWrapper = mapper.readValue(is, ANXWalletHistoryWrapper.class);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory() != null);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getRecords() == 104);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getCurrentPage() == 1);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxPage() == 3);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxResults() == 50);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries().length == 50);
Assert.assertEquals("BTC bought: [tid:264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51] 10.00000000 BTC at 280.65500 HKD", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0]
.getInfo());
Assert.assertEquals(104, anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getIndex());
Assert.assertEquals("1394594770000", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getDate());
Assert.assertEquals("fee", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getType());
Assert.assertEquals("BTC", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getCurrency());
// Assert.assertEquals(new BigDecimal(0),
// anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getValue());
Assert.assertEquals(new BigDecimal("103168.75400000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getBalance().getValue());
Assert.assertEquals("cc496636-4849-4acf-a390-e4091a5009c3", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getOid());
Assert.assertEquals("264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getTid());
Assert.assertEquals(new BigDecimal("10.00000000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getAmount().getValue());
Assert.assertEquals("market", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getProperties());
}
} | Achterhoeker/XChange | xchange-anx/src/test/java/com/xeiam/xchange/anx/v2/account/polling/WalletHistoryJSONTest.java | Java | mit | 3,272 |
public class LeetCode0363 {
public int maxSumSubmatrix(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE;
long[] sum = new long[m + 1];
for (int i = 0; i < n; ++i) {
long[] sumInRow = new long[m];
for (int j = i; j < n; ++j) {
for (int p = 0; p < m; ++p) {
sumInRow[p] += matrix[p][j];
sum[p + 1] = sum[p] + sumInRow[p];
}
ans = Math.max(ans, mergeSort(sum, 0, m + 1, k));
if (ans == k)
return k;
}
}
return ans;
}
int mergeSort(long[] sum, int start, int end, int k) {
if (end == start + 1)
return Integer.MIN_VALUE;
int mid = start + (end - start) / 2, cnt = 0;
int ans = mergeSort(sum, start, mid, k);
if (ans == k)
return k;
ans = Math.max(ans, mergeSort(sum, mid, end, k));
if (ans == k)
return k;
long[] cache = new long[end - start];
for (int i = start, j = mid, p = mid; i < mid; ++i) {
while (j < end && sum[j] - sum[i] <= k){
++j;
}
if (j - 1 >= mid) {
ans = Math.max(ans, (int) (sum[j - 1] - sum[i]));
if (ans == k){
return k;
}
}
while (p < end && sum[p] < sum[i]){
cache[cnt++] = sum[p++];
}
cache[cnt++] = sum[i];
}
System.arraycopy(cache, 0, sum, start, cnt);
return ans;
}
}
| dunso/algorithm | Java/Devide/LeetCode0363.java | Java | mit | 1,278 |
package com.ocdsoft.bacta.swg.shared.localization;
/**
* Created by crush on 11/21/2015.
*/
public class LocalizedString {
}
| bacta/pre-cu | src/main/java/com/ocdsoft/bacta/swg/shared/localization/LocalizedString.java | Java | mit | 128 |
package de.andreasgiemza.mangadownloader.gui.chapter;
import de.andreasgiemza.mangadownloader.MangaDownloader;
import de.andreasgiemza.mangadownloader.helpers.RegexHelper;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
/**
*
* @author Andreas Giemza <andreas@giemza.net>
*/
public class ChapterListSearchDocumentListener implements DocumentListener {
private final MangaDownloader mangaDownloader;
private final JTextField chapterListSearchTextField;
private final TableRowSorter<ChapterTableModel> chapterTableRowSorter;
@SuppressWarnings("unchecked")
public ChapterListSearchDocumentListener(MangaDownloader mangaDownloader,
JTextField chapterListSearchTextField, JTable chapterListTable) {
this.mangaDownloader = mangaDownloader;
this.chapterListSearchTextField = chapterListSearchTextField;
chapterTableRowSorter = (TableRowSorter<ChapterTableModel>) chapterListTable
.getRowSorter();
}
@Override
public void insertUpdate(DocumentEvent e) {
changed();
}
@Override
public void removeUpdate(DocumentEvent e) {
changed();
}
@Override
public void changedUpdate(DocumentEvent e) {
changed();
}
private void changed() {
mangaDownloader.chapterSearchChanged();
final String searchText = chapterListSearchTextField.getText();
if (searchText.length() == 0) {
chapterTableRowSorter.setRowFilter(null);
} else if (searchText.length() > 0) {
chapterTableRowSorter.setRowFilter(RowFilter
.regexFilter(RegexHelper.build(searchText)));
}
}
}
| hurik/MangaDownloader | src/main/java/de/andreasgiemza/mangadownloader/gui/chapter/ChapterListSearchDocumentListener.java | Java | mit | 1,897 |
package nxt.http;
import nxt.Account;
import nxt.Attachment;
import nxt.Constants;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_ASSET;
import static nxt.http.JSONResponses.INCORRECT_PRICE;
import static nxt.http.JSONResponses.INCORRECT_QUANTITY;
import static nxt.http.JSONResponses.MISSING_ASSET;
import static nxt.http.JSONResponses.MISSING_PRICE;
import static nxt.http.JSONResponses.MISSING_QUANTITY;
import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS;
import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT;
public final class PlaceAskOrder extends CreateTransaction {
static final PlaceAskOrder instance = new PlaceAskOrder();
private PlaceAskOrder() {
super("asset", "quantity", "price");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException {
String assetValue = req.getParameter("asset");
String quantityValue = req.getParameter("quantity");
String priceValue = req.getParameter("price");
if (assetValue == null) {
return MISSING_ASSET;
} else if (quantityValue == null) {
return MISSING_QUANTITY;
} else if (priceValue == null) {
return MISSING_PRICE;
}
long price;
try {
price = Long.parseLong(priceValue);
if (price <= 0 || price > Constants.MAX_BALANCE * 100L) {
return INCORRECT_PRICE;
}
} catch (NumberFormatException e) {
return INCORRECT_PRICE;
}
Long asset;
try {
asset = Convert.parseUnsignedLong(assetValue);
} catch (RuntimeException e) {
return INCORRECT_ASSET;
}
int quantity;
try {
quantity = Integer.parseInt(quantityValue);
if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) {
return INCORRECT_QUANTITY;
}
} catch (NumberFormatException e) {
return INCORRECT_QUANTITY;
}
Account account = getAccount(req);
if (account == null) {
return UNKNOWN_ACCOUNT;
}
Integer assetBalance = account.getUnconfirmedAssetBalance(asset);
if (assetBalance == null || quantity > assetBalance) {
return NOT_ENOUGH_ASSETS;
}
Attachment attachment = new Attachment.ColoredCoinsAskOrderPlacement(asset, quantity, price);
return createTransaction(req, account, attachment);
}
}
| aspnmy/NasCoin | src/java/nxt/http/PlaceAskOrder.java | Java | mit | 2,662 |
package net.sf.esfinge.metadata.validate.minValue; | pedrocavalero/metadata | src/test/java/net/sf/esfinge/metadata/validate/minValue/package-info.java | Java | mit | 50 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package cn.sharesdk.demo.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@TargetApi(17)
public class ScreenShotListenManager {
private static final String TAG = "ScreenShotListenManager";
private static final String[] MEDIA_PROJECTIONS = new String[]{"_data", "datetaken"};
private static final String[] MEDIA_PROJECTIONS_API_16 = new String[]{"_data", "datetaken", "width", "height"};
private static final String[] KEYWORDS = new String[]{"screenshot", "screen_shot", "screen-shot", "screen shot", "screencapture",
"screen_capture", "screen-capture", "screen capture", "screencap", "screen_cap", "screen-cap", "screen cap"};
private static Point sScreenRealSize;
private final List<String> sHasCallbackPaths = new ArrayList();
private Context context;
private OnScreenShotListener listener;
private long startListenTime;
private MediaContentObserver internalObserver;
private MediaContentObserver externalObserver;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private ScreenShotListenManager(Context context) {
if(context == null) {
throw new IllegalArgumentException("The context must not be null.");
} else {
this.context = context;
if(sScreenRealSize == null) {
sScreenRealSize = this.getRealScreenSize();
if(sScreenRealSize != null) {
Log.d("ScreenShotListenManager", "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
} else {
Log.w("ScreenShotListenManager", "Get screen real size failed.");
}
}
}
}
public static ScreenShotListenManager newInstance(Context context) {
assertInMainThread();
return new ScreenShotListenManager(context);
}
public void startListen() {
assertInMainThread();
this.sHasCallbackPaths.clear();
this.startListenTime = System.currentTimeMillis();
this.internalObserver = new MediaContentObserver(Media.INTERNAL_CONTENT_URI, this.uiHandler);
this.externalObserver = new MediaContentObserver(Media.EXTERNAL_CONTENT_URI, this.uiHandler);
this.context.getContentResolver().registerContentObserver(Media.INTERNAL_CONTENT_URI, false, this.internalObserver);
this.context.getContentResolver().registerContentObserver(Media.EXTERNAL_CONTENT_URI, false, this.externalObserver);
}
public void stopListen() {
assertInMainThread();
if(this.internalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.internalObserver);
} catch (Exception var3) {
var3.printStackTrace();
}
this.internalObserver = null;
}
if(this.externalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.externalObserver);
} catch (Exception var2) {
var2.printStackTrace();
}
this.externalObserver = null;
}
this.startListenTime = 0L;
this.sHasCallbackPaths.clear();
}
private void handleMediaContentChange(Uri contentUri) {
Cursor cursor = null;
try {
cursor = this.context.getContentResolver().query(contentUri, VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
(String)null, (String[])null, "date_added desc limit 1");
if(cursor == null) {
Log.e("ScreenShotListenManager", "Deviant logic.");
return;
}
if(cursor.moveToFirst()) {
int e = cursor.getColumnIndex("_data");
int dateTakenIndex = cursor.getColumnIndex("datetaken");
int widthIndex = -1;
int heightIndex = -1;
if(VERSION.SDK_INT >= 16) {
widthIndex = cursor.getColumnIndex("width");
heightIndex = cursor.getColumnIndex("height");
}
String data = cursor.getString(e);
long dateTaken = cursor.getLong(dateTakenIndex);
boolean width = false;
boolean height = false;
int width1;
int height1;
if(widthIndex >= 0 && heightIndex >= 0) {
width1 = cursor.getInt(widthIndex);
height1 = cursor.getInt(heightIndex);
} else {
Point size = this.getImageSize(data);
width1 = size.x;
height1 = size.y;
}
this.handleMediaRowData(data, dateTaken, width1, height1);
return;
}
Log.d("ScreenShotListenManager", "Cursor no data.");
} catch (Exception var16) {
var16.printStackTrace();
return;
} finally {
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private Point getImageSize(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return new Point(options.outWidth, options.outHeight);
}
private void handleMediaRowData(String data, long dateTaken, int width, int height) {
if(this.checkScreenShot(data, dateTaken, width, height)) {
Log.d("ScreenShotListenManager", "ScreenShot: path = " + data + "; size = " + width + " * " + height + "; date = " + dateTaken);
if(this.listener != null && !this.checkCallback(data)) {
this.listener.onShot(data);
}
} else {
Log.w("ScreenShotListenManager", "Media content changed, but not screenshot: path = " + data + "; size = " + width + " * "
+ height + "; date = " + dateTaken);
}
}
private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
long currentTime = System.currentTimeMillis() - dateTaken;
if(dateTaken >= this.startListenTime && currentTime <= 20000L) {
if(sScreenRealSize == null || width <= sScreenRealSize.x && height <= sScreenRealSize.y || height <= sScreenRealSize.x
&& width <= sScreenRealSize.y) {
if(TextUtils.isEmpty(data)) {
return false;
} else {
data = data.toLowerCase();
String[] var11 = KEYWORDS;
int var10 = KEYWORDS.length;
for(int var9 = 0; var9 < var10; var9++) {
String keyWork = var11[var9];
if(data.contains(keyWork)) {
return true;
}
}
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean checkCallback(String imagePath) {
if(this.sHasCallbackPaths.contains(imagePath)) {
return true;
} else {
if(this.sHasCallbackPaths.size() >= 20) {
for(int i = 0; i < 5; i++) {
this.sHasCallbackPaths.remove(0);
}
}
this.sHasCallbackPaths.add(imagePath);
return false;
}
}
private Point getRealScreenSize() {
Point screenSize = null;
try {
screenSize = new Point();
WindowManager e = (WindowManager)this.context.getSystemService("window");
Display defaultDisplay = e.getDefaultDisplay();
if(VERSION.SDK_INT >= 17) {
defaultDisplay.getRealSize(screenSize);
} else {
try {
Method e1 = Display.class.getMethod("getRawWidth", new Class[0]);
Method getRawH = Display.class.getMethod("getRawHeight", new Class[0]);
screenSize.set(((Integer)e1.invoke(defaultDisplay, new Object[0])).intValue(),
((Integer)getRawH.invoke(defaultDisplay, new Object[0])).intValue());
} catch (Exception var6) {
screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());
var6.printStackTrace();
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return screenSize;
}
public void setListener(ScreenShotListenManager.OnScreenShotListener listener) {
this.listener = listener;
}
private static void assertInMainThread() {
if(Looper.myLooper() != Looper.getMainLooper()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String methodMsg = null;
if(elements != null && elements.length >= 4) {
methodMsg = elements[3].toString();
}
throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
}
}
private class MediaContentObserver extends ContentObserver {
private Uri contentUri;
public MediaContentObserver(Uri contentUri, Handler handler) {
super(handler);
this.contentUri = contentUri;
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handleMediaContentChange(this.contentUri);
}
}
public interface OnScreenShotListener {
void onShot(String var1);
}
}
| ShareSDKPlatform/ShareSDK-for-Android | SampleFresh/app/src/main/java/cn/sharesdk/demo/utils/ScreenShotListenManager.java | Java | mit | 8,651 |
package velir.intellij.cq5.util;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class for helping work with Repository objects.
*/
public class RepositoryUtils {
/**
* Hide default constructor for true static class.
*/
private RepositoryUtils() {
}
public static List<String> getAllNodeTypeNames(Session session) throws RepositoryException {
//get our child nodeTypes from our root
NodeIterator nodeTypes = getAllNodeTypes(session);
//go through each node type and pull out the name
List<String> nodeTypeNames = new ArrayList<String>();
while (nodeTypes.hasNext()) {
Node node = nodeTypes.nextNode();
nodeTypeNames.add(node.getName());
}
//return our node type names
return nodeTypeNames;
}
/**
* Will get all the nodes that represent the different node types.
*
* @param session Repository session to use for pulling out this information.
* @return
* @throws RepositoryException
*/
public static NodeIterator getAllNodeTypes(Session session) throws RepositoryException {
//get our node types root
Node nodeTypesRoot = session.getNode("/jcr:system/jcr:nodeTypes");
//get our child nodeTypes from our root
return nodeTypesRoot.getNodes();
}
}
| tmowad/intellij-jcr-plugin | source/src/velir/intellij/cq5/util/RepositoryUtils.java | Java | mit | 1,342 |
package queue;
/**
* Queue server metadata manager.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.1.0
*/
public interface IQsMetadataManager {
}
| kangkot/queue-server | app/queue/IQsMetadataManager.java | Java | mit | 166 |
class Test {
public static int[] test() {
return null;
}
public static void main(String[] args) {
int [] arr = test();
System.out.println(arr);
} | parin2092/cook | Test.java | Java | mit | 154 |
package com.example.exampleeureka;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleEurekaApplicationTests {
@Test
public void contextLoads() {
}
}
| ko-sasaki/springboot-example | springboot-eureka-server/src/test/java/com/example/exampleeureka/ExampleEurekaApplicationTests.java | Java | mit | 349 |
package com.github.bachelorpraktikum.visualisierbar.model;
import com.github.bachelorpraktikum.visualisierbar.model.Element.State;
import com.github.bachelorpraktikum.visualisierbar.model.Element.Type;
public class ElementShapeableTest extends ShapeableImplementationTest {
@Override
protected Shapeable<?> getShapeable() {
Context context = new Context();
Node node = Node.in(context).create("node", new Coordinates(0, 0));
return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT);
}
}
| Bachelorpraktikum/VisualisierbaR | src/test/java/com/github/bachelorpraktikum/visualisierbar/model/ElementShapeableTest.java | Java | mit | 551 |
/**
* The MIT License
*
* Copyright (c) 2019, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.random;
import static org.jeasy.random.FieldPredicates.*;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.jeasy.random.api.ContextAwareRandomizer;
import org.jeasy.random.api.RandomizerContext;
import org.jeasy.random.beans.*;
import org.jeasy.random.beans.exclusion.A;
import org.jeasy.random.beans.exclusion.B;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.jeasy.random.beans.exclusion.C;
@ExtendWith(MockitoExtension.class)
class FieldExclusionTest {
private EasyRandom easyRandom;
@BeforeEach
void setUp() {
easyRandom = new EasyRandom();
}
@Test
void excludedFieldsShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name"));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
//then
assertThat(person).isNotNull();
assertThat(person.getName()).isNull();
}
@Test
void excludedFieldsUsingSkipRandomizerShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name").and(ofType(String.class)).and(inClass(Human.class)));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getName()).isNull();
}
@Test
void excludedFieldsUsingFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(named("name"));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
assertThat(person.getAddress().getStreet()).isNotNull();
// person.name and street.name should be null
assertThat(person.getName()).isNull();
assertThat(person.getAddress().getStreet().getName()).isNull();
}
@Test
void excludedDottedFieldsShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name").and(inClass(Street.class)));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
assertThat(person.getAddress().getStreet()).isNotNull();
assertThat(person.getAddress().getStreet().getName()).isNull();
}
@Test
void fieldsExcludedWithAnnotationShouldNotBePopulated() {
Person person = easyRandom.nextObject(Person.class);
assertThat(person).isNotNull();
assertThat(person.getExcluded()).isNull();
}
@Test
@SuppressWarnings("deprecation")
void fieldsExcludedWithAnnotationViaFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(isAnnotatedWith(Deprecated.class));
easyRandom = new EasyRandom(parameters);
// when
Website website = easyRandom.nextObject(Website.class);
// then
assertThat(website).isNotNull();
assertThat(website.getProvider()).isNull();
}
@Test
void fieldsExcludedFromTypeViaFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(inClass(Address.class));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
// all fields declared in class Address must be null
assertThat(person.getAddress().getCity()).isNull();
assertThat(person.getAddress().getStreet()).isNull();
assertThat(person.getAddress().getZipCode()).isNull();
assertThat(person.getAddress().getCountry()).isNull();
}
@Test
void testFirstLevelExclusion() {
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("b2").and(inClass(C.class)));
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B2 must be null
assertThat(c.getB2()).isNull();
}
@Test
void testSecondLevelExclusion() { // goal: exclude only b2.a2
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(ofType(A.class).and(inClass(B.class)), new ContextAwareRandomizer<A>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public A getRandomValue() {
if (context.getCurrentField().equals("b2.a2")) {
return null;
}
return new EasyRandom().nextObject(A.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// Only B2.A2 must be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNull();
}
@Test
void testThirdLevelExclusion() { // goal: exclude only b2.a2.s2
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(FieldPredicates.named("s2").and(inClass(A.class)), new ContextAwareRandomizer<String>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public String getRandomValue() {
if (context.getCurrentField().equals("b2.a2.s2")) {
return null;
}
return new EasyRandom().nextObject(String.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// Only B2.A2.S2 must be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNull();
}
@Test
void testFirstLevelCollectionExclusion() {
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(FieldPredicates.named("b3").and(inClass(C.class)));
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNotNull();
// B3 must be null
assertThat(c.getB3()).isNull();
}
@Test
void testSecondLevelCollectionExclusion() { // b3.a2 does not make sense, should be ignored
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(FieldPredicates.named("a2").and(inClass(B.class)), new ContextAwareRandomizer<A>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public A getRandomValue() {
if (context.getCurrentField().equals("b3.a2")) {
return null;
}
return new EasyRandom().nextObject(A.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B2 and its "children" must not be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNotNull();
// B3 must not be null
assertThat(c.getB3()).isNotNull();
}
@Test
void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBean.class)));
easyRandom = new EasyRandom(parameters);
// when
InlineInitializationBean bean = easyRandom.nextObject(InlineInitializationBean.class);
// then
assertThat(bean).isNotNull();
assertThat(bean.getMyList()).isEmpty();
}
@Test
void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs_EvenIfBeanHasNoPublicConstructor() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBeanPrivateConstructor.class)));
easyRandom = new EasyRandom(parameters);
// when
InlineInitializationBeanPrivateConstructor bean = easyRandom.nextObject(InlineInitializationBeanPrivateConstructor.class);
// then
assertThat(bean.getMyList()).isEmpty();
}
@Test
void fieldsExcludedWithOneModifierShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNull();
}
@Test
void fieldsExcludedWithTwoModifiersShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PROTECTED));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNull();
}
@Test
void fieldsExcludedWithTwoModifiersShouldBePopulatedIfOneModifierIsNotFit() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PUBLIC));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNotNull();
}
public static class InlineInitializationBean {
private List<String> myList = new ArrayList<>();
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
}
public static class InlineInitializationBeanPrivateConstructor {
private List<String> myList = new ArrayList<>();
public List<String> getMyList() {
return myList;
}
private InlineInitializationBeanPrivateConstructor() {}
}
}
| benas/jPopulator | easy-random-core/src/test/java/org/jeasy/random/FieldExclusionTest.java | Java | mit | 16,362 |
package logbook.server.proxy;
/**
* 動作に必要なデータのみ取得するためのフィルターです。
*
*/
public class Filter {
/** フィルターするContent-Type */
public static final String CONTENT_TYPE_FILTER = "text/plain";
/** キャプチャーするリクエストのバイトサイズ上限 */
public static final int MAX_POST_FIELD_SIZE = 1024 * 1024;
/** setAttribute用のキー(Response) */
public static final String RESPONSE_BODY = "res-body";
/** setAttribute用のキー(Request) */
public static final String REQUEST_BODY = "req-body";
private static String serverName;
/**
* 鎮守府サーバー名を設定する
* @param name 鎮守府サーバー名
*/
public static void setServerName(String name) {
serverName = name;
}
/**
* 鎮守府サーバー名を取得する
* @param name 鎮守府サーバー名
*/
public static String getServerName() {
return serverName;
}
/**
* 鎮守府サーバー名を検出した場合true
*
* @return 鎮守府サーバー名を検出した場合true
*/
public static boolean isServerDetected() {
return serverName != null;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名から必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合は常にtrue<br>
*
* @param name サーバー名
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name) {
if ((!isServerDetected() || (isServerDetected() && serverName.equals(name)))) {
return true;
}
return false;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名とContent-Typeから必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合はContent-Typeから必要かどうかを判別します<br>
*
* @param name サーバー名
* @param contentType Content-Type
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name, String contentType) {
if ((!isServerDetected() || serverName.equals(name))
&& CONTENT_TYPE_FILTER.equals(contentType)) {
return true;
}
return false;
}
}
| silfumus/logbook-EN | main/logbook/server/proxy/Filter.java | Java | mit | 2,555 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ForwardDocumentEvent.proto
package Diadoc.Api.Proto;
public final class ForwardDocumentEventProtos {
private ForwardDocumentEventProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface ForwardDocumentEventOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.ForwardDocumentEvent)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
boolean hasTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder();
/**
* <code>optional string ToBoxId = 2;</code>
*/
boolean hasToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
java.lang.String getToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
com.google.protobuf.ByteString
getToBoxIdBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class ForwardDocumentEvent extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
ForwardDocumentEventOrBuilder {
// Use ForwardDocumentEvent.newBuilder() to construct.
private ForwardDocumentEvent(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private ForwardDocumentEvent(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final ForwardDocumentEvent defaultInstance;
public static ForwardDocumentEvent getDefaultInstance() {
return defaultInstance;
}
public ForwardDocumentEvent getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ForwardDocumentEvent(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
subBuilder = timestamp_.toBuilder();
}
timestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(timestamp_);
timestamp_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
toBoxId_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
public static com.google.protobuf.Parser<ForwardDocumentEvent> PARSER =
new com.google.protobuf.AbstractParser<ForwardDocumentEvent>() {
public ForwardDocumentEvent parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ForwardDocumentEvent(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<ForwardDocumentEvent> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int TIMESTAMP_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
return timestamp_;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
return timestamp_;
}
public static final int TOBOXID_FIELD_NUMBER = 2;
private java.lang.Object toBoxId_;
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
toBoxId_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeMessage(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getToBoxIdBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getToBoxIdBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEventOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
// Construct using Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getTimestampFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
toBoxId_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent getDefaultInstanceForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance();
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent build() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent buildPartial() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = new Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
if (timestampBuilder_ == null) {
result.timestamp_ = timestamp_;
} else {
result.timestamp_ = timestampBuilder_.build();
}
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.toBoxId_ = toBoxId_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) {
return mergeFrom((Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent other) {
if (other == Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance()) return this;
if (other.hasTimestamp()) {
mergeTimestamp(other.getTimestamp());
}
if (other.hasToBoxId()) {
bitField0_ |= 0x00000002;
toBoxId_ = other.toBoxId_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> timestampBuilder_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
if (timestampBuilder_ == null) {
return timestamp_;
} else {
return timestampBuilder_.getMessage();
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
timestamp_ = value;
onChanged();
} else {
timestampBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) {
if (timestampBuilder_ == null) {
timestamp_ = builderForValue.build();
onChanged();
} else {
timestampBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder mergeTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001) &&
timestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) {
timestamp_ =
Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(timestamp_).mergeFrom(value).buildPartial();
} else {
timestamp_ = value;
}
onChanged();
} else {
timestampBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder clearTimestamp() {
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
onChanged();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getTimestampBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getTimestampFieldBuilder().getBuilder();
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
if (timestampBuilder_ != null) {
return timestampBuilder_.getMessageOrBuilder();
} else {
return timestamp_;
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>
getTimestampFieldBuilder() {
if (timestampBuilder_ == null) {
timestampBuilder_ = new com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>(
getTimestamp(),
getParentForChildren(),
isClean());
timestamp_ = null;
}
return timestampBuilder_;
}
private java.lang.Object toBoxId_ = "";
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder clearToBoxId() {
bitField0_ = (bitField0_ & ~0x00000002);
toBoxId_ = getDefaultInstance().getToBoxId();
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
static {
defaultInstance = new ForwardDocumentEvent(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032ForwardDocumentEvent.proto\022\020Diadoc.Api" +
".Proto\032\017Timestamp.proto\"W\n\024ForwardDocume" +
"ntEvent\022.\n\tTimestamp\030\001 \001(\0132\033.Diadoc.Api." +
"Proto.Timestamp\022\017\n\007ToBoxId\030\002 \001(\tB\034B\032Forw" +
"ardDocumentEventProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
Diadoc.Api.Proto.TimestampProtos.getDescriptor(),
}, assigner);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor,
new java.lang.String[] { "Timestamp", "ToBoxId", });
Diadoc.Api.Proto.TimestampProtos.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| halex2005/diadocsdk-java | src/main/java/Diadoc/Api/Proto/ForwardDocumentEventProtos.java | Java | mit | 27,479 |
package saberapplications.pawpads.databinding;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import saberapplications.pawpads.R;
/**
* Created by Stanislav Volnjanskij on 25.08.16.
*/
public class BindableDouble extends BaseObservable {
private Double value;
private String format="%f";
public Double get() {
return value;
}
public void set(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
notifyChange();
}
}
public void setSilent(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
}
}
public BindableDouble(double value) {
super();
this.value = value;
}
public BindableDouble() {
super();
}
@BindingConversion
public static String convertIntegerToString(BindableDouble value) {
if (value != null && value.get()!=null)
return String.format(value.getFormat(), value.get());
else {
return null;
}
}
@BindingAdapter({"binding2way"})
public static void bindEditText(EditText view,
final BindableDouble bindableDouble) {
if (view.getTag(R.id.BIND_ID) == null) {
view.setTag(R.id.BIND_ID, true);
view.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
bindableDouble.setSilent(Double.parseDouble(s.toString()));
} catch (Exception e) {
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//initial value
if (bindableDouble == null) return;
Double newValue = bindableDouble.get();
if (newValue == null) return;
String strValue= String.format(bindableDouble.getFormat(),newValue);
if (!view.getText().toString().equals(strValue) ) {
view.setText(strValue);
}
}
/**
* Number format to display in text field
* @return
*/
public String getFormat() {
return format;
}
/**
*Set number format to display in text field
* @param format
*/
public void setFormat(String format) {
this.format = format;
}
}
| castaway2000/Pawpads | app/src/main/java/saberapplications/pawpads/databinding/BindableDouble.java | Java | mit | 2,887 |
/*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.entity;
import com.google.j2objc.annotations.Property;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import im.actor.core.api.ApiAvatar;
import im.actor.core.api.ApiBotCommand;
import im.actor.core.api.ApiContactRecord;
import im.actor.core.api.ApiContactType;
import im.actor.core.api.ApiFullUser;
import im.actor.core.api.ApiInt32Value;
import im.actor.core.api.ApiMapValue;
import im.actor.core.api.ApiMapValueItem;
import im.actor.core.api.ApiUser;
import im.actor.runtime.bser.BserCreator;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;
import im.actor.runtime.storage.KeyValueItem;
// Disabling Bounds checks for speeding up calculations
/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/
public class User extends WrapperExtEntity<ApiFullUser, ApiUser> implements KeyValueItem {
private static final int RECORD_ID = 10;
private static final int RECORD_FULL_ID = 20;
public static BserCreator<User> CREATOR = User::new;
@Property("readonly, nonatomic")
private int uid;
@Property("readonly, nonatomic")
private long accessHash;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private String name;
@Nullable
@Property("readonly, nonatomic")
private String localName;
@Nullable
@Property("readonly, nonatomic")
private String username;
@Nullable
@Property("readonly, nonatomic")
private String about;
@Nullable
@Property("readonly, nonatomic")
private Avatar avatar;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private Sex sex;
@Property("readonly, nonatomic")
private boolean isBot;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private List<ContactRecord> records;
@Property("readonly, nonatomic")
private boolean isBlocked;
@Nullable
@Property("readonly, nonatomic")
private String timeZone;
@Property("readonly, nonatomic")
private boolean isVerified;
@Property("readonly, nonatomic")
private List<BotCommand> commands;
@NotNull
@Property("readonly, nonatomic")
private boolean haveExtension;
public User(@NotNull ApiUser wrappedUser, @Nullable ApiFullUser ext) {
super(RECORD_ID, RECORD_FULL_ID, wrappedUser, ext);
}
public User(@NotNull byte[] data) throws IOException {
super(RECORD_ID, RECORD_FULL_ID, data);
}
private User() {
super(RECORD_ID, RECORD_FULL_ID);
}
@NotNull
public Peer peer() {
return new Peer(PeerType.PRIVATE, uid);
}
public int getUid() {
return uid;
}
public long getAccessHash() {
return accessHash;
}
@NotNull
public String getServerName() {
return name;
}
@Nullable
public String getLocalName() {
return localName;
}
@NotNull
public String getName() {
if (localName == null) {
return name;
} else {
return localName;
}
}
@Nullable
public String getNick() {
return username;
}
@Nullable
public String getAbout() {
return about;
}
@Nullable
public Avatar getAvatar() {
return avatar;
}
@NotNull
public Sex getSex() {
return sex;
}
public boolean isHaveExtension() {
return haveExtension;
}
@NotNull
public List<ContactRecord> getRecords() {
return records;
}
public boolean isBot() {
return isBot;
}
public List<BotCommand> getCommands() {
return commands;
}
public boolean isBlocked() {
return isBlocked;
}
@Nullable
public String getTimeZone() {
return timeZone;
}
public boolean isVerified() {
return isVerified;
}
public User editName(@NotNull String name) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
name,
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editLocalName(@NotNull String localName) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
localName,
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editNick(@Nullable String nick) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
nick,
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editExt(@Nullable ApiMapValue ext) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
ext);
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editAvatar(@Nullable ApiAvatar avatar) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
avatar,
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User updateExt(@Nullable ApiFullUser ext) {
return new User(getWrapped(), ext);
}
public User editAbout(@Nullable String about) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
about,
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editPreferredLanguages(List<String> preferredLanguages) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
preferredLanguages,
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editTimeZone(String timeZone) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
timeZone,
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editContacts(List<ApiContactRecord> contacts) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
contacts,
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBotCommands(List<ApiBotCommand> commands) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
commands,
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editFullExt(ApiMapValue extv) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
extv,
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBlocked(boolean isBlocked) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
isBlocked
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
@Override
protected void applyWrapped(@NotNull ApiUser wrapped, @Nullable ApiFullUser ext) {
this.uid = wrapped.getId();
this.accessHash = wrapped.getAccessHash();
this.name = wrapped.getName();
this.localName = wrapped.getLocalName();
if (wrapped.getNick() != null && wrapped.getNick().length() > 0) {
this.username = wrapped.getNick();
} else {
this.username = null;
}
if (wrapped.getAvatar() != null) {
this.avatar = new Avatar(wrapped.getAvatar());
}
this.isBot = false;
if (wrapped.isBot() != null) {
this.isBot = wrapped.isBot();
}
this.sex = Sex.UNKNOWN;
if (wrapped.getSex() != null) {
switch (wrapped.getSex()) {
case FEMALE:
this.sex = Sex.FEMALE;
break;
case MALE:
this.sex = Sex.MALE;
break;
}
}
if (wrapped.getExt() != null) {
this.isVerified = true;
for (ApiMapValueItem i : wrapped.getExt().getItems()) {
if ("is_verified".equals(i.getKey())) {
if (i.getValue() instanceof ApiInt32Value) {
this.isVerified = ((ApiInt32Value) i.getValue()).getValue() > 0;
}
}
}
}
// Extension
if (ext != null) {
this.haveExtension = true;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
if (ext.isBlocked() != null) {
this.isBlocked = ext.isBlocked();
} else {
this.isBlocked = false;
}
this.timeZone = ext.getTimeZone();
for (ApiContactRecord record : ext.getContactInfo()) {
if (record.getType() == ApiContactType.PHONE) {
this.records.add(new ContactRecord(ContactRecordType.PHONE, record.getTypeSpec(), "" + record.getLongValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.EMAIL) {
this.records.add(new ContactRecord(ContactRecordType.EMAIL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.WEB) {
this.records.add(new ContactRecord(ContactRecordType.WEB, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.SOCIAL) {
this.records.add(new ContactRecord(ContactRecordType.SOCIAL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
}
}
//Bot commands
for (ApiBotCommand command : ext.getBotCommands()) {
commands.add(new BotCommand(command.getSlashCommand(), command.getDescription(), command.getLocKey()));
}
this.about = ext.getAbout();
} else {
this.isBlocked = false;
this.haveExtension = false;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
this.about = null;
this.timeZone = null;
}
}
@Override
public void parse(BserValues values) throws IOException {
// Is Wrapper Layout
if (values.getBool(8, false)) {
// Parse wrapper layout
super.parse(values);
} else {
// Convert old layout
throw new IOException("Unsupported obsolete format");
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
// Mark as wrapper layout
writer.writeBool(8, true);
// Serialize wrapper layout
super.serialize(writer);
}
@Override
public long getEngineId() {
return getUid();
}
@Override
@NotNull
protected ApiUser createInstance() {
return new ApiUser();
}
@Override
protected ApiFullUser createExtInstance() {
return new ApiFullUser();
}
} | ljshj/actor-platform | actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/User.java | Java | mit | 15,291 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.monitor;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Part of MultiTenantDiagnosticSettings. Specifies the settings for a
* particular log.
*/
public class LogSettings {
/**
* Name of a Diagnostic Log category for a resource type this setting is
* applied to. To obtain the list of Diagnostic Log categories for a
* resource, first perform a GET diagnostic settings operation.
*/
@JsonProperty(value = "category")
private String category;
/**
* a value indicating whether this log is enabled.
*/
@JsonProperty(value = "enabled", required = true)
private boolean enabled;
/**
* the retention policy for this log.
*/
@JsonProperty(value = "retentionPolicy")
private RetentionPolicy retentionPolicy;
/**
* Get the category value.
*
* @return the category value
*/
public String category() {
return this.category;
}
/**
* Set the category value.
*
* @param category the category value to set
* @return the LogSettings object itself.
*/
public LogSettings withCategory(String category) {
this.category = category;
return this;
}
/**
* Get the enabled value.
*
* @return the enabled value
*/
public boolean enabled() {
return this.enabled;
}
/**
* Set the enabled value.
*
* @param enabled the enabled value to set
* @return the LogSettings object itself.
*/
public LogSettings withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the retentionPolicy value.
*
* @return the retentionPolicy value
*/
public RetentionPolicy retentionPolicy() {
return this.retentionPolicy;
}
/**
* Set the retentionPolicy value.
*
* @param retentionPolicy the retentionPolicy value to set
* @return the LogSettings object itself.
*/
public LogSettings withRetentionPolicy(RetentionPolicy retentionPolicy) {
this.retentionPolicy = retentionPolicy;
return this;
}
}
| martinsawicki/azure-sdk-for-java | azure-mgmt-monitor/src/main/java/com/microsoft/azure/management/monitor/LogSettings.java | Java | mit | 2,421 |
package com.xeiam.xchange.lakebtc.marketdata;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCOrderBook;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTicker;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTickers;
public class LakeBTCMarketDataJsonTest {
@Test
public void testDeserializeTicker() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCTickers tickers = mapper.readValue(is, LakeBTCTickers.class);
LakeBTCTicker cnyTicker = tickers.getCny();
assertThat(cnyTicker.getAsk()).isEqualTo("3524.07");
assertThat(cnyTicker.getBid()).isEqualTo("3517.13");
assertThat(cnyTicker.getLast()).isEqualTo("3524.07");
assertThat(cnyTicker.getHigh()).isEqualTo("3584.97");
assertThat(cnyTicker.getLow()).isEqualTo("3480.07");
assertThat(cnyTicker.getVolume()).isEqualTo("5964.7677");
LakeBTCTicker usdTicker = tickers.getUsd();
assertThat(usdTicker.getAsk()).isEqualTo("564.63");
assertThat(usdTicker.getBid()).isEqualTo("564.63");
assertThat(usdTicker.getLast()).isEqualTo("564.4");
assertThat(usdTicker.getHigh()).isEqualTo("573.83");
assertThat(usdTicker.getLow()).isEqualTo("557.7");
assertThat(usdTicker.getVolume()).isEqualTo("3521.2782");
}
@Test
public void testDeserializeOrderBook() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-orderbook-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCOrderBook orderBook = mapper.readValue(is, LakeBTCOrderBook.class);
BigDecimal[][] asks = orderBook.getAsks();
assertThat(asks).hasSize(3);
assertThat(asks[0][0]).isEqualTo("564.87");
assertThat(asks[0][1]).isEqualTo("22.371");
BigDecimal[][] bids = orderBook.getBids();
assertThat(bids).hasSize(3);
assertThat(bids[2][0]).isEqualTo("558.08");
assertThat(bids[2][1]).isEqualTo("0.9878");
}
}
| coingecko/XChange | xchange-lakebtc/src/test/java/com/xeiam/xchange/lakebtc/marketdata/LakeBTCMarketDataJsonTest.java | Java | mit | 2,443 |
package org.magcruise.gaming.executor.api.message;
import org.magcruise.gaming.lang.Message;
import org.magcruise.gaming.lang.SConstructor;
public interface RequestToGameExecutor extends Message {
@Override
public SConstructor<? extends RequestToGameExecutor> toConstructor(ToExpressionStyle style);
@Override
public default SConstructor<? extends RequestToGameExecutor> toConstructor() {
return toConstructor(ToExpressionStyle.DEFAULT);
}
}
| MAGCruise/magcruise-core | src/main/java/org/magcruise/gaming/executor/api/message/RequestToGameExecutor.java | Java | mit | 454 |
/*
* Copyright 2010-2017 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.auth;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Simple implementation AWSCredentials that reads in AWS access keys from a
* properties file. The AWS access key is expected to be in the "accessKey"
* property and the AWS secret key id is expected to be in the "secretKey"
* property.
*/
public class PropertiesCredentials implements AWSCredentials {
private final String accessKey;
private final String secretAccessKey;
/**
* Reads the specified file as a Java properties file and extracts the
* AWS access key from the "accessKey" property and AWS secret access
* key from the "secretKey" property. If the specified file doesn't
* contain the AWS access keys an IOException will be thrown.
*
* @param file
* The file from which to read the AWS credentials
* properties.
*
* @throws FileNotFoundException
* If the specified file isn't found.
* @throws IOException
* If any problems are encountered reading the AWS access
* keys from the specified file.
* @throws IllegalArgumentException
* If the specified properties file does not contain the
* required keys.
*/
public PropertiesCredentials(File file) throws FileNotFoundException, IOException, IllegalArgumentException {
if (!file.exists()) {
throw new FileNotFoundException("File doesn't exist: "
+ file.getAbsolutePath());
}
FileInputStream stream = new FileInputStream(file);
try {
Properties accountProperties = new Properties();
accountProperties.load(stream);
if (accountProperties.getProperty("accessKey") == null ||
accountProperties.getProperty("secretKey") == null) {
throw new IllegalArgumentException(
"The specified file (" + file.getAbsolutePath()
+ ") doesn't contain the expected properties 'accessKey' "
+ "and 'secretKey'."
);
}
accessKey = accountProperties.getProperty("accessKey");
secretAccessKey = accountProperties.getProperty("secretKey");
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
}
/**
* Reads the specified input stream as a stream of Java properties file
* content and extracts the AWS access key ID and secret access key from the
* properties.
*
* @param inputStream
* The input stream containing the AWS credential properties.
*
* @throws IOException
* If any problems occur while reading from the input stream.
*/
public PropertiesCredentials(InputStream inputStream) throws IOException {
Properties accountProperties = new Properties();
try {
accountProperties.load(inputStream);
} finally {
try {inputStream.close();} catch (Exception e) {}
}
if (accountProperties.getProperty("accessKey") == null ||
accountProperties.getProperty("secretKey") == null) {
throw new IllegalArgumentException("The specified properties data " +
"doesn't contain the expected properties 'accessKey' and 'secretKey'.");
}
accessKey = accountProperties.getProperty("accessKey");
secretAccessKey = accountProperties.getProperty("secretKey");
}
/* (non-Javadoc)
* @see com.amazonaws.auth.AWSCredentials#getAWSAccessKeyId()
*/
public String getAWSAccessKeyId() {
return accessKey;
}
/* (non-Javadoc)
* @see com.amazonaws.auth.AWSCredentials#getAWSSecretKey()
*/
public String getAWSSecretKey() {
return secretAccessKey;
}
}
| loremipsumdolor/CastFast | src/com/amazonaws/auth/PropertiesCredentials.java | Java | mit | 4,679 |
/*
* Copyright 2010-2017 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.s3.transfer;
import java.io.File;
import com.amazonaws.services.s3.model.ObjectMetadata;
/**
* This is the callback interface which is used by TransferManager.uploadDirectory and
* TransferManager.uploadFileList. The callback is invoked for each file that is uploaded by
* <code>TransferManager</code> and given an opportunity to specify the metadata for each file.
*/
public interface ObjectMetadataProvider {
/*
* This method is called for every file that is uploaded by <code>TransferManager</code>
* and gives an opportunity to specify the metadata for the file.
*
* @param file
* The file being uploaded.
*
* @param metadata
* The default metadata for the file. You can modify this object to specify
* your own metadata.
*/
public void provideObjectMetadata(final File file, final ObjectMetadata metadata);
}
| loremipsumdolor/CastFast | src/com/amazonaws/services/s3/transfer/ObjectMetadataProvider.java | Java | mit | 1,511 |
package org.luban.common.plugin;
import org.luban.common.network.URL;
/**
* 服务插件接口
*
* @author hexiaofeng
* @version 1.0.0
* @since 12-12-12 下午8:47
*/
public interface ServicePlugin {
/**
* 返回类型
*
* @return
*/
String getType();
/**
* 设置URL
*
* @param url
*/
void setUrl(URL url);
}
| krisjin/common-base | luban-common/src/main/java/org/luban/common/plugin/ServicePlugin.java | Java | mit | 377 |
package nxt.http;
import nxt.Nxt;
import nxt.Transaction;
import nxt.util.Convert;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_TRANSACTION;
import static nxt.http.JSONResponses.MISSING_TRANSACTION;
import static nxt.http.JSONResponses.UNKNOWN_TRANSACTION;
public final class GetTransaction extends APIServlet.APIRequestHandler {
static final GetTransaction instance = new GetTransaction();
private GetTransaction() {
super("transaction", "hash");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) {
String transactionIdString = Convert.emptyToNull(req.getParameter("transaction"));
String transactionHash = Convert.emptyToNull(req.getParameter("hash"));
if (transactionIdString == null && transactionHash == null) {
return MISSING_TRANSACTION;
}
Long transactionId = null;
Transaction transaction;
try {
if (transactionIdString != null) {
transactionId = Convert.parseUnsignedLong(transactionIdString);
transaction = Nxt.getBlockchain().getTransaction(transactionId);
} else {
transaction = Nxt.getBlockchain().getTransaction(transactionHash);
if (transaction == null) {
return UNKNOWN_TRANSACTION;
}
}
} catch (RuntimeException e) {
return INCORRECT_TRANSACTION;
}
JSONObject response;
if (transaction == null) {
transaction = Nxt.getTransactionProcessor().getUnconfirmedTransaction(transactionId);
if (transaction == null) {
return UNKNOWN_TRANSACTION;
}
response = transaction.getJSONObject();
} else {
response = transaction.getJSONObject();
response.put("block", Convert.toUnsignedLong(transaction.getBlockId()));
response.put("confirmations", Nxt.getBlockchain().getLastBlock().getHeight() - transaction.getHeight());
response.put("blockTimestamp", transaction.getBlockTimestamp());
}
response.put("sender", Convert.toUnsignedLong(transaction.getSenderId()));
response.put("hash", transaction.getHash());
return response;
}
}
| aspnmy/NasCoin | src/java/nxt/http/GetTransaction.java | Java | mit | 2,418 |
package com.github.scribejava.apis.examples;
import com.github.scribejava.apis.EtsyApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class EtsyExample {
private static final String PROTECTED_RESOURCE_URL = "https://openapi.etsy.com/v2/users/__SELF__";
private EtsyExample() {
}
@SuppressWarnings("PMD.SystemPrintln")
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
// Replace with your api and secret key
final OAuth10aService service = new ServiceBuilder("your api key")
.apiSecret("your secret key")
.build(EtsyApi.instance());
final Scanner in = new Scanner(System.in);
System.out.println("=== Etsy's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
final OAuth1RequestToken requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize ScribeJava here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
final String oauthVerifier = in.nextLine();
System.out.println();
// Trade the Request Token and Verifier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("That's it man! Go and build something awesome with ScribeJava! :)");
}
}
| fernandezpablo85/scribe-java | scribejava-apis/src/test/java/com/github/scribejava/apis/examples/EtsyExample.java | Java | mit | 2,876 |
public class A extends B {
public A() {}
}
| gregwym/joos-compiler-java | testcases/a2/Je_4_ClassExtendsCyclicClass/A.java | Java | mit | 47 |
package easyupload.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
@Entity
public class FileUpload {
public FileUpload(String filename, byte[] file, String mimeType) {
this.file = file;
this.filename = filename;
this.mimeType = mimeType;
}
public FileUpload() {
// Default Constructor
}
@Id
private String filename;
@Lob
private byte[] file;
private String mimeType;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
}
| vberbenetz/EasyUpload | Backend/src/main/java/easyupload/entity/FileUpload.java | Java | mit | 936 |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Lukas Degener (among others)
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.prolog.connector.cterm;
import org.cs3.prolog.connector.internal.cterm.parser.ASTNode;
/**
* Represents a Prolog string.
*/
public class CString extends CTerm {
public CString(ASTNode node) {
super(node);
}
}
| TeamSPoon/logicmoo_base | prolog/logicmoo/pdt_server/prolog.connector/src/org/cs3/prolog/connector/cterm/CString.java | Java | mit | 870 |
/* Copyright (c) 2018 lib4j
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.lib4j.test;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.lib4j.xml.dom.DOMStyle;
import org.lib4j.xml.dom.DOMs;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
import org.xmlunit.diff.ComparisonListener;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.DOMDifferenceEngine;
import org.xmlunit.diff.DifferenceEngine;
public class AssertXml {
private XPath newXPath() {
final XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI));
return xPath;
}
public static AssertXml compare(final Element controlElement, final Element testElement) {
final Map<String,String> prefixToNamespaceURI = new HashMap<>();
prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
final NamedNodeMap attributes = controlElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Attr attribute = (Attr)attributes.item(i);
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix()))
prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue());
}
return new AssertXml(prefixToNamespaceURI, controlElement, testElement);
}
private final Map<String,String> prefixToNamespaceURI;
private final Element controlElement;
private final Element testElement;
private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) {
if (!controlElement.getPrefix().equals(testElement.getPrefix()))
throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix());
this.prefixToNamespaceURI = prefixToNamespaceURI;
this.controlElement = controlElement;
this.testElement = testElement;
}
public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (!(node instanceof Element))
throw new UnsupportedOperationException("Only support addition of attributes to elements");
final Element target = (Element)node;
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
target.setAttributeNS(namespaceURI, name, value);
}
}
public void remove(final Element element, final String ... xpaths) throws XPathExpressionException {
for (final String xpath : xpaths) {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
attribute.getOwnerElement().removeAttributeNode(attribute);
}
else {
node.getParentNode().removeChild(node);
}
}
}
}
public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
if (name == null) {
attribute.setValue(value);
}
else {
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
final Element owner = attribute.getOwnerElement();
owner.removeAttributeNode(attribute);
owner.setAttributeNS(namespaceURI, name, value);
}
}
else {
throw new UnsupportedOperationException("Only support replacement of attribute values");
}
}
}
public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException {
replace(element, xpath, null, value);
}
public void assertEqual() {
final String prefix = controlElement.getPrefix();
final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final Source controlSource = Input.fromString(controlXml).build();
final Source testSource = Input.fromString(testXml).build();
final DifferenceEngine diffEngine = new DOMDifferenceEngine();
diffEngine.addDifferenceListener(new ComparisonListener() {
@Override
public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) {
final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1");
if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()"))
return;
try {
Assert.assertEquals(controlXml, testXml);
}
catch (final ComparisonFailure e) {
final StackTraceElement[] stackTrace = e.getStackTrace();
int i;
for (i = 3; i < stackTrace.length; i++)
if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff"))
break;
final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i];
System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i);
e.setStackTrace(filtered);
throw e;
}
Assert.fail(comparison.toString());
}
});
diffEngine.compare(controlSource, testSource);
}
} | safris-src/org | lib4j/test/src/main/java/org/lib4j/test/AssertXml.java | Java | mit | 7,601 |
package com.github.mlk.queue.codex;
import com.github.mlk.queue.Queuify;
import com.github.mlk.queue.implementation.Module;
public class Utf8StringModule implements Module {
public static Utf8StringModule utfStrings() {
return new Utf8StringModule();
}
@Override
public void bind(Queuify.Builder builder) {
builder.encoder(new StringEncoder())
.decoder(new StringDecoder());
}
}
| mlk/miniature-queue | core/src/main/java/com/github/mlk/queue/codex/Utf8StringModule.java | Java | mit | 434 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Jean-Baptiste Quenot, id:cactusman
* 2015 Kanstantsin Shautsou
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.triggers;
import antlr.ANTLRException;
import com.google.common.base.Preconditions;
import hudson.Extension;
import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Run;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormValidation;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.model.RunAction2;
import jenkins.scm.SCMDecisionHandler;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import static java.util.logging.Level.WARNING;
/**
* {@link Trigger} that checks for SCM updates periodically.
*
* You can add UI elements under the SCM section by creating a
* config.jelly or config.groovy in the resources area for
* your class that inherits from SCMTrigger and has the
* @{@link hudson.model.Extension} annotation. The UI should
* be wrapped in an f:section element to denote it.
*
* @author Kohsuke Kawaguchi
*/
public class SCMTrigger extends Trigger<Item> {
private boolean ignorePostCommitHooks;
public SCMTrigger(String scmpoll_spec) throws ANTLRException {
this(scmpoll_spec, false);
}
@DataBoundConstructor
public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException {
super(scmpoll_spec);
this.ignorePostCommitHooks = ignorePostCommitHooks;
}
/**
* This trigger wants to ignore post-commit hooks.
* <p>
* SCM plugins must respect this and not run this trigger for post-commit notifications.
*
* @since 1.493
*/
public boolean isIgnorePostCommitHooks() {
return this.ignorePostCommitHooks;
}
@Override
public void run() {
if (job == null) {
return;
}
run(null);
}
/**
* Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus
* to trigger a build at a specific revisionn number.
*
* @param additionalActions
* @since 1.375
*/
public void run(Action[] additionalActions) {
if (job == null) {
return;
}
DescriptorImpl d = getDescriptor();
LOGGER.fine("Scheduling a polling for "+job);
if (d.synchronousPolling) {
LOGGER.fine("Running the trigger directly without threading, " +
"as it's already taken care of by Trigger.Cron");
new Runner(additionalActions).run();
} else {
// schedule the polling.
// even if we end up submitting this too many times, that's OK.
// the real exclusion control happens inside Runner.
LOGGER.fine("scheduling the trigger to (asynchronously) run");
d.queue.execute(new Runner(additionalActions));
d.clogCheck();
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Override
public Collection<? extends Action> getProjectActions() {
if (job == null) {
return Collections.emptyList();
}
return Collections.singleton(new SCMAction());
}
/**
* Returns the file that records the last/current polling activity.
*/
public File getLogFile() {
return new File(job.getRootDir(),"scm-polling.log");
}
@Extension @Symbol("scm")
public static class DescriptorImpl extends TriggerDescriptor {
private static ThreadFactory threadFactory() {
return new NamingThreadFactory(Executors.defaultThreadFactory(), "SCMTrigger");
}
/**
* Used to control the execution of the polling tasks.
* <p>
* This executor implementation has a semantics suitable for polling. Namely, no two threads will try to poll the same project
* at once, and multiple polling requests to the same job will be combined into one. Note that because executor isn't aware
* of a potential workspace lock between a build and a polling, we may end up using executor threads unwisely --- they
* may block.
*/
private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory()));
/**
* Whether the projects should be polled all in one go in the order of dependencies. The default behavior is
* that each project polls for changes independently.
*/
public boolean synchronousPolling = false;
/**
* Max number of threads for SCM polling.
* 0 for unbounded.
*/
private int maximumThreads;
public DescriptorImpl() {
load();
resizeThreadPool();
}
public boolean isApplicable(Item item) {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null;
}
public ExecutorService getExecutor() {
return queue.getExecutors();
}
/**
* Returns true if the SCM polling thread queue has too many jobs
* than it can handle.
*/
public boolean isClogged() {
return queue.isStarving(STARVATION_THRESHOLD);
}
/**
* Checks if the queue is clogged, and if so,
* activate {@link AdministrativeMonitorImpl}.
*/
public void clogCheck() {
AdministrativeMonitor.all().get(AdministrativeMonitorImpl.class).on = isClogged();
}
/**
* Gets the snapshot of {@link Runner}s that are performing polling.
*/
public List<Runner> getRunners() {
return Util.filter(queue.getInProgress(),Runner.class);
}
// originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway
public List<SCMTriggerItem> getItemsBeingPolled() {
List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>();
for (Runner i : getRunners())
r.add(i.getTarget());
return r;
}
public String getDisplayName() {
return Messages.SCMTrigger_DisplayName();
}
/**
* Gets the number of concurrent threads used for polling.
*
* @return
* 0 if unlimited.
*/
public int getPollingThreadCount() {
return maximumThreads;
}
/**
* Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly
* @param n number of concurrent threads, zero or less means unlimited, maximum is 100
*/
public void setPollingThreadCount(int n) {
// fool proof
if(n<0) n=0;
if(n>100) n=100;
maximumThreads = n;
resizeThreadPool();
}
@Restricted(NoExternalUse.class)
public boolean isPollingThreadCountOptionVisible() {
// unless you have a fair number of projects, this option is likely pointless.
// so let's hide this option for new users to avoid confusing them
// unless it was already changed
// TODO switch to check for SCMTriggerItem
return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10
|| getPollingThreadCount() != 0;
}
/**
* Update the {@link ExecutorService} instance.
*/
/*package*/ synchronized void resizeThreadPool() {
queue.setExecutors(
(maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory())));
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
String t = json.optString("pollingThreadCount",null);
if(t==null || t.length()==0)
setPollingThreadCount(0);
else
setPollingThreadCount(Integer.parseInt(t));
// Save configuration
save();
return true;
}
public FormValidation doCheckPollingThreadCount(@QueryParameter String value) {
if (value != null && "".equals(value.trim()))
return FormValidation.ok();
return FormValidation.validateNonNegativeInteger(value);
}
}
@Extension
public static final class AdministrativeMonitorImpl extends AdministrativeMonitor {
private boolean on;
public boolean isActivated() {
return on;
}
}
/**
* Associated with {@link Run} to show the polling log
* that triggered that build.
*
* @since 1.376
*/
public static class BuildAction implements RunAction2 {
private transient /*final*/ Run<?,?> run;
@Deprecated
public transient /*final*/ AbstractBuild build;
/**
* @since 1.568
*/
public BuildAction(Run<?,?> run) {
this.run = run;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
@Deprecated
public BuildAction(AbstractBuild build) {
this((Run) build);
}
/**
* @since 1.568
*/
public Run<?,?> getRun() {
return run;
}
/**
* Polling log that triggered the build.
*/
public File getPollingLogFile() {
return new File(run.getRootDir(),"polling.log");
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
return Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "pollingLog";
}
/**
* Sends out the raw polling log output.
*/
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
try {
getPollingLogText().writeLogTo(0, out);
} finally {
IOUtils.closeQuietly(out);
}
}
public AnnotatedLargeText getPollingLogText() {
return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this);
}
/**
* Used from <tt>polling.jelly</tt> to write annotated polling log to the given output.
*/
public void writePollingLogTo(long offset, XMLOutput out) throws IOException {
// TODO: resurrect compressed log file support
getPollingLogText().writeHtmlTo(offset, out.asWriter());
}
@Override public void onAttached(Run<?, ?> r) {
// unnecessary, existing constructor does this
}
@Override public void onLoad(Run<?, ?> r) {
run = r;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
}
/**
* Action object for job. Used to display the last polling log.
*/
public final class SCMAction implements Action {
public AbstractProject<?,?> getOwner() {
Item item = getItem();
return item instanceof AbstractProject ? ((AbstractProject) item) : null;
}
/**
* @since 1.568
*/
public Item getItem() {
return job().asItem();
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>();
for (SCM scm : job().getSCMs()) {
descriptors.add(scm.getDescriptor());
}
return descriptors.size() == 1 ? Messages.SCMTrigger_getDisplayName(descriptors.iterator().next().getDisplayName()) : Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "scmPollLog";
}
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Writes the annotated log to the given output.
* @since 1.350
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
}
}
private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName());
/**
* {@link Runnable} that actually performs polling.
*/
public class Runner implements Runnable {
/**
* When did the polling start?
*/
private volatile long startTime;
private Action[] additionalActions;
public Runner() {
this(null);
}
public Runner(Action[] actions) {
Preconditions.checkNotNull(job, "Runner can't be instantiated when job is null");
if (actions == null) {
additionalActions = new Action[0];
} else {
additionalActions = actions;
}
}
/**
* Where the log file is written.
*/
public File getLogFile() {
return SCMTrigger.this.getLogFile();
}
/**
* For which {@link Item} are we polling?
* @since 1.568
*/
public SCMTriggerItem getTarget() {
return job();
}
/**
* When was this polling started?
*/
public long getStartTime() {
return startTime;
}
/**
* Human readable string of when this polling is started.
*/
public String getDuration() {
return Util.getTimeSpanString(System.currentTimeMillis()-startTime);
}
private boolean runPolling() {
try {
// to make sure that the log file contains up-to-date text,
// don't do buffering.
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
boolean result = job().poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
if(result)
logger.println("Changes found");
else
logger.println("No changes");
return result;
} catch (Error | RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling for "+job));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
return false;
}
}
public void run() {
if (job == null) {
return;
}
// we can pre-emtively check the SCMDecisionHandler instances here
// note that job().poll(listener) should also check this
SCMDecisionHandler veto = SCMDecisionHandler.firstShouldPollVeto(job);
if (veto != null) {
try (StreamTaskListener listener = new StreamTaskListener(getLogFile())) {
listener.getLogger().println(
"Skipping polling on " + DateFormat.getDateTimeInstance().format(new Date())
+ " due to veto from " + veto);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to record SCM polling for " + job, e);
}
LOGGER.log(Level.FINE, "Skipping polling for {0} due to veto from {1}",
new Object[]{job.getFullDisplayName(), veto}
);
return;
}
String threadName = Thread.currentThread().getName();
Thread.currentThread().setName("SCM polling for "+job);
try {
startTime = System.currentTimeMillis();
if(runPolling()) {
SCMTriggerItem p = job();
String name = " #"+p.getNextBuildNumber();
SCMTriggerCause cause;
try {
cause = new SCMTriggerCause(getLogFile());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse the polling log",e);
cause = new SCMTriggerCause();
}
Action[] queueActions = new Action[additionalActions.length + 1];
queueActions[0] = new CauseAction(cause);
System.arraycopy(additionalActions, 0, queueActions, 1, additionalActions.length);
if (p.scheduleBuild2(p.getQuietPeriod(), queueActions) != null) {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Triggering "+name);
} else {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Job is already in the queue");
}
}
} finally {
Thread.currentThread().setName(threadName);
}
}
// as per the requirement of SequentialExecutionQueue, value equality is necessary
@Override
public boolean equals(Object that) {
return that instanceof Runner && job == ((Runner) that)._job();
}
private Item _job() {return job;}
@Override
public int hashCode() {
return job.hashCode();
}
}
@SuppressWarnings("deprecation")
private SCMTriggerItem job() {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
}
public static class SCMTriggerCause extends Cause {
/**
* Only used while ths cause is in the queue.
* Once attached to the build, we'll move this into a file to reduce the memory footprint.
*/
private String pollingLog;
private transient Run run;
public SCMTriggerCause(File logFile) throws IOException {
// TODO: charset of this log file?
this(FileUtils.readFileToString(logFile));
}
public SCMTriggerCause(String pollingLog) {
this.pollingLog = pollingLog;
}
/**
* @deprecated
* Use {@link SCMTrigger.SCMTriggerCause#SCMTriggerCause(String)}.
*/
@Deprecated
public SCMTriggerCause() {
this("");
}
@Override
public void onLoad(Run run) {
this.run = run;
}
@Override
public void onAddedTo(Run build) {
this.run = build;
try {
BuildAction a = new BuildAction(build);
FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog);
build.replaceAction(a);
} catch (IOException e) {
LOGGER.log(WARNING,"Failed to persist the polling log",e);
}
pollingLog = null;
}
@Override
public String getShortDescription() {
return Messages.SCMTrigger_SCMTriggerCause_ShortDescription();
}
@Restricted(DoNotUse.class)
public Run getRun() {
return this.run;
}
@Override
public boolean equals(Object o) {
return o instanceof SCMTriggerCause;
}
@Override
public int hashCode() {
return 3;
}
}
/**
* How long is too long for a polling activity to be in the queue?
*/
public static long STARVATION_THRESHOLD = SystemProperties.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1));
}
| SebastienGllmt/jenkins | core/src/main/java/hudson/triggers/SCMTrigger.java | Java | mit | 23,475 |
/*
* The MIT License
*
* Copyright 2019 Karus Labs.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.karuslabs.commons.command.synchronization;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SynchronizationTest {
Synchronizer synchronizer = mock(Synchronizer.class);
BukkitScheduler scheduler = mock(BukkitScheduler.class);
Synchronization synchronization = new Synchronization(synchronizer, scheduler, null);
PlayerCommandSendEvent event = mock(PlayerCommandSendEvent.class);
@Test
void add() {
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_duplicate() {
synchronization.events.add(event);
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertFalse(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_running() {
synchronization.running = true;
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void run() {
when(event.getPlayer()).thenReturn(mock(Player.class));
when(event.getCommands()).thenReturn(List.of("a"));
synchronization.add(event);
synchronization.run();
verify(synchronizer).synchronize(any(Player.class), any(List.class));
assertTrue(synchronization.events.isEmpty());
assertFalse(synchronization.running);
}
}
| Pante/Karus-Commons | commons/src/test/java/com/karuslabs/commons/command/synchronization/SynchronizationTest.java | Java | mit | 3,282 |
package net.ontrack.core.security;
import lombok.Data;
import net.ontrack.core.model.AccountSummary;
@Data
public class ProjectAuthorization {
private final int project;
private final AccountSummary account;
private final ProjectRole role;
}
| joansmith/ontrack | ontrack-core/src/main/java/net/ontrack/core/security/ProjectAuthorization.java | Java | mit | 258 |
package com.softserve.app.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.softserve.app.model.Pet;
@RunWith(MockitoJUnitRunner.class)
public class PetRepositoryStubTest {
@Mock PetRepository stubM;
@Mock Pet petM;
@Test
public void testFindAllPetsWithMockStub() {
List<Pet> pets = stubM.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindAllPetsWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
List<Pet> pets = (ArrayList<Pet>) stub.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindPetWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("101");
System.out.println(pet);
assertNotNull(pet);
}
@Test
public void testFindPetWithMockStub() {
when(stubM.findPet("10").getType()).thenReturn("dog");
assertEquals("dog", stubM.findPet("0").getType());
}
@Test(expected=RuntimeException.class)
public void testFindPetWithBadRequestWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("0");
}
@Test
public void testCreate() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet5 = new Pet();
pet5.setId("5");
pet5.setType("Dog");
System.out.println(pet5.getType());
stub.create(pet5);
System.out.println(stub.findPet("5").getType());
assertNotNull(stub.findPet("5").getType());
}
}
| OlegSvyryd/animalsRepo | SampleProjectPet/src/test/java/com/softserve/app/repository/PetRepositoryStubTest.java | Java | mit | 1,751 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for ResourceBurstType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ResourceBurstType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Actions" type="{}ArrayOfActionType" minOccurs="0"/>
* <element name="Status" type="{}ResourceBurstStatus" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResourceBurstType", propOrder = {
"actions",
"status"
})
public class ResourceBurstType {
@XmlElementRef(name = "Actions", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfActionType> actions;
@XmlElement(name = "Status")
@XmlSchemaType(name = "string")
protected ResourceBurstStatus status;
/**
* Gets the value of the actions property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public JAXBElement<ArrayOfActionType> getActions() {
return actions;
}
/**
* Sets the value of the actions property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public void setActions(JAXBElement<ArrayOfActionType> value) {
this.actions = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link ResourceBurstStatus }
*
*/
public ResourceBurstStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link ResourceBurstStatus }
*
*/
public void setStatus(ResourceBurstStatus value) {
this.status = value;
}
}
| AltisourceLabs/ecloudmanager | tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ResourceBurstType.java | Java | mit | 2,598 |
package org.ominidi.api.controller;
import org.ominidi.api.exception.ConnectionException;
import org.ominidi.api.exception.NotFoundException;
import org.ominidi.api.model.Errors;
import org.ominidi.domain.model.Feed;
import org.ominidi.domain.model.Post;
import org.ominidi.facebook.service.PageFeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class FeedController {
private PageFeedService pageFeedService;
@Autowired
public FeedController(PageFeedService pageFeedService) {
this.pageFeedService = pageFeedService;
}
@GetMapping(value = "/feed", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Feed<Post> getFeed(@RequestParam(value = "u", required = false) Optional<String> feedUrl) {
Optional<Feed<Post>> result = feedUrl.isPresent()
? pageFeedService.getFeed(feedUrl.get())
: pageFeedService.getFeed();
return result.orElseThrow(() -> new ConnectionException(Errors.CONNECTION_PROBLEM));
}
@GetMapping(value = "/post/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Post getPost(@PathVariable(value = "id") String id) {
return pageFeedService.getPostById(id).orElseThrow(() -> new NotFoundException(Errors.postNotFound(id)));
}
}
| ominidi/ominidi-web | src/main/java/org/ominidi/api/controller/FeedController.java | Java | mit | 1,506 |
/*
* FILE: RDDSampleUtilsTest
* Copyright (c) 2015 - 2018 GeoSpark Development Team
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.datasyslab.geospark.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class RDDSampleUtilsTest
{
/**
* Test get sample numbers.
*/
@Test
public void testGetSampleNumbers()
{
assertEquals(10, RDDSampleUtils.getSampleNumbers(2, 10, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(2, 100, -1));
assertEquals(10, RDDSampleUtils.getSampleNumbers(5, 1000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10001, -1));
assertEquals(1000, RDDSampleUtils.getSampleNumbers(5, 100011, -1));
assertEquals(99, RDDSampleUtils.getSampleNumbers(6, 100011, 99));
assertEquals(999, RDDSampleUtils.getSampleNumbers(20, 999, -1));
assertEquals(40, RDDSampleUtils.getSampleNumbers(20, 1000, -1));
}
/**
* Test too many partitions.
*/
@Test
public void testTooManyPartitions()
{
assertFailure(505, 999);
assertFailure(505, 1000);
assertFailure(10, 1000, 2100);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords)
{
assertFailure(numPartitions, totalNumberOfRecords, -1);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords, int givenSampleNumber)
{
try {
RDDSampleUtils.getSampleNumbers(numPartitions, totalNumberOfRecords, givenSampleNumber);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
} | Sarwat/GeoSpark | core/src/test/java/org/datasyslab/geospark/utils/RDDSampleUtilsTest.java | Java | mit | 2,880 |
package com.dubture.twig.core.model;
public interface IFunction extends ITwigCallable {
}
| gencer/Twig-Eclipse-Plugin | com.dubture.twig.core/src/com/dubture/twig/core/model/IFunction.java | Java | mit | 91 |
package maritech.nei;
import mariculture.core.lib.Modules;
import mariculture.factory.Factory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
public class MTNEIConfig implements IConfigureNEI {
@Override
public void loadConfig() {
if (Modules.isActive(Modules.factory)) {
API.hideItem(new ItemStack(Factory.customRFBlock, 1, OreDictionary.WILDCARD_VALUE));
}
}
@Override
public String getName() {
return "MariTech NEI";
}
@Override
public String getVersion() {
return "1.0";
}
}
| svgorbunov/Mariculture | src/main/java/maritech/nei/MTNEIConfig.java | Java | mit | 676 |
package tpe.exceptions.trycatchfinally;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import de.smits_net.games.framework.board.Board;
/**
* Spielfeld.
*/
public class GameBoard extends Board {
/** Sprite, das durch das Bild läuft. */
private Professor sprite;
/**
* Erzeugt ein neues Board.
*/
public GameBoard() {
// neues Spielfeld anlegen
super(10, new Dimension(400, 400), Color.BLACK);
// Sprite initialisieren
sprite = new Professor(this, new Point(300, 200));
}
/**
* Spielfeld neu zeichnen. Wird vom Framework aufgerufen.
*/
@Override
public void drawGame(Graphics g) {
sprite.draw(g, this);
}
/**
* Spielsituation updaten. Wird vom Framework aufgerufen.
*/
@Override
public boolean updateGame() {
sprite.move();
return sprite.isVisible();
}
}
| tpe-lecture/repo-27 | 06_ausnahmen/02_finally/src/tpe/exceptions/trycatchfinally/GameBoard.java | Java | mit | 955 |
/*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package test.org.jboss.forge.furnace.lifecycle;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jboss.forge.arquillian.services.LocalServices;
import org.jboss.forge.furnace.Furnace;
import org.jboss.forge.furnace.addons.Addon;
import org.jboss.forge.furnace.addons.AddonId;
import org.jboss.forge.furnace.addons.AddonRegistry;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.repositories.MutableAddonRepository;
import org.jboss.forge.furnace.util.Addons;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import test.org.jboss.forge.furnace.mocks.MockImpl1;
import test.org.jboss.forge.furnace.mocks.MockInterface;
@RunWith(Arquillian.class)
public class PreShutdownEventTest
{
@Deployment(order = 2)
public static AddonArchive getDeployment()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addAsAddonDependencies(
AddonDependencyEntry.create("dep1")
);
archive.addAsLocalServices(PreShutdownEventTest.class);
return archive;
}
@Deployment(name = "dep2,2", testable = false, order = 1)
public static AddonArchive getDeployment2()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addAsLocalServices(MockImpl1.class)
.addClasses(MockImpl1.class, MockInterface.class)
.addBeansXML();
return archive;
}
@Deployment(name = "dep1,1", testable = false, order = 0)
public static AddonArchive getDeployment1()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addClass(RecordingEventManager.class)
.addAsLocalServices(RecordingEventManager.class);
return archive;
}
@Test(timeout = 5000)
public void testPreShutdownIsCalled() throws Exception
{
Furnace furnace = LocalServices.getFurnace(getClass().getClassLoader());
AddonRegistry registry = furnace.getAddonRegistry();
Addon dep2 = registry.getAddon(AddonId.from("dep2", "2"));
RecordingEventManager manager = registry.getServices(RecordingEventManager.class).get();
Assert.assertEquals(3, manager.getPostStartupCount());
MutableAddonRepository repository = (MutableAddonRepository) furnace.getRepositories().get(0);
repository.disable(dep2.getId());
Addons.waitUntilStopped(dep2);
Assert.assertEquals(1, manager.getPreShutdownCount());
}
}
| pplatek/furnace | container-tests/src/test/java/test/org/jboss/forge/furnace/lifecycle/PreShutdownEventTest.java | Java | epl-1.0 | 2,843 |
/**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.io.rest.core.link;
import java.util.ArrayList;
import java.util.Collection;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.link.AbstractLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry;
import org.eclipse.smarthome.core.thing.link.ThingLinkManager;
import org.eclipse.smarthome.core.thing.link.dto.AbstractLinkDTO;
import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO;
import org.eclipse.smarthome.io.rest.JSONResponse;
import org.eclipse.smarthome.io.rest.RESTResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* This class acts as a REST resource for links.
*
* @author Dennis Nobel - Initial contribution
* @author Yordan Zhelev - Added Swagger annotations
* @author Kai Kreuzer - Removed Thing links and added auto link url
*/
@Path(ItemChannelLinkResource.PATH_LINKS)
@Api(value = ItemChannelLinkResource.PATH_LINKS)
public class ItemChannelLinkResource implements RESTResource {
/** The URI path to this resource */
public static final String PATH_LINKS = "links";
private ItemChannelLinkRegistry itemChannelLinkRegistry;
private ThingLinkManager thingLinkManager;
@Context
UriInfo uriInfo;
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available links.", response = ItemChannelLinkDTO.class, responseContainer = "Collection")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getAll() {
Collection<ItemChannelLink> channelLinks = itemChannelLinkRegistry.getAll();
return Response.ok(toBeans(channelLinks)).build();
}
@GET
@Path("/auto")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Tells whether automatic link mode is active or not", response = Boolean.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response isAutomatic() {
return Response.ok(thingLinkManager.isAutoLinksEnabled()).build();
}
@PUT
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Links item to a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Item already linked to the channel.") })
public Response link(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
itemChannelLinkRegistry.add(new ItemChannelLink(itemName, new ChannelUID(channelUid)));
return Response.ok().build();
}
@DELETE
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Unlinks item from a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Link not found."),
@ApiResponse(code = 405, message = "Link not editable.") })
public Response unlink(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
String linkId = AbstractLink.getIDFor(itemName, new ChannelUID(channelUid));
if (itemChannelLinkRegistry.get(linkId) == null) {
String message = "Link " + linkId + " does not exist!";
return JSONResponse.createResponse(Status.NOT_FOUND, null, message);
}
ItemChannelLink result = itemChannelLinkRegistry
.remove(AbstractLink.getIDFor(itemName, new ChannelUID(channelUid)));
if (result != null) {
return Response.ok().build();
} else {
return JSONResponse.createErrorResponse(Status.METHOD_NOT_ALLOWED, "Channel is read-only.");
}
}
protected void setThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = thingLinkManager;
}
protected void unsetThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = null;
}
protected void setItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
}
protected void unsetItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = null;
}
private Collection<AbstractLinkDTO> toBeans(Iterable<ItemChannelLink> links) {
Collection<AbstractLinkDTO> beans = new ArrayList<>();
for (AbstractLink link : links) {
ItemChannelLinkDTO bean = new ItemChannelLinkDTO(link.getItemName(), link.getUID().toString());
beans.add(bean);
}
return beans;
}
}
| marinmitev/smarthome | bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/link/ItemChannelLinkResource.java | Java | epl-1.0 | 5,631 |
/*******************************************************************************
* Copyright (c) 2017, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.social.fat.LibertyOP;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import com.ibm.websphere.simplicity.log.Log;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.RSCommonTestTools;
import com.ibm.ws.security.social.fat.LibertyOP.CommonTests.LibertyOPRepeatActions;
import com.ibm.ws.security.social.fat.commonTests.Social_BasicTests;
import com.ibm.ws.security.social.fat.utils.SocialConstants;
import com.ibm.ws.security.social.fat.utils.SocialTestSettings;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.rules.repeater.RepeatTests;
import componenttest.topology.impl.LibertyServerWrapper;
@RunWith(FATRunner.class)
@LibertyServerWrapper
@Mode(TestMode.FULL)
public class LibertyOP_BasicTests_oauth_usingSocialConfig extends Social_BasicTests {
public static Class<?> thisClass = LibertyOP_BasicTests_oauth_usingSocialConfig.class;
public static RSCommonTestTools rsTools = new RSCommonTestTools();
@ClassRule
public static RepeatTests r = RepeatTests.with(LibertyOPRepeatActions.usingUserInfo()).andWith(LibertyOPRepeatActions.usingIntrospect());
@BeforeClass
public static void setUp() throws Exception {
classOverrideValidationEndpointValue = FATSuite.UserApiEndpoint;
List<String> startMsgs = new ArrayList<String>();
startMsgs.add("CWWKT0016I.*" + SocialConstants.SOCIAL_DEFAULT_CONTEXT_ROOT);
List<String> extraApps = new ArrayList<String>();
extraApps.add(SocialConstants.HELLOWORLD_SERVLET);
// TODO fix
List<String> opStartMsgs = new ArrayList<String>();
// opStartMsgs.add("CWWKS1600I.*" + SocialConstants.OIDCCONFIGMEDIATOR_APP);
opStartMsgs.add("CWWKS1631I.*");
// TODO fix
List<String> opExtraApps = new ArrayList<String>();
opExtraApps.add(SocialConstants.OP_SAMPLE_APP);
String[] propagationTokenTypes = rsTools.chooseTokenSettings(SocialConstants.OIDC_OP);
String tokenType = propagationTokenTypes[0];
String certType = propagationTokenTypes[1];
Log.info(thisClass, "setupBeforeTest", "inited tokenType to: " + tokenType);
socialSettings = new SocialTestSettings();
testSettings = socialSettings;
testOPServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.op", "op_server_orig.xml", SocialConstants.OIDC_OP, null, SocialConstants.DO_NOT_USE_DERBY, opStartMsgs, null, SocialConstants.OIDC_OP, true, true, tokenType, certType);
genericTestServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.social", "server_LibertyOP_basicTests_oauth_usingSocialConfig.xml", SocialConstants.GENERIC_SERVER, extraApps, SocialConstants.DO_NOT_USE_DERBY, startMsgs);
setActionsForProvider(SocialConstants.LIBERTYOP_PROVIDER, SocialConstants.OAUTH_OP);
setGenericVSSpeicificProviderFlags(GenericConfig, "server_LibertyOP_basicTests_oauth_usingSocialConfig");
socialSettings = updateLibertyOPSettings(socialSettings);
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.security.social_fat.commonTest.LibertyOP/fat/src/com/ibm/ws/security/social/fat/LibertyOP/LibertyOP_BasicTests_oauth_usingSocialConfig.java | Java | epl-1.0 | 3,772 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:21 AM(foreman)-
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.06.11 at 05:49:00 PM EDT
//
package com.ibm.jbatch.jsl.model.v2;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Batchlet complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Batchlet">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="properties" type="{https://jakarta.ee/xml/ns/jakartaee}Properties" minOccurs="0"/>
* </sequence>
* <attribute name="ref" use="required" type="{https://jakarta.ee/xml/ns/jakartaee}artifactRef" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Batchlet", propOrder = {
"properties"
})
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public class Batchlet extends com.ibm.jbatch.jsl.model.Batchlet {
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected JSLProperties properties;
@XmlAttribute(name = "ref", required = true)
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected String ref;
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public JSLProperties getProperties() {
return properties;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setProperties(com.ibm.jbatch.jsl.model.JSLProperties value) {
this.properties = (JSLProperties) value;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public String getRef() {
return ref;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setRef(String value) {
this.ref = value;
}
/**
* Copyright 2013 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.
*/
/*
* Appended by build tooling.
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder(100);
buf.append("Batchlet: ref=" + ref);
buf.append("\n");
buf.append("Properties = " + com.ibm.jbatch.jsl.model.helper.PropertiesToStringHelper.getString(properties));
return buf.toString();
}
} | OpenLiberty/open-liberty | dev/com.ibm.jbatch.jsl.model/src/com/ibm/jbatch/jsl/model/v2/Batchlet.java | Java | epl-1.0 | 4,330 |
/*
* Copyright (c) 2012-2017 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
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static com.google.common.base.Strings.nullToEmpty;
import java.io.IOException;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.user.server.UserManager;
import org.eclipse.che.commons.auth.token.RequestTokenExtractor;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.subject.Subject;
import org.eclipse.che.commons.subject.SubjectImpl;
import org.eclipse.che.multiuser.api.permission.server.AuthorizedSubject;
import org.eclipse.che.multiuser.api.permission.server.PermissionChecker;
/** @author Max Shaposhnik (mshaposhnik@codenvy.com) */
@Singleton
public class MachineLoginFilter implements Filter {
@Inject private RequestTokenExtractor tokenExtractor;
@Inject private MachineTokenRegistry machineTokenRegistry;
@Inject private UserManager userManager;
@Inject private PermissionChecker permissionChecker;
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
if (httpRequest.getScheme().startsWith("ws")
|| !nullToEmpty(tokenExtractor.getToken(httpRequest)).startsWith("machine")) {
filterChain.doFilter(servletRequest, servletResponse);
return;
} else {
String tokenString;
User user;
try {
tokenString = tokenExtractor.getToken(httpRequest);
String userId = machineTokenRegistry.getUserId(tokenString);
user = userManager.getById(userId);
} catch (NotFoundException | ServerException e) {
throw new ServletException("Cannot find user by machine token.");
}
final Subject subject =
new AuthorizedSubject(
new SubjectImpl(user.getName(), user.getId(), tokenString, false), permissionChecker);
try {
EnvironmentContext.getCurrent().setSubject(subject);
filterChain.doFilter(addUserInRequest(httpRequest, subject), servletResponse);
} finally {
EnvironmentContext.reset();
}
}
}
private HttpServletRequest addUserInRequest(
final HttpServletRequest httpRequest, final Subject subject) {
return new HttpServletRequestWrapper(httpRequest) {
@Override
public String getRemoteUser() {
return subject.getUserName();
}
@Override
public Principal getUserPrincipal() {
return subject::getUserName;
}
};
}
@Override
public void destroy() {}
}
| TypeFox/che | multiuser/machine-auth/che-multiuser-machine-authentication/src/main/java/org/eclipse/che/multiuser/machine/authentication/server/MachineLoginFilter.java | Java | epl-1.0 | 3,592 |
/*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.cdi.services.impl;
import javax.enterprise.context.Dependent;
/**
* This class only needs to be here to make sure this is a BDA with a BeanManager
*/
@Dependent
public class MyPojoUser {
public String getUser() {
String s = "DefaultPojoUser";
return s;
}
}
| OpenLiberty/open-liberty | dev/com.ibm.ws.cdi.jee_fat/test-applications/resourceWebServicesProvider.war/src/com/ibm/ws/cdi/services/impl/MyPojoUser.java | Java | epl-1.0 | 840 |
/*
* 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 javax.faces;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
/**
* Provide utility methods used by FactoryFinder class to lookup for SPI interface FactoryFinderProvider.
*
* @since 2.0.5
*/
class _FactoryFinderProviderFactory
{
public static final String FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi" +
".FactoryFinderProviderFactory";
public static final String FACTORY_FINDER_PROVIDER_CLASS_NAME = "org.apache.myfaces.spi.FactoryFinderProvider";
public static final String INJECTION_PROVIDER_FACTORY_CLASS_NAME =
"org.apache.myfaces.spi.InjectionProviderFactory";
// INJECTION_PROVIDER_CLASS_NAME to provide use of new Injection Provider methods which take a
// a class as an input. This is required for CDI 1.2, particularly in regard to constructor injection/
public static final String INJECTION_PROVIDER_CLASS_NAME = "com.ibm.ws.jsf.spi.WASInjectionProvider";
// MANAGED_OBJECT_CLASS_NAME added for CDI 1.2 support. Because CDI now creates the class, inject needs
// to return two objects : the instance of the required class and the creational context. To do this
// an Managed object is returned from which both of the required objects can be obtained.
public static final String MANAGED_OBJECT_CLASS_NAME = "com.ibm.ws.managedobject.ManagedObject";
public static final Class<?> FACTORY_FINDER_PROVIDER_FACTORY_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD;
public static final Class<?> FACTORY_FINDER_PROVIDER_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD;
public static final Class<?> INJECTION_PROVIDER_FACTORY_CLASS;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD;
public static final Class<?> INJECTION_PROVIDER_CLASS;
public static final Method INJECTION_PROVIDER_INJECT_OBJECT_METHOD;
public static final Method INJECTION_PROVIDER_INJECT_CLASS_METHOD;
public static final Method INJECTION_PROVIDER_POST_CONSTRUCT_METHOD;
public static final Method INJECTION_PROVIDER_PRE_DESTROY_METHOD;
// New for CDI 1.2
public static final Class<?> MANAGED_OBJECT_CLASS;
public static final Method MANAGED_OBJECT_GET_OBJECT_METHOD;
public static final Method MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD;
static
{
Class factoryFinderFactoryClass = null;
Method factoryFinderproviderFactoryGetMethod = null;
Method factoryFinderproviderFactoryGetFactoryFinderMethod = null;
Class<?> factoryFinderProviderClass = null;
Method factoryFinderProviderGetFactoryMethod = null;
Method factoryFinderProviderSetFactoryMethod = null;
Method factoryFinderProviderReleaseFactoriesMethod = null;
Class injectionProviderFactoryClass = null;
Method injectionProviderFactoryGetInstanceMethod = null;
Method injectionProviderFactoryGetInjectionProviderMethod = null;
Class injectionProviderClass = null;
Method injectionProviderInjectObjectMethod = null;
Method injectionProviderInjectClassMethod = null;
Method injectionProviderPostConstructMethod = null;
Method injectionProviderPreDestroyMethod = null;
Class managedObjectClass = null;
Method managedObjectGetObjectMethod = null;
Method managedObjectGetContextDataMethod = null;
try
{
factoryFinderFactoryClass = classForName(FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME);
if (factoryFinderFactoryClass != null)
{
factoryFinderproviderFactoryGetMethod = factoryFinderFactoryClass.getMethod
("getInstance", null);
factoryFinderproviderFactoryGetFactoryFinderMethod = factoryFinderFactoryClass
.getMethod("getFactoryFinderProvider", null);
}
factoryFinderProviderClass = classForName(FACTORY_FINDER_PROVIDER_CLASS_NAME);
if (factoryFinderProviderClass != null)
{
factoryFinderProviderGetFactoryMethod = factoryFinderProviderClass.getMethod("getFactory",
new Class[]{String.class});
factoryFinderProviderSetFactoryMethod = factoryFinderProviderClass.getMethod("setFactory",
new Class[]{String.class, String.class});
factoryFinderProviderReleaseFactoriesMethod = factoryFinderProviderClass.getMethod
("releaseFactories", null);
}
injectionProviderFactoryClass = classForName(INJECTION_PROVIDER_FACTORY_CLASS_NAME);
if (injectionProviderFactoryClass != null)
{
injectionProviderFactoryGetInstanceMethod = injectionProviderFactoryClass.
getMethod("getInjectionProviderFactory", null);
injectionProviderFactoryGetInjectionProviderMethod = injectionProviderFactoryClass.
getMethod("getInjectionProvider", ExternalContext.class);
}
injectionProviderClass = classForName(INJECTION_PROVIDER_CLASS_NAME);
if (injectionProviderClass != null)
{
injectionProviderInjectObjectMethod = injectionProviderClass.
getMethod("inject", Object.class);
injectionProviderInjectClassMethod = injectionProviderClass.
getMethod("inject", Class.class);
injectionProviderPostConstructMethod = injectionProviderClass.
getMethod("postConstruct", Object.class, Object.class);
injectionProviderPreDestroyMethod = injectionProviderClass.
getMethod("preDestroy", Object.class, Object.class);
}
// get managed object and getObject and getContextData methods for CDI 1.2 support.
// getObject() is used to the created object instance
// getContextData(Class) is used to get the creational context
managedObjectClass = classForName(MANAGED_OBJECT_CLASS_NAME);
if (managedObjectClass != null)
{
managedObjectGetObjectMethod = managedObjectClass.getMethod("getObject", null);
managedObjectGetContextDataMethod = managedObjectClass.getMethod("getContextData", Class.class);
}
}
catch (Exception e)
{
// no op
}
FACTORY_FINDER_PROVIDER_FACTORY_CLASS = factoryFinderFactoryClass;
FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD = factoryFinderproviderFactoryGetMethod;
FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD = factoryFinderproviderFactoryGetFactoryFinderMethod;
FACTORY_FINDER_PROVIDER_CLASS = factoryFinderProviderClass;
FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD = factoryFinderProviderGetFactoryMethod;
FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD = factoryFinderProviderSetFactoryMethod;
FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD = factoryFinderProviderReleaseFactoriesMethod;
INJECTION_PROVIDER_FACTORY_CLASS = injectionProviderFactoryClass;
INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD = injectionProviderFactoryGetInstanceMethod;
INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD = injectionProviderFactoryGetInjectionProviderMethod;
INJECTION_PROVIDER_CLASS = injectionProviderClass;
INJECTION_PROVIDER_INJECT_OBJECT_METHOD = injectionProviderInjectObjectMethod;
INJECTION_PROVIDER_INJECT_CLASS_METHOD = injectionProviderInjectClassMethod;
INJECTION_PROVIDER_POST_CONSTRUCT_METHOD = injectionProviderPostConstructMethod;
INJECTION_PROVIDER_PRE_DESTROY_METHOD = injectionProviderPreDestroyMethod;
MANAGED_OBJECT_CLASS = managedObjectClass;
MANAGED_OBJECT_GET_OBJECT_METHOD = managedObjectGetObjectMethod;
MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD = managedObjectGetContextDataMethod;
}
public static Object getInstance()
{
if (FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD != null)
{
try
{
return FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD.invoke(FACTORY_FINDER_PROVIDER_FACTORY_CLASS, null);
}
catch (Exception e)
{
//No op
Logger log = Logger.getLogger(_FactoryFinderProviderFactory.class.getName());
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "Cannot retrieve current FactoryFinder instance from " +
"FactoryFinderProviderFactory." +
" Default strategy using thread context class loader will be used.", e);
}
}
}
return null;
}
// ~ Methods Copied from _ClassUtils
// ------------------------------------------------------------------------------------
/**
* Tries a Class.loadClass with the context class loader of the current thread first and automatically falls back
* to
* the ClassUtils class loader (i.e. the loader of the myfaces.jar lib) if necessary.
*
* @param type fully qualified name of a non-primitive non-array class
* @return the corresponding Class
* @throws NullPointerException if type is null
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String type) throws ClassNotFoundException
{
if (type == null)
{
throw new NullPointerException("type");
}
try
{
// Try WebApp ClassLoader first
return Class.forName(type, false, // do not initialize for faster startup
getContextClassLoader());
}
catch (ClassNotFoundException ignore)
{
// fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
return Class.forName(type, false, // do not initialize for faster startup
_FactoryFinderProviderFactory.class.getClassLoader());
}
}
/**
* Gets the ClassLoader associated with the current thread. Returns the class loader associated with the specified
* default object if no context loader is associated with the current thread.
*
* @return ClassLoader
*/
protected static ClassLoader getContextClassLoader()
{
if (System.getSecurityManager() != null)
{
try
{
Object cl = AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws PrivilegedActionException
{
return Thread.currentThread().getContextClassLoader();
}
});
return (ClassLoader) cl;
}
catch (PrivilegedActionException pae)
{
throw new FacesException(pae);
}
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
}
| OpenLiberty/open-liberty | dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/_FactoryFinderProviderFactory.java | Java | epl-1.0 | 12,732 |
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.http.internal.config;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.http.internal.converter.ColorItemConverter;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.NextPreviousType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PlayPauseType;
import org.openhab.core.library.types.RewindFastforwardType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
/**
* The {@link HttpChannelConfig} class contains fields mapping channel configuration parameters.
*
* @author Jan N. Klug - Initial contribution
*/
@NonNullByDefault
public class HttpChannelConfig {
private final Map<String, State> stringStateMap = new HashMap<>();
private final Map<Command, @Nullable String> commandStringMap = new HashMap<>();
private boolean initialized = false;
public @Nullable String stateExtension;
public @Nullable String commandExtension;
public @Nullable String stateTransformation;
public @Nullable String commandTransformation;
public HttpChannelMode mode = HttpChannelMode.READWRITE;
// switch, dimmer, color
public @Nullable String onValue;
public @Nullable String offValue;
// dimmer, color
public BigDecimal step = BigDecimal.ONE;
public @Nullable String increaseValue;
public @Nullable String decreaseValue;
// color
public ColorItemConverter.ColorMode colorMode = ColorItemConverter.ColorMode.RGB;
// contact
public @Nullable String openValue;
public @Nullable String closedValue;
// rollershutter
public @Nullable String upValue;
public @Nullable String downValue;
public @Nullable String stopValue;
public @Nullable String moveValue;
// player
public @Nullable String playValue;
public @Nullable String pauseValue;
public @Nullable String nextValue;
public @Nullable String previousValue;
public @Nullable String rewindValue;
public @Nullable String fastforwardValue;
/**
* maps a command to a user-defined string
*
* @param command the command to map
* @return a string or null if no mapping found
*/
public @Nullable String commandToFixedValue(Command command) {
if (!initialized) {
createMaps();
}
return commandStringMap.get(command);
}
/**
* maps a user-defined string to a state
*
* @param string the string to map
* @return the state or null if no mapping found
*/
public @Nullable State fixedValueToState(String string) {
if (!initialized) {
createMaps();
}
return stringStateMap.get(string);
}
private void createMaps() {
addToMaps(this.onValue, OnOffType.ON);
addToMaps(this.offValue, OnOffType.OFF);
addToMaps(this.openValue, OpenClosedType.OPEN);
addToMaps(this.closedValue, OpenClosedType.CLOSED);
addToMaps(this.upValue, UpDownType.UP);
addToMaps(this.downValue, UpDownType.DOWN);
commandStringMap.put(IncreaseDecreaseType.INCREASE, increaseValue);
commandStringMap.put(IncreaseDecreaseType.DECREASE, decreaseValue);
commandStringMap.put(StopMoveType.STOP, stopValue);
commandStringMap.put(StopMoveType.MOVE, moveValue);
commandStringMap.put(PlayPauseType.PLAY, playValue);
commandStringMap.put(PlayPauseType.PAUSE, pauseValue);
commandStringMap.put(NextPreviousType.NEXT, nextValue);
commandStringMap.put(NextPreviousType.PREVIOUS, previousValue);
commandStringMap.put(RewindFastforwardType.REWIND, rewindValue);
commandStringMap.put(RewindFastforwardType.FASTFORWARD, fastforwardValue);
initialized = true;
}
private void addToMaps(@Nullable String value, State state) {
if (value != null) {
commandStringMap.put((Command) state, value);
stringStateMap.put(value, state);
}
}
}
| openhab/openhab2 | bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/config/HttpChannelConfig.java | Java | epl-1.0 | 4,709 |
/*******************************************************************************
* Copyright (c) 2012 Max Hohenegger.
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Max Hohenegger - initial implementation
******************************************************************************/
package eu.hohenegger.c0ffee_tips.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import eu.hohenegger.c0ffee_tips.TestBasic;
@RunWith(Suite.class)
@SuiteClasses({TestBasic.class})
public class AllTests {
}
| Treehopper/c0ffee_tips | eu.hohenegger.c0ffee_tips.tests/src/eu/hohenegger/c0ffee_tips/tests/AllTests.java | Java | epl-1.0 | 791 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.hql.ast.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Collection;
import org.hibernate.AssertionFailure;
import org.hibernate.dialect.Dialect;
import org.hibernate.impl.FilterImpl;
import org.hibernate.type.Type;
import org.hibernate.param.DynamicFilterParameterSpecification;
import org.hibernate.param.CollectionFilterKeyParameterSpecification;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
import org.hibernate.hql.antlr.SqlTokenTypes;
import org.hibernate.hql.ast.HqlSqlWalker;
import org.hibernate.hql.ast.tree.FromClause;
import org.hibernate.hql.ast.tree.FromElement;
import org.hibernate.hql.ast.tree.QueryNode;
import org.hibernate.hql.ast.tree.DotNode;
import org.hibernate.hql.ast.tree.ParameterContainer;
import org.hibernate.hql.classic.ParserHelper;
import org.hibernate.sql.JoinFragment;
import org.hibernate.util.StringHelper;
import org.hibernate.util.ArrayHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs the post-processing of the join information gathered during semantic analysis.
* The join generating classes are complex, this encapsulates some of the JoinSequence-related
* code.
*
* @author Joshua Davis
*/
public class JoinProcessor implements SqlTokenTypes {
private static final Logger log = LoggerFactory.getLogger( JoinProcessor.class );
private final HqlSqlWalker walker;
private final SyntheticAndFactory syntheticAndFactory;
/**
* Constructs a new JoinProcessor.
*
* @param walker The walker to which we are bound, giving us access to needed resources.
*/
public JoinProcessor(HqlSqlWalker walker) {
this.walker = walker;
this.syntheticAndFactory = new SyntheticAndFactory( walker );
}
/**
* Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
*
* @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
* @return a JoinFragment.XXX join type.
* @see JoinFragment
* @see SqlTokenTypes
*/
public static int toHibernateJoinType(int astJoinType) {
switch ( astJoinType ) {
case LEFT_OUTER:
return JoinFragment.LEFT_OUTER_JOIN;
case INNER:
return JoinFragment.INNER_JOIN;
case RIGHT_OUTER:
return JoinFragment.RIGHT_OUTER_JOIN;
default:
throw new AssertionFailure( "undefined join type " + astJoinType );
}
}
public void processJoins(QueryNode query) {
final FromClause fromClause = query.getFromClause();
final List fromElements;
if ( DotNode.useThetaStyleImplicitJoins ) {
// for regression testing against output from the old parser...
// found it easiest to simply reorder the FromElements here into ascending order
// in terms of injecting them into the resulting sql ast in orders relative to those
// expected by the old parser; this is definitely another of those "only needed
// for regression purposes". The SyntheticAndFactory, then, simply injects them as it
// encounters them.
fromElements = new ArrayList();
ListIterator liter = fromClause.getFromElements().listIterator( fromClause.getFromElements().size() );
while ( liter.hasPrevious() ) {
fromElements.add( liter.previous() );
}
}
else {
fromElements = fromClause.getFromElements();
}
// Iterate through the alias,JoinSequence pairs and generate SQL token nodes.
Iterator iter = fromElements.iterator();
while ( iter.hasNext() ) {
final FromElement fromElement = ( FromElement ) iter.next();
JoinSequence join = fromElement.getJoinSequence();
join.setSelector(
new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
// The uber-rule here is that we need to include subclass joins if
// the FromElement is in any way dereferenced by a property from
// the subclass table; otherwise we end up with column references
// qualified by a non-existent table reference in the resulting SQL...
boolean containsTableAlias = fromClause.containsTableAlias( alias );
if ( fromElement.isDereferencedBySubclassProperty() ) {
// TODO : or should we return 'containsTableAlias'??
log.trace( "forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + "]" );
return true;
}
boolean shallowQuery = walker.isShallowQuery();
boolean includeSubclasses = fromElement.isIncludeSubclasses();
boolean subQuery = fromClause.isSubQuery();
return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery;
}
}
);
addJoinNodes( query, join, fromElement );
}
}
private void addJoinNodes(QueryNode query, JoinSequence join, FromElement fromElement) {
JoinFragment joinFragment = join.toJoinFragment(
walker.getEnabledFilters(),
fromElement.useFromFragment() || fromElement.isDereferencedBySuperclassOrSubclassProperty(),
fromElement.getWithClauseFragment(),
fromElement.getWithClauseJoinAlias()
);
String frag = joinFragment.toFromFragmentString();
String whereFrag = joinFragment.toWhereFragmentString();
// If the from element represents a JOIN_FRAGMENT and it is
// a theta-style join, convert its type from JOIN_FRAGMENT
// to FROM_FRAGMENT
if ( fromElement.getType() == JOIN_FRAGMENT &&
( join.isThetaStyle() || StringHelper.isNotEmpty( whereFrag ) ) ) {
fromElement.setType( FROM_FRAGMENT );
fromElement.getJoinSequence().setUseThetaStyle( true ); // this is used during SqlGenerator processing
}
// If there is a FROM fragment and the FROM element is an explicit, then add the from part.
if ( fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/ ) {
String fromFragment = processFromFragment( frag, join ).trim();
if ( log.isDebugEnabled() ) {
log.debug( "Using FROM fragment [" + fromFragment + "]" );
}
processDynamicFilterParameters(
fromFragment,
fromElement,
walker
);
}
syntheticAndFactory.addWhereFragment(
joinFragment,
whereFrag,
query,
fromElement,
walker
);
}
private String processFromFragment(String frag, JoinSequence join) {
String fromFragment = frag.trim();
// The FROM fragment will probably begin with ', '. Remove this if it is present.
if ( fromFragment.startsWith( ", " ) ) {
fromFragment = fromFragment.substring( 2 );
}
return fromFragment;
}
public static void processDynamicFilterParameters(
final String sqlFragment,
final ParameterContainer container,
final HqlSqlWalker walker) {
if ( walker.getEnabledFilters().isEmpty()
&& ( ! hasDynamicFilterParam( sqlFragment ) )
&& ( ! ( hasCollectionFilterParam( sqlFragment ) ) ) ) {
return;
}
Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
String symbols = new StringBuffer().append( ParserHelper.HQL_SEPARATORS )
.append( dialect.openQuote() )
.append( dialect.closeQuote() )
.toString();
StringTokenizer tokens = new StringTokenizer( sqlFragment, symbols, true );
StringBuffer result = new StringBuffer();
while ( tokens.hasMoreTokens() ) {
final String token = tokens.nextToken();
if ( token.startsWith( ParserHelper.HQL_VARIABLE_PREFIX ) ) {
final String filterParameterName = token.substring( 1 );
final String[] parts = LoadQueryInfluencers.parseFilterParameterName( filterParameterName );
final FilterImpl filter = ( FilterImpl ) walker.getEnabledFilters().get( parts[0] );
final Object value = filter.getParameter( parts[1] );
final Type type = filter.getFilterDefinition().getParameterType( parts[1] );
final String typeBindFragment = StringHelper.join(
",",
ArrayHelper.fillArray( "?", type.getColumnSpan( walker.getSessionFactoryHelper().getFactory() ) )
);
final String bindFragment = ( value != null && Collection.class.isInstance( value ) )
? StringHelper.join( ",", ArrayHelper.fillArray( typeBindFragment, ( ( Collection ) value ).size() ) )
: typeBindFragment;
result.append( bindFragment );
container.addEmbeddedParameter( new DynamicFilterParameterSpecification( parts[0], parts[1], type ) );
}
else {
result.append( token );
}
}
container.setText( result.toString() );
}
private static boolean hasDynamicFilterParam(String sqlFragment) {
return sqlFragment.indexOf( ParserHelper.HQL_VARIABLE_PREFIX ) < 0;
}
private static boolean hasCollectionFilterParam(String sqlFragment) {
return sqlFragment.indexOf( "?" ) < 0;
}
}
| ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java | Java | epl-1.0 | 9,793 |
/**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.tinkerforge.internal.model.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.openhab.binding.tinkerforge.internal.LoggerConstants;
import org.openhab.binding.tinkerforge.internal.TinkerforgeErrorHandler;
import org.openhab.binding.tinkerforge.internal.model.MBaseDevice;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelay;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelayBricklet;
import org.openhab.binding.tinkerforge.internal.model.MSubDevice;
import org.openhab.binding.tinkerforge.internal.model.MSubDeviceHolder;
import org.openhab.binding.tinkerforge.internal.model.ModelPackage;
import org.openhab.binding.tinkerforge.internal.types.OnOffValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>MIndustrial Quad Relay</b></em>'.
*
* @author Theo Weiss
* @since 1.4.0
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSwitchState
* <em>Switch State</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getLogger
* <em>Logger</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getUid <em>Uid</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#isPoll <em>Poll</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getEnabledA
* <em>Enabled A</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSubId
* <em>Sub Id</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getMbrick
* <em>Mbrick</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getDeviceType
* <em>Device Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MIndustrialQuadRelayImpl extends MinimalEObjectImpl.Container implements MIndustrialQuadRelay {
/**
* The default value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected static final OnOffValue SWITCH_STATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected OnOffValue switchState = SWITCH_STATE_EDEFAULT;
/**
* The default value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected static final Logger LOGGER_EDEFAULT = null;
/**
* The cached value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected Logger logger = LOGGER_EDEFAULT;
/**
* The default value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected static final String UID_EDEFAULT = null;
/**
* The cached value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected String uid = UID_EDEFAULT;
/**
* The default value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected static final boolean POLL_EDEFAULT = true;
/**
* The cached value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected boolean poll = POLL_EDEFAULT;
/**
* The default value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected static final AtomicBoolean ENABLED_A_EDEFAULT = null;
/**
* The cached value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected AtomicBoolean enabledA = ENABLED_A_EDEFAULT;
/**
* The default value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected static final String SUB_ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected String subId = SUB_ID_EDEFAULT;
/**
* The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected static final String DEVICE_TYPE_EDEFAULT = "quad_relay";
/**
* The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected String deviceType = DEVICE_TYPE_EDEFAULT;
private short relayNum;
private int mask;
private static final byte DEFAULT_SELECTION_MASK = 0000000000000001;
private static final byte OFF_BYTE = 0000000000000000;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected MIndustrialQuadRelayImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return ModelPackage.Literals.MINDUSTRIAL_QUAD_RELAY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public OnOffValue getSwitchState() {
return switchState;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSwitchState(OnOffValue newSwitchState) {
OnOffValue oldSwitchState = switchState;
switchState = newSwitchState;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE,
oldSwitchState, switchState));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void turnSwitch(OnOffValue state) {
logger.debug("turnSwitchState called on: {}", MIndustrialQuadRelayBrickletImpl.class);
try {
if (state == OnOffValue.OFF) {
logger.debug("setSwitchValue off");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, OFF_BYTE);
} else if (state == OnOffValue.ON) {
logger.debug("setSwitchState on");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, mask);
} else {
logger.error("{} unkown switchstate {}", LoggerConstants.TFMODELUPDATE, state);
}
setSwitchState(state);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void fetchSwitchState() {
OnOffValue value = OnOffValue.UNDEF;
try {
int deviceValue = getMbrick().getTinkerforgeDevice().getValue();
if ((deviceValue & mask) == mask) {
value = OnOffValue.ON;
} else {
value = OnOffValue.OFF;
}
setSwitchState(value);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Logger getLogger() {
return logger;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setLogger(Logger newLogger) {
Logger oldLogger = logger;
logger = newLogger;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER,
oldLogger, logger));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getUid() {
return uid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setUid(String newUid) {
String oldUid = uid;
uid = newUid;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID, oldUid,
uid));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isPoll() {
return poll;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setPoll(boolean newPoll) {
boolean oldPoll = poll;
poll = newPoll;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL, oldPoll,
poll));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public AtomicBoolean getEnabledA() {
return enabledA;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setEnabledA(AtomicBoolean newEnabledA) {
AtomicBoolean oldEnabledA = enabledA;
enabledA = newEnabledA;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A,
oldEnabledA, enabledA));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getSubId() {
return subId;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSubId(String newSubId) {
String oldSubId = subId;
subId = newSubId;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID, oldSubId,
subId));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public MIndustrialQuadRelayBricklet getMbrick() {
if (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK) {
return null;
}
return (MIndustrialQuadRelayBricklet) eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetMbrick(MIndustrialQuadRelayBricklet newMbrick, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject) newMbrick, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setMbrick(MIndustrialQuadRelayBricklet newMbrick) {
if (newMbrick != eInternalContainer()
|| (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK && newMbrick != null)) {
if (EcoreUtil.isAncestor(this, newMbrick)) {
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
}
NotificationChain msgs = null;
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
if (newMbrick != null) {
msgs = ((InternalEObject) newMbrick).eInverseAdd(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
msgs = basicSetMbrick(newMbrick, msgs);
if (msgs != null) {
msgs.dispatch();
}
} else if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK,
newMbrick, newMbrick));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getDeviceType() {
return deviceType;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void init() {
setEnabledA(new AtomicBoolean());
poll = true; // don't use the setter to prevent notification
logger = LoggerFactory.getLogger(MIndustrialQuadRelay.class);
relayNum = Short.parseShort(String.valueOf(subId.charAt(subId.length() - 1)));
mask = DEFAULT_SELECTION_MASK << relayNum;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void enable() {
logger.debug("enable called on MIndustrialQuadRelayImpl");
fetchSwitchState();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void disable() {
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
return basicSetMbrick((MIndustrialQuadRelayBricklet) otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return basicSetMbrick(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return eInternalContainer().eInverseRemove(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return getSwitchState();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return getLogger();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return getUid();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return isPoll();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return getEnabledA();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return getSubId();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return getDeviceType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState((OnOffValue) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger((Logger) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll((Boolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA((AtomicBoolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState(SWITCH_STATE_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger(LOGGER_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid(UID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll(POLL_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA(ENABLED_A_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId(SUB_ID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return SWITCH_STATE_EDEFAULT == null ? switchState != null : !SWITCH_STATE_EDEFAULT.equals(switchState);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return LOGGER_EDEFAULT == null ? logger != null : !LOGGER_EDEFAULT.equals(logger);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return UID_EDEFAULT == null ? uid != null : !UID_EDEFAULT.equals(uid);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return poll != POLL_EDEFAULT;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ENABLED_A_EDEFAULT == null ? enabledA != null : !ENABLED_A_EDEFAULT.equals(enabledA);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return SUB_ID_EDEFAULT == null ? subId != null : !SUB_ID_EDEFAULT.equals(subId);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick() != null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return ModelPackage.MBASE_DEVICE__LOGGER;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return ModelPackage.MBASE_DEVICE__UID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return ModelPackage.MBASE_DEVICE__POLL;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ModelPackage.MBASE_DEVICE__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return ModelPackage.MSUB_DEVICE__SUB_ID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return ModelPackage.MSUB_DEVICE__MBRICK;
default:
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MBASE_DEVICE__LOGGER:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER;
case ModelPackage.MBASE_DEVICE__UID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID;
case ModelPackage.MBASE_DEVICE__POLL:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL;
case ModelPackage.MBASE_DEVICE__ENABLED_A:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MSUB_DEVICE__SUB_ID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID;
case ModelPackage.MSUB_DEVICE__MBRICK:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK;
default:
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedOperationID(int baseOperationID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseOperationID) {
case ModelPackage.MBASE_DEVICE___INIT:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT;
case ModelPackage.MBASE_DEVICE___ENABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE;
case ModelPackage.MBASE_DEVICE___DISABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseOperationID) {
default:
return -1;
}
}
return super.eDerivedOperationID(baseOperationID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT:
init();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE:
enable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE:
disable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___TURN_SWITCH__ONOFFVALUE:
turnSwitch((OnOffValue) arguments.get(0));
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___FETCH_SWITCH_STATE:
fetchSwitchState();
return null;
}
return super.eInvoke(operationID, arguments);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (switchState: ");
result.append(switchState);
result.append(", logger: ");
result.append(logger);
result.append(", uid: ");
result.append(uid);
result.append(", poll: ");
result.append(poll);
result.append(", enabledA: ");
result.append(enabledA);
result.append(", subId: ");
result.append(subId);
result.append(", deviceType: ");
result.append(deviceType);
result.append(')');
return result.toString();
}
} // MIndustrialQuadRelayImpl
| sytone/openhab | bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/impl/MIndustrialQuadRelayImpl.java | Java | epl-1.0 | 28,553 |
package org.hibernate.envers.tools;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.Value;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class MappingTools {
/**
* @param componentName Name of the component, that is, name of the property in the entity that references the
* component.
* @return A prefix for properties in the given component.
*/
public static String createComponentPrefix(String componentName) {
return componentName + "_";
}
/**
* @param referencePropertyName The name of the property that holds the relation to the entity.
* @return A prefix which should be used to prefix an id mapper for the related entity.
*/
public static String createToOneRelationPrefix(String referencePropertyName) {
return referencePropertyName + "_";
}
public static String getReferencedEntityName(Value value) {
if (value instanceof ToOne) {
return ((ToOne) value).getReferencedEntityName();
} else if (value instanceof OneToMany) {
return ((OneToMany) value).getReferencedEntityName();
} else if (value instanceof Collection) {
return getReferencedEntityName(((Collection) value).getElement());
}
return null;
}
}
| ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/envers/src/main/java/org/hibernate/envers/tools/MappingTools.java | Java | epl-1.0 | 1,365 |
/*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.oauth20.web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.Subject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import com.ibm.ejs.ras.TraceNLS;
import com.ibm.oauth.core.api.OAuthResult;
import com.ibm.oauth.core.api.attributes.AttributeList;
import com.ibm.oauth.core.api.error.OidcServerException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20AccessDeniedException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20DuplicateParameterException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20Exception;
import com.ibm.oauth.core.api.oauth20.token.OAuth20Token;
import com.ibm.oauth.core.internal.oauth20.OAuth20Constants;
import com.ibm.oauth.core.internal.oauth20.OAuth20Util;
import com.ibm.oauth.core.internal.oauth20.OAuthResultImpl;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.security.WSSecurityException;
import com.ibm.websphere.security.auth.WSSubject;
import com.ibm.ws.ffdc.FFDCFilter;
import com.ibm.ws.ffdc.annotation.FFDCIgnore;
import com.ibm.ws.security.SecurityService;
import com.ibm.ws.security.common.claims.UserClaims;
import com.ibm.ws.security.oauth20.ProvidersService;
import com.ibm.ws.security.oauth20.api.Constants;
import com.ibm.ws.security.oauth20.api.OAuth20EnhancedTokenCache;
import com.ibm.ws.security.oauth20.api.OAuth20Provider;
import com.ibm.ws.security.oauth20.error.impl.OAuth20TokenRequestExceptionHandler;
import com.ibm.ws.security.oauth20.exception.OAuth20BadParameterException;
import com.ibm.ws.security.oauth20.plugins.OAuth20TokenImpl;
import com.ibm.ws.security.oauth20.plugins.OidcBaseClient;
import com.ibm.ws.security.oauth20.util.ConfigUtils;
import com.ibm.ws.security.oauth20.util.Nonce;
import com.ibm.ws.security.oauth20.util.OAuth20ProviderUtils;
import com.ibm.ws.security.oauth20.util.OIDCConstants;
import com.ibm.ws.security.oauth20.util.OidcOAuth20Util;
import com.ibm.ws.security.oauth20.web.OAuth20Request.EndpointType;
import com.ibm.ws.webcontainer.security.CookieHelper;
import com.ibm.ws.webcontainer.security.ReferrerURLCookieHandler;
import com.ibm.ws.webcontainer.security.WebAppSecurityCollaboratorImpl;
import com.ibm.wsspi.kernel.service.utils.AtomicServiceReference;
import com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceMap;
import com.ibm.wsspi.security.oauth20.JwtAccessTokenMediator;
import com.ibm.wsspi.security.oauth20.TokenIntrospectProvider;
@Component(service = OAuth20EndpointServices.class, name = "com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", immediate = true, configurationPolicy = ConfigurationPolicy.IGNORE, property = "service.vendor=IBM")
public class OAuth20EndpointServices {
private static TraceComponent tc = Tr.register(OAuth20EndpointServices.class);
private static TraceComponent tc2 = Tr.register(OAuth20EndpointServices.class, // use this one when bundle is the usual bundle.
TraceConstants.TRACE_GROUP,
TraceConstants.MESSAGE_BUNDLE);
protected static final String MESSAGE_BUNDLE = "com.ibm.ws.security.oauth20.internal.resources.OAuthMessages";
protected static final String MSG_RESOURCE_BUNDLE = "com.ibm.ws.security.oauth20.resources.ProviderMsgs";
public static final String KEY_SERVICE_PID = "service.pid";
public static final String KEY_SECURITY_SERVICE = "securityService";
protected final AtomicServiceReference<SecurityService> securityServiceRef = new AtomicServiceReference<SecurityService>(KEY_SECURITY_SERVICE);
public static final String KEY_TOKEN_INTROSPECT_PROVIDER = "tokenIntrospectProvider";
private final ConcurrentServiceReferenceMap<String, TokenIntrospectProvider> tokenIntrospectProviderRef = new ConcurrentServiceReferenceMap<String, TokenIntrospectProvider>(KEY_TOKEN_INTROSPECT_PROVIDER);
public static final String KEY_JWT_MEDIATOR = "jwtAccessTokenMediator";
private final ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator> jwtAccessTokenMediatorRef = new ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator>(KEY_JWT_MEDIATOR);
public static final String KEY_OAUTH_CLIENT_METATYPE_SERVICE = "oauth20ClientMetatypeService";
private static final AtomicServiceReference<OAuth20ClientMetatypeService> oauth20ClientMetatypeServiceRef = new AtomicServiceReference<OAuth20ClientMetatypeService>(KEY_OAUTH_CLIENT_METATYPE_SERVICE);
private static final String ATTR_NONCE = "consentNonce";
public static final String AUTHENTICATED = "authenticated";
protected volatile ClientAuthentication clientAuthentication = new ClientAuthentication();
protected volatile ClientAuthorization clientAuthorization = new ClientAuthorization();
protected volatile UserAuthentication userAuthentication = new UserAuthentication();
protected volatile CoverageMapEndpointServices coverageMapServices = new CoverageMapEndpointServices();
protected volatile RegistrationEndpointServices registrationEndpointServices = new RegistrationEndpointServices();
protected volatile Consent consent = new Consent();
protected volatile TokenExchange tokenExchange = new TokenExchange();
@Reference(service = SecurityService.class, name = KEY_SECURITY_SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
protected void setSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.setReference(reference);
}
protected void unsetSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.unsetReference(reference);
}
@Reference(service = TokenIntrospectProvider.class, name = KEY_TOKEN_INTROSPECT_PROVIDER, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY)
protected void setTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = JwtAccessTokenMediator.class, name = KEY_JWT_MEDIATOR, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY)
protected void setJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = OAuth20ClientMetatypeService.class, name = KEY_OAUTH_CLIENT_METATYPE_SERVICE, policy = ReferencePolicy.DYNAMIC)
protected void setOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.setReference(ref);
}
protected void unsetOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.unsetReference(ref);
}
@Activate
protected void activate(ComponentContext cc) {
securityServiceRef.activate(cc);
tokenIntrospectProviderRef.activate(cc);
jwtAccessTokenMediatorRef.activate(cc);
oauth20ClientMetatypeServiceRef.activate(cc);
ConfigUtils.setJwtAccessTokenMediatorService(jwtAccessTokenMediatorRef);
TokenIntrospect.setTokenIntrospect(tokenIntrospectProviderRef);
// The TraceComponent object was not initialized with the message bundle containing this message, so we cannot use
// Tr.info(tc, "OAUTH_ENDPOINT_SERVICE_ACTIVATED"). Eventually these messages will be merged into one file, making this infoMsg variable unnecessary
String infoMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_ENDPOINT_SERVICE_ACTIVATED",
null,
"CWWKS1410I: The OAuth endpoint service is activated.");
Tr.info(tc, infoMsg);
}
@Deactivate
protected void deactivate(ComponentContext cc) {
securityServiceRef.deactivate(cc);
tokenIntrospectProviderRef.deactivate(cc);
jwtAccessTokenMediatorRef.deactivate(cc);
oauth20ClientMetatypeServiceRef.deactivate(cc);
}
protected void handleOAuthRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext) throws ServletException, IOException {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if OAuth20 Provider should process the request.");
Tr.debug(tc, "Inbound request " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
OAuth20Request oauth20Request = getAuth20Request(request, response);
OAuth20Provider oauth20Provider = null;
if (oauth20Request != null) {
EndpointType endpointType = oauth20Request.getType();
oauth20Provider = getProvider(response, oauth20Request);
if (oauth20Provider != null) {
AttributeList optionalParams = new AttributeList();
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS IS STARTING.");
Tr.debug(tc, "OAUTH20 _SSO OP inbound URL " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
handleEndpointRequest(request, response, servletContext, oauth20Provider, endpointType, optionalParams);
}
}
if (tc.isDebugEnabled()) {
if (oauth20Provider != null) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS HAS ENDED.");
} else {
Tr.debug(tc, "OAUTH20 _SSO OP WILL NOT PROCESS THE REQUEST");
}
}
}
@FFDCIgnore({ OidcServerException.class })
protected void handleEndpointRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext,
OAuth20Provider oauth20Provider,
EndpointType endpointType,
AttributeList oidcOptionalParams) throws ServletException, IOException {
checkHttpsRequirement(request, response, oauth20Provider);
if (response.isCommitted()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Response has already been committed, so likely did not pass HTTPS requirement");
}
return;
}
boolean isBrowserWithBasicAuth = false;
UIAccessTokenBuilder uitb = null;
if (tc.isDebugEnabled()) {
Tr.debug(tc, "endpointType[" + endpointType + "]");
}
try {
switch (endpointType) {
case authorize:
OAuthResult result = processAuthorizationRequest(oauth20Provider, request, response, servletContext, oidcOptionalParams);
if (result != null) {
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
break;
} else if (result.getStatus() != OAuthResult.STATUS_OK) {
userAuthentication.renderErrorPage(oauth20Provider, request, response, result);
}
}
break;
case token:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
processTokenRequest(oauth20Provider, request, response);
}
break;
case introspect:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
introspect(oauth20Provider, request, response);
}
break;
case revoke:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
revoke(oauth20Provider, request, response);
}
break;
case coverage_map: // non-spec extension
coverageMapServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case registration:
secureEndpointServices(oauth20Provider, request, response, servletContext, RegistrationEndpointServices.ROLE_REQUIRED, true);
registrationEndpointServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case logout:
// no need to authenticate
logout(oauth20Provider, request, response);
break;
case app_password:
tokenExchange.processAppPassword(oauth20Provider, request, response);
break;
case app_token:
tokenExchange.processAppToken(oauth20Provider, request, response);
break;
// these next 3 are for UI pages
case clientManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, RegistrationEndpointServices.ROLE_REQUIRED)) {
break;
}
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd = servletContext.getRequestDispatcher("WEB-CONTENT/clientAdmin/index.jsp");
rd.forward(request, response);
break;
case personalTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, null)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd2 = servletContext.getRequestDispatcher("WEB-CONTENT/accountManager/index.jsp");
rd2.forward(request, response);
break;
case usersTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, OAuth20Constants.TOKEN_MANAGER_ROLE)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd3 = servletContext.getRequestDispatcher("WEB-CONTENT/tokenManager/index.jsp");
rd3.forward(request, response);
break;
case clientMetatype:
serveClientMetatypeRequest(request, response);
break;
default:
break;
}
} catch (OidcServerException e) {
if (!isBrowserWithBasicAuth) {
// we don't want routine browser auth challenges producing ffdc's.
// (but if a login is invalid in that case, we will still get a CWIML4537E from base sec.)
// however for non-browsers we want ffdc's like we had before, so generate manually
if (!e.getErrorDescription().contains("CWWKS1424E")) { // no ffdc for nonexistent clients
com.ibm.ws.ffdc.FFDCFilter.processException(e,
"com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", "324", this);
}
}
boolean suppressBasicAuthChallenge = isBrowserWithBasicAuth; // ui must NOT log in using basic auth, so logout function will work.
WebUtils.sendErrorJSON(response, e.getHttpStatus(), e.getErrorCode(), e.getErrorDescription(request.getLocales()), suppressBasicAuthChallenge);
}
}
// return true if clear to go, false otherwise. Log message and/or throw exception if unsuccessful
private boolean authenticateUI(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options, String requiredRole)
throws ServletException, IOException, OidcServerException {
OAuthResult result = handleUIUserAuthentication(request, response, servletContext, provider, options);
if (!isUIAuthenticationComplete(request, response, provider, result, requiredRole)) {
return false;
}
return true;
}
private boolean isUIAuthenticationComplete(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider, OAuthResult result, String requiredRole) throws OidcServerException {
if (result == null) { // sent to login page
return false;
}
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
return false;
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
try {
userAuthentication.renderErrorPage(provider, request, response, result);
} catch (Exception e) {
// ffdc
}
return false;
}
if (requiredRole != null && !request.isUserInRole(requiredRole)) {
throw new OidcServerException("403", OIDCConstants.ERROR_ACCESS_DENIED, HttpServletResponse.SC_FORBIDDEN);
}
return true;
}
void serveClientMetatypeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
OAuth20ClientMetatypeService metatypeService = oauth20ClientMetatypeServiceRef.getService();
if (metatypeService == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
metatypeService.sendClientMetatypeData(request, response);
}
private boolean checkUIConfig(OAuth20Provider provider, HttpServletRequest request) {
String uri = request.getRequestURI();
String id = provider.getInternalClientId();
String secret = provider.getInternalClientSecret();
OidcBaseClient client = null;
boolean result = false;
try {
client = provider.getClientProvider().get(id);
} catch (OidcServerException e) {
// ffdc
}
if (client != null) {
result = secret != null && client.isEnabled() && (client.isAppPasswordAllowed() || client.isAppTokenAllowed());
}
if (!result) {
Tr.warning(tc2, "OAUTH_UI_ENDPOINT_NOT_ENABLED", uri);
}
return result;
}
/**
* Perform logout. call base security logout to clear ltpa cookie.
* Then redirect to a configured logout page if available, else a default.
*
* This does NOT implement
* OpenID Connect Session Management 1.0 draft 28. as of Nov. 2017
* https://openid.net/specs/openid-connect-session-1_0.html#RedirectionAfterLogout
*
* Instead it is a simpler approach that just deletes the ltpa (sso) cookie
* and sends a simple error page if things go wrong.
*
* @param provider
* @param request
* @param response
*/
public void logout(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Processing logout");
}
try {
request.logout(); // ltpa cookie removed if present. No exception if not.
} catch (ServletException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
return;
}
// not part of spec: logout url defined in config, not client-specific
String logoutRedirectURL = provider.getLogoutRedirectURL();
try {
if (logoutRedirectURL != null) {
String encodedURL = URLEncodeParams(logoutRedirectURL);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP redirecting to [" + logoutRedirectURL + "], url encoded to [" + encodedURL + "]");
}
response.sendRedirect(encodedURL);
return;
} else {
// send default logout page
new LogoutPages().sendDefaultLogoutPage(request, response);
}
} catch (IOException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
}
}
String URLEncodeParams(String UrlStr) {
String sep = "?";
String encodedURL = UrlStr;
int index = UrlStr.indexOf(sep);
// if encoded url in server.xml, don't encode it again.
boolean alreadyEncoded = UrlStr.contains("%");
if (index > -1 && !alreadyEncoded) {
index++; // don't encode ?
String prefix = UrlStr.substring(0, index);
String suffix = UrlStr.substring(index);
try {
encodedURL = prefix + java.net.URLEncoder.encode(suffix, StandardCharsets.UTF_8.toString());
// shouldn't encode = in queries, so flip those back
encodedURL = encodedURL.replace("%3D", "=");
} catch (UnsupportedEncodingException e) {
// ffdc
}
}
return encodedURL;
}
public OAuthResult processAuthorizationRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, AttributeList options)
throws ServletException, IOException, OidcServerException {
OAuthResult oauthResult = checkForError(request);
if (oauthResult != null) {
return oauthResult;
}
boolean autoAuthz = clientAuthorization.isClientAutoAuthorized(provider, request);
String reqConsentNonce = getReqConsentNonce(request);
boolean afterLogin = isAfterLogin(request); // we've been to login.jsp or it's replacement.
if (reqConsentNonce == null) { // validate request for initial authorization request only
oauthResult = clientAuthorization.validateAuthorization(provider, request, response);
if (oauthResult.getStatus() != OAuthResult.STATUS_OK) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Status is OK, returning result");
}
return oauthResult;
}
}
oauthResult = handleUserAuthentication(oauthResult, request, response, servletContext,
provider, reqConsentNonce, options, autoAuthz, afterLogin);
return oauthResult;
}
/**
* Adds the id_token_hint_status, id_token_hint_username, and id_token_hint_clientid attributes from the options list
* into attrList, if those attributes exist.
*
* @param options
* @param attrList
*/
private void setTokenHintAttributes(AttributeList options, AttributeList attrList) {
String value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
}
/**
* @param attrs
* @param request
* @return OAuthResultImpl if validation failed, null otherwise.
*/
private OAuthResultImpl validateIdTokenHintIfPresent(AttributeList attrs, HttpServletRequest request) {
if (attrs != null) {
Principal user = request.getUserPrincipal();
String username = null;
if (user != null) {
username = user.getName();
}
try {
userAuthentication.validateIdTokenHint(username, attrs);
} catch (OAuth20Exception oe) {
return new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, oe);
}
}
return null;
}
/**
* Creates a 401 STATUS_FAILED result due to the token limit being reached.
*
* @param attrs
* @param request
* @param clientId
* @return
*/
private OAuthResult createTokenLimitResult(AttributeList attrs, HttpServletRequest request, String clientId) {
if (attrs == null) {
attrs = new AttributeList();
String responseType = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { responseType });
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { clientId });
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Attribute responseType:" + responseType + " client_id:" + clientId);
}
}
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.token.limit.external.error");
e.setHttpStatusCode(HttpServletResponse.SC_BAD_REQUEST);
OAuthResult oauthResultWithExcep = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
return oauthResultWithExcep;
}
private OAuthResult handleUIUserAuthentication(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options) throws IOException, ServletException, OidcServerException {
OAuthResult oauthResult = null;
Prompt prompt = new Prompt();
if (request.getUserPrincipal() == null) {
// authenticate user if not done yet. Send to login page.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED)) { // must be authorized, we'll check userInRole later.
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
return new OAuthResultImpl(OAuthResult.STATUS_OK, new AttributeList());
}
@FFDCIgnore({ OAuth20BadParameterException.class })
private OAuthResult handleUserAuthentication(OAuthResult oauthResult, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider,
String reqConsentNonce, AttributeList options, boolean autoauthz, boolean afterLogin) throws IOException, ServletException, OidcServerException {
Prompt prompt = null;
String[] scopesAttr = null;
AttributeList attrs = null;
if (oauthResult != null) {
attrs = oauthResult.getAttributeList();
scopesAttr = attrs.getAttributeValuesByName(OAuth20Constants.SCOPE);
if (options != null) {
setTokenHintAttributes(options, attrs);
}
String[] validResources = attrs.getAttributeValuesByName(OAuth20Constants.RESOURCE);
if (validResources != null) {
options.setAttribute(OAuth20Constants.RESOURCE, OAuth20Constants.ATTRTYPE_PARAM_OAUTH, validResources);
}
}
// Per section 4.1.2.1 of the OAuth 2.0 spec (RFC6749), the state parameter must be included in any error response if it was
// originally provided in the request. Adding it to the attribute list here will ensure it is propagated to any failure response.
String[] stateParams = request.getParameterValues(OAuth20Constants.STATE);
if (stateParams != null) {
if (attrs == null) {
attrs = new AttributeList();
}
attrs.setAttribute(OAuth20Constants.STATE, OAuth20Constants.ATTRTYPE_PARAM_QUERY, stateParams);
}
boolean isOpenId = false;
if (scopesAttr != null) {
for (String scope : scopesAttr) {
if (OIDCConstants.SCOPE_OPENID.equals(scope)) {
isOpenId = true;
break;
}
}
}
if (isOpenId) {
// if id_token_hint exists and user is already logged in, compare...
OAuthResultImpl result = validateIdTokenHintIfPresent(attrs, request);
if (result != null) {
return result;
}
}
prompt = new Prompt(request);
if (request.getUserPrincipal() == null || (prompt.hasLogin() && !afterLogin)) {
// authenticate user if not done yet
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED) && !request.isUserInRole(OAuth20Constants.TOKEN_MANAGER_ROLE)) { // must be authorized
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
if (reqConsentNonce != null && !consent.isNonceValid(request, reqConsentNonce)) { // nonce must be valid if has one
consent.handleNonceError(request, response);
return oauthResult;
}
String clientId = getClientId(request);
String[] reducedScopes = null;
try {
reducedScopes = clientAuthorization.getReducedScopes(provider, request, clientId, true);
} catch (Exception e1) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception, so setting reduced scopes to null. Exception was: " + e1);
}
reducedScopes = null;
}
boolean preAuthzed = false;
if (reqConsentNonce == null) {
try {
preAuthzed = clientAuthorization.isPreAuthorizedScope(provider, clientId, reducedScopes);
} catch (Exception e) {
preAuthzed = false;
}
}
// Handle consent
if (!autoauthz && !preAuthzed && reqConsentNonce == null && !consent.isCachedAndValid(oauthResult, provider, request, response)) {
if (prompt.hasNone()) {
// Prompt includes "none," however authorization has not been obtained or cached; return error
oauthResult = prompt.errorConsentRequired(attrs);
} else {
// ask user for approval if not auto authorized, or not approved
Nonce nonce = consent.setNonce(request);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "_SSO OP redirecting for consent");
}
consent.renderConsentForm(request, response, provider, clientId, nonce, oauthResult.getAttributeList(), servletContext);
}
return oauthResult;
}
if (reachedTokenLimit(provider, request)) {
return createTokenLimitResult(attrs, request, clientId);
}
if (request.getAttribute(OAuth20Constants.OIDC_REQUEST_OBJECT_ATTR_NAME) != null) {
// Ensure that the reduced scopes list is not empty
oauthResult = clientAuthorization.checkForEmptyScopeSetAfterConsent(reducedScopes, oauthResult, request, provider, clientId);
if (oauthResult != null && oauthResult.getStatus() != OAuthResult.STATUS_OK) {
response.setStatus(HttpServletResponse.SC_FOUND);
return oauthResult;
}
}
// getBack the resource. better double check it
OidcBaseClient client;
try {
client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
OAuth20ProviderUtils.validateResource(request, options, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
if (options != null) {
options.setAttribute(OAuth20Constants.SCOPE, OAuth20Constants.ATTRTYPE_RESPONSE_ATTRIBUTE, reducedScopes);
}
if (provider.isTrackOAuthClients()) {
OAuthClientTracker clientTracker = new OAuthClientTracker(request, response, provider);
clientTracker.trackOAuthClient(clientId);
}
consent.handleConsent(provider, request, prompt, clientId);
getExternalClaimsFromWSSubject(request, options);
oauthResult = provider.processAuthorization(request, response, options);
return oauthResult;
}
/**
* Secure registration services with BASIC Auth and validating against the required role.
*
* @param provider
* @param request
* @param response
* @param servletContext
* @param requiredRole - user must be in this role.
* @param fallbacktoBasicAuth - if false, if there is no cookie on the request, then no basic auth challenge will be sent back to browser.
* @throws OidcServerException
*/
@FFDCIgnore({ OidcServerException.class })
private void secureEndpointServices(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, String requiredRole, boolean fallbackToBasicAuth) throws OidcServerException {
try {
userAuthentication.handleBasicAuthenticationWithRequiredRole(provider, request, response, securityServiceRef, servletContext, requiredRole, fallbackToBasicAuth);
} catch (OidcServerException e) {
if (fallbackToBasicAuth) {
if (e.getHttpStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
response.setHeader(RegistrationEndpointServices.HDR_WWW_AUTHENTICATE, RegistrationEndpointServices.UNAUTHORIZED_HEADER_VALUE);
}
}
throw e;
}
}
@FFDCIgnore({ OAuth20BadParameterException.class })
public void processTokenRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) throws ServletException, OidcServerException {
String clientId = (String) request.getAttribute("authenticatedClient");
try {
// checking resource
OidcBaseClient client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
if (client == null || !client.isEnabled()) {
throw new OidcServerException("security.oauth20.error.invalid.client", OIDCConstants.ERROR_INVALID_CLIENT_METADATA, HttpServletResponse.SC_BAD_REQUEST);
}
OAuth20ProviderUtils.validateResource(request, null, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
OAuthResult result = clientAuthorization.validateAndHandle2LegsScope(provider, request, response, clientId);
if (result.getStatus() == OAuthResult.STATUS_OK) {
result = provider.processTokenRequest(clientId, request, response);
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
OAuth20TokenRequestExceptionHandler handler = new OAuth20TokenRequestExceptionHandler();
handler.handleResultException(request, response, result);
}
}
/**
* Get the access token from the request's token parameter and look it up in
* the token cache.
*
* If the access token is found in the cache return status 200 and a JSON object.
*
* If the token is not found or the request had errors return status 400.
*
* @param provider
* @param request
* @param response
* @throws OidcServerException
* @throws IOException
*/
public void introspect(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) throws OidcServerException, IOException {
TokenIntrospect tokenIntrospect = new TokenIntrospect();
tokenIntrospect.introspect(provider, request, response);
}
/**
* Revoke the provided token by removing it from the cache
*
* If the access token is found in the cache remove it from the cache
* and return status 200.
*
* @param provider
* @param request
* @param response
*/
public void revoke(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
try {
String tokenString = request.getParameter(com.ibm.ws.security.oauth20.util.UtilConstants.TOKEN);
if (tokenString == null) {
// send 400 per OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_REQUEST, null); // invalid_request
return;
}
String tokenLookupStr = tokenString;
OAuth20Token token = null;
boolean isAppPasswordOrToken = false;
if (OidcOAuth20Util.isJwtToken(tokenString)) {
tokenLookupStr = com.ibm.ws.security.oauth20.util.HashUtils.digest(tokenString);
} else if (tokenString.length() == (provider.getAccessTokenLength() + 2)) {
// app-token
String encode = provider.getAccessTokenEncoding();
if (OAuth20Constants.PLAIN_ENCODING.equals(encode)) { // must be app-password or app-token
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString);
} else {
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString, encode);
}
isAppPasswordOrToken = true;
}
if (isAppPasswordOrToken) {
token = provider.getTokenCache().getByHash(tokenLookupStr);
} else {
token = provider.getTokenCache().get(tokenLookupStr);
}
boolean isAppPassword = false;
if (token != null && OAuth20Constants.APP_PASSWORD.equals(token.getGrantType())) {
isAppPassword = true;
Tr.error(tc, "security.oauth20.apppwtok.revoke.disallowed", new Object[] {});
}
if (token == null) {
// send 200 per OAuth Token revocation spec
response.setStatus(HttpServletResponse.SC_OK);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token " + tokenString + " not in cache or wrong token type, return");
}
return;
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token type: " + token.getType());
}
ClientAuthnData clientAuthData = new ClientAuthnData(request, response);
if (clientAuthData.hasAuthnData() &&
clientAuthData.getUserName().equals(token.getClientId()) == true) {
if (!isAppPassword && ((token.getType().equals(OAuth20Constants.TOKENTYPE_AUTHORIZATION_GRANT) &&
token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) ||
token.getType().equals(OAuth20Constants.TOKENTYPE_ACCESS_TOKEN))) {
// Revoke the token by removing it from the cache
if (tc.isDebugEnabled()) {
OAuth20Token theToken = provider.getTokenCache().get(tokenLookupStr);
String buf = (theToken != null) ? "is in the cache" : "is not in the cache";
Tr.debug(tc, "token " + tokenLookupStr + " " + buf + ", calling remove");
}
if (isAppPasswordOrToken) {
provider.getTokenCache().removeByHash(tokenLookupStr);
} else {
provider.getTokenCache().remove(tokenLookupStr);
}
if (token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) {
removeAssociatedAccessTokens(request, provider, token);
}
response.setStatus(HttpServletResponse.SC_OK);
} else {
// Unsupported token type, send 400 per RFC7009 OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_UNSUPPORTED_TOKEN_TYPE, null);
}
} else {
// client is not authorized. send 400 per RFC6749 5.2 OAuth Token revocation spec
String defaultMsg = "CWWKS1406E: The revoke request had an invalid client credential. The request URI was {" + request.getRequestURI() + "}.";
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_INVALID_CLIENT",
new Object[] { "revoke", request.getRequestURI() },
defaultMsg);
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_CLIENT, errorMsg);
}
} catch (OAuth20DuplicateParameterException e) {
// Duplicate parameter found in request
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_REQUEST, e.getMessage());
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error processing token revoke request", e);
}
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (IOException ioe) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error process token introspect revoke error", ioe);
}
}
}
}
/**
* For OpenidConnect, when a refresh token is revoked, also delete all access tokens that have become associated with it.
* (Each time a refresh token is submitted for a new one, the prior access tokens become associated with the new refresh token)
* @param request
* @param provider
* @param refreshToken
* @throws Exception
*/
private void removeAssociatedAccessTokens(HttpServletRequest request, OAuth20Provider provider, OAuth20Token refreshToken) throws Exception {
String contextPath = request.getContextPath();
if (contextPath != null && !contextPath.equals("/oidc")) {
// if this is for oauth, return. Oauth's persistence code doesn't support this token association.
// and we only wanted revocation for oidc, we wanted to leave oauth alone.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "not oidc, returning");
}
return;
}
if (!provider.getRevokeAccessTokensWithRefreshTokens()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "provider prop revokeAccessTokensWithRefreshTokens is false, returning");
}
return;
}
String username = refreshToken.getUsername();
String clientId = refreshToken.getClientId();
String refreshTokenId = refreshToken.getId();
OAuth20EnhancedTokenCache cache = provider.getTokenCache();
Collection<OAuth20Token> ctokens = cache.getAllUserTokens(username);
for (OAuth20Token ctoken : ctokens) {
boolean nullGuard = (cache != null && ctoken.getType() != null && clientId != null && ctoken.getClientId() != null && ctoken.getId() != null);
if (nullGuard && OAuth20Constants.TOKENTYPE_ACCESS_TOKEN.equals(ctoken.getType()) && clientId.equals(ctoken.getClientId())
&& refreshTokenId.equals(((OAuth20TokenImpl) ctoken).getRefreshTokenKey())) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "removing token: " + ctoken.getId());
}
cache.remove(ctoken.getId());
}
}
}
protected void checkHttpsRequirement(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider) throws IOException {
String url = request.getRequestURL().toString();
if (provider.isHttpsRequired()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if URL starts with https: " + url);
}
if (url != null && !url.startsWith("https")) {
Tr.error(tc, "security.oauth20.error.wrong.http.scheme", new Object[] { url });
response.sendError(HttpServletResponse.SC_NOT_FOUND,
Tr.formatMessage(tc, "security.oauth20.error.wrong.http.scheme",
new Object[] { url }));
}
}
}
/**
* Determines if this user hit the token limit for the user / client combination
*
* @param provider
* @param request
* @return
*/
protected boolean reachedTokenLimit(OAuth20Provider provider, HttpServletRequest request) {
String userName = getUserName(request);
String clientId = getClientId(request);
long limit = provider.getClientTokenCacheSize();
if (limit > 0) {
long numtokens = provider.getTokenCache().getNumTokens(userName, clientId);
if (numtokens >= limit) {
Tr.error(tc, "security.oauth20.token.limit.error", new Object[] { userName, clientId, limit });
return true;
}
}
return false;
}
private OAuth20Request getAuth20Request(HttpServletRequest request, HttpServletResponse response) throws IOException {
OAuth20Request oauth20Request = (OAuth20Request) request.getAttribute(OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME);
if (oauth20Request == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_REQUEST_ATTRIBUTE_MISSING",
new Object[] { request.getRequestURI(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1412E: The request endpoint {0} does not have attribute {1}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return oauth20Request;
}
private OAuth20Provider getProvider(HttpServletResponse response, OAuth20Request oauth20Request) throws IOException {
OAuth20Provider provider = ProvidersService.getOAuth20Provider(oauth20Request.getProviderName());
if (provider == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_PROVIDER_OBJECT_NULL",
new Object[] { oauth20Request.getProviderName(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1413E: The OAuth20Provider object is null for OAuth provider {0}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return provider;
}
private String getReqConsentNonce(HttpServletRequest request) {
return request.getParameter(ATTR_NONCE);
}
private String getUserName(HttpServletRequest request) {
return request.getUserPrincipal().getName();
}
private String getClientId(HttpServletRequest request) {
return request.getParameter(OAuth20Constants.CLIENT_ID);
}
/* returns whether login form had been presented */
protected boolean isAfterLogin(HttpServletRequest request) {
boolean output = false;
HttpSession session = request.getSession(false);
if (session != null) {
if (session.getAttribute(Constants.ATTR_AFTERLOGIN) != null) {
session.removeAttribute(Constants.ATTR_AFTERLOGIN);
output = true;
}
}
return output;
}
/**
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String[]> getExternalClaimsFromWSSubject(HttpServletRequest request, AttributeList options) {
final String methodName = "getExternalClaimsFromWSSubject";
try {
String externalClaimNames = options.getAttributeValueByName(OAuth20Constants.EXTERNAL_CLAIM_NAMES);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClamiNames:" + externalClaimNames);
if (externalClaimNames != null) {
Map<String, String[]> map2 = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_MEDIATION);
if (map2 != null && map2.size() > 0) {
Set<Entry<String, String[]>> entries = map2.entrySet();
for (Entry<String, String[]> entry : entries) {
options.setAttribute(entry.getKey(), OAuth20Constants.EXTERNAL_MEDIATION, entry.getValue());
}
}
// get the external claims
Map<String, String[]> map = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_CLAIMS);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClaims:" + map);
if (map == null)
return null;
// filter properties by externalClaimNames
StringTokenizer strTokenizer = new StringTokenizer(externalClaimNames, ", ");
while (strTokenizer.hasMoreTokens()) {
String key = strTokenizer.nextToken();
String[] values = map.get(key);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " key:" + key + " values:'" + OAuth20Util.arrayToSpaceString(values) + "'");
if (values != null && values.length > 0) {
options.setAttribute(OAuth20Constants.EXTERNAL_CLAIMS_PREFIX + key, OAuth20Constants.EXTERNAL_CLAIMS, values);
}
}
return map;
}
} catch (WSSecurityException e) {
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " failed. Nothing changed. WSSecurityException:" + e);
}
return null;
}
/**
* @param externalClaims
* @return
*/
private Object getFromWSSubject(String externalClaims) throws WSSecurityException {
Subject runAsSubject = WSSubject.getRunAsSubject();
Object obj = null;
try {
Set<Object> publicCreds = runAsSubject.getPublicCredentials();
if (publicCreds != null && publicCreds.size() > 0) {
Iterator<Object> publicCredIterator = publicCreds.iterator();
while (publicCredIterator.hasNext()) {
Object cred = publicCredIterator.next();
if (cred != null && cred instanceof Hashtable) {
@SuppressWarnings("rawtypes")
Hashtable userCred = (Hashtable) cred;
obj = userCred.get(externalClaims);
if (obj != null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "getFromWSSubject found:" + obj);
}
break;
}
}
}
}
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Unable to match predefined cache key." + e);
}
}
return obj;
}
/**
* Check if the request contains an "error" parameter. If one is present and equals the OAuth 2.0 error type "access_denied", a message indicating the user likely canceled the request will be
* logged and a failure result will be returned.
*
* @param request
* @return A {@code OAuthResult} object initialized with AuthResult.FAILURE and 403 status code if an "error" parameter is present and equals "access_denied." Returns null otherwise.
*/
private OAuthResult checkForError(HttpServletRequest request) {
OAuthResult result = null;
String error = request.getParameter("error");
if (error != null && error.length() > 0 && OAuth20Exception.ACCESS_DENIED.equals(error)) {
// User likely canceled the request
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"security.oauth20.request.denied",
new Object[] {},
"CWOAU0067E: The request has been denied by the user, or another error occurred that resulted in denial of the request.");
Tr.error(tc, errorMsg);
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.request.denied");
e.setHttpStatusCode(HttpServletResponse.SC_FORBIDDEN);
AttributeList attrs = new AttributeList();
String value = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { value });
}
value = getClientId(request);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { value });
}
result = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
}
return result;
}
/**
* @param provider
* @param responseJSON
* @param accessToken
* @param groupsOnly
* @throws IOException
*/
protected Map<String, Object> getUserClaimsMap(UserClaims userClaims, boolean groupsOnly) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsMap(userClaims, groupsOnly);
}
protected UserClaims getUserClaimsObj(OAuth20Provider provider, OAuth20Token accessToken) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsObj(provider, accessToken);
}
}
| kgibm/open-liberty | dev/com.ibm.ws.security.oauth/src/com/ibm/ws/security/oauth20/web/OAuth20EndpointServices.java | Java | epl-1.0 | 60,040 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.