repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
openbase/jul | interface/src/main/java/org/openbase/jul/iface/TimedProcessable.java | 2825 | package org.openbase.jul.iface;
/*-
* #%L
* JUL Interface
* %%
* Copyright (C) 2015 - 2022 openbase.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 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.exception.FatalImplementationErrorException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Interface is used to process any data of type {@code <I>} into data of type {@code <O>} while the processing is limited in time.
*
* @param <I> Input type needed for processing.
* @param <O> Output type defining the process result.
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
*/
public interface TimedProcessable<I, O> extends Processable<I, O> {
/**
* Using Long.MAX_VALUE as infinity timeout is not practical because in any calculations using this timeout like adding +1 causes a value overrun.
* Therefore, this constant is introduced to use a infinity timeout which represents in fact 3170 years which should covers at least some human generations ;)
*
* The unit of the {@code INFINITY_TIMEOUT} is in milliseconds.
*/
long INFINITY_TIMEOUT = 100000000000000L;
/**
* @param input the input data to process.
* @param timeout the timeout of the processing.
* @param timeUnit the timeunit of the timeout.
*
* @return the result.
*
* @throws CouldNotPerformException is thrown if the processing failed.
* @throws InterruptedException is thrown if the thread was externally interrupted.
* @throws TimeoutException in thrown if the timeout was reached and the task is still not done.
*/
O process(final I input, final long timeout, final TimeUnit timeUnit) throws CouldNotPerformException, InterruptedException, TimeoutException;
@Override
default O process(final I input) throws CouldNotPerformException, InterruptedException {
try {
return process(input, INFINITY_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new FatalImplementationErrorException(this, e);
}
}
}
| lgpl-3.0 |
ideaconsult/i5 | iuclid_6_2-io/src/main/java/eu/europa/echa/iuclid6/namespaces/endpoint_study_record_immunotoxicity/_2/TestMaterials.java | 2692 |
package eu.europa.echa.iuclid6.namespaces.endpoint_study_record_immunotoxicity._2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="TestMaterialInformation" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}documentReferenceField"/>
* <element name="SpecificDetailsOnTestMaterialUsedForTheStudy" type="{http://iuclid6.echa.europa.eu/namespaces/platform-fields/v1}textFieldLarge"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"testMaterialInformation",
"specificDetailsOnTestMaterialUsedForTheStudy"
})
public class TestMaterials {
@XmlElement(name = "TestMaterialInformation", required = true)
protected String testMaterialInformation;
@XmlElement(name = "SpecificDetailsOnTestMaterialUsedForTheStudy", required = true)
protected String specificDetailsOnTestMaterialUsedForTheStudy;
/**
* Gets the value of the testMaterialInformation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTestMaterialInformation() {
return testMaterialInformation;
}
/**
* Sets the value of the testMaterialInformation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTestMaterialInformation(String value) {
this.testMaterialInformation = value;
}
/**
* Gets the value of the specificDetailsOnTestMaterialUsedForTheStudy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecificDetailsOnTestMaterialUsedForTheStudy() {
return specificDetailsOnTestMaterialUsedForTheStudy;
}
/**
* Sets the value of the specificDetailsOnTestMaterialUsedForTheStudy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecificDetailsOnTestMaterialUsedForTheStudy(String value) {
this.specificDetailsOnTestMaterialUsedForTheStudy = value;
}
}
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/test/java/org/sonar/server/computation/task/projectanalysis/qualitygate/ConditionTest.java | 2966 | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.computation.task.projectanalysis.qualitygate;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.server.computation.task.projectanalysis.metric.Metric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConditionTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private static final Metric SOME_METRIC = mock(Metric.class);
private static final String SOME_OPERATOR = "EQ";
@Test(expected = NullPointerException.class)
public void constructor_throws_NPE_for_null_metric_argument() {
new Condition(null, SOME_OPERATOR, null, null, false);
}
@Test(expected = NullPointerException.class)
public void constructor_throws_NPE_for_null_operator_argument() {
new Condition(SOME_METRIC, null, null, null, false);
}
@Test
public void constructor_throws_IAE_if_operator_is_not_valid() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Unsupported operator value: 'troloto'");
new Condition(SOME_METRIC, "troloto", null, null, false);
}
@Test
public void verify_getters() {
String error = "error threshold";
String warning = "warning threshold";
Condition condition = new Condition(SOME_METRIC, SOME_OPERATOR, error, warning, true);
assertThat(condition.getMetric()).isSameAs(SOME_METRIC);
assertThat(condition.getOperator()).isSameAs(Condition.Operator.EQUALS);
assertThat(condition.hasPeriod()).isTrue();
assertThat(condition.getErrorThreshold()).isEqualTo(error);
assertThat(condition.getWarningThreshold()).isEqualTo(warning);
}
@Test
public void all_fields_are_displayed_in_toString() {
when(SOME_METRIC.toString()).thenReturn("metric1");
assertThat(new Condition(SOME_METRIC, SOME_OPERATOR, "error_l", "warn", true).toString())
.isEqualTo("Condition{metric=metric1, hasPeriod=true, operator=EQUALS, warningThreshold=warn, errorThreshold=error_l}");
}
}
| lgpl-3.0 |
HATB0T/RuneCraftery | forge/mcp/temp/src/minecraft/net/minecraft/stats/StatBase.java | 2853 | package net.minecraft.stats;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import net.minecraft.stats.AchievementMap;
import net.minecraft.stats.IStatType;
import net.minecraft.stats.StatList;
import net.minecraft.stats.StatTypeDistance;
import net.minecraft.stats.StatTypeFloat;
import net.minecraft.stats.StatTypeSimple;
import net.minecraft.stats.StatTypeTime;
import net.minecraft.util.StatCollector;
public class StatBase {
public final int field_75975_e;
public final String field_75978_a;
public boolean field_75972_f;
public String field_75973_g;
private final IStatType field_75976_b;
private static NumberFormat field_75977_c = NumberFormat.getIntegerInstance(Locale.US);
public static IStatType field_75980_h = new StatTypeSimple();
private static DecimalFormat field_75974_d = new DecimalFormat("########0.00");
public static IStatType field_75981_i = new StatTypeTime();
public static IStatType field_75979_j = new StatTypeDistance();
public static IStatType field_111202_k = new StatTypeFloat();
public StatBase(int p_i1546_1_, String p_i1546_2_, IStatType p_i1546_3_) {
this.field_75975_e = p_i1546_1_;
this.field_75978_a = p_i1546_2_;
this.field_75976_b = p_i1546_3_;
}
public StatBase(int p_i1547_1_, String p_i1547_2_) {
this(p_i1547_1_, p_i1547_2_, field_75980_h);
}
public StatBase func_75966_h() {
this.field_75972_f = true;
return this;
}
public StatBase func_75971_g() {
if(StatList.field_75942_a.containsKey(Integer.valueOf(this.field_75975_e))) {
throw new RuntimeException("Duplicate stat id: \"" + ((StatBase)StatList.field_75942_a.get(Integer.valueOf(this.field_75975_e))).field_75978_a + "\" and \"" + this.field_75978_a + "\" at id " + this.field_75975_e);
} else {
StatList.field_75940_b.add(this);
StatList.field_75942_a.put(Integer.valueOf(this.field_75975_e), this);
this.field_75973_g = AchievementMap.func_75962_a(this.field_75975_e);
return this;
}
}
@SideOnly(Side.CLIENT)
public boolean func_75967_d() {
return false;
}
@SideOnly(Side.CLIENT)
public String func_75968_a(int p_75968_1_) {
return this.field_75976_b.func_75843_a(p_75968_1_);
}
@SideOnly(Side.CLIENT)
public String func_75970_i() {
return this.field_75978_a;
}
public String toString() {
return StatCollector.func_74838_a(this.field_75978_a);
}
@SideOnly(Side.CLIENT)
// $FF: synthetic method
static NumberFormat func_75965_j() {
return field_75977_c;
}
@SideOnly(Side.CLIENT)
// $FF: synthetic method
static DecimalFormat func_75969_k() {
return field_75974_d;
}
}
| lgpl-3.0 |
Putnami/putnami-web-toolkit | core/src/main/java/fr/putnami/pwt/core/widget/client/Affix.java | 6848 | /**
* This file is part of pwt.
*
* pwt is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser
* General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* pwt 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 pwt. If not,
* see <http://www.gnu.org/licenses/>.
*/
package fr.putnami.pwt.core.widget.client;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ScrollEvent;
import com.google.gwt.user.client.Window.ScrollHandler;
import com.google.gwt.user.client.ui.IsWidget;
import fr.putnami.pwt.core.event.client.HandlerRegistrationCollection;
import fr.putnami.pwt.core.theme.client.CssStyle;
import fr.putnami.pwt.core.widget.client.util.StyleUtils;
import fr.putnami.pwt.core.widget.client.util.WidgetUtils;
public class Affix extends OneWidgetPanel {
public enum Affixed implements CssStyle {
AFFIX("affix"),
TOP("affix-top"),
BOTTOM("affix-bottom");
private final String style;
Affixed(String style) {
this.style = style;
}
@Override
public String get() {
return this.style;
}
}
private final HandlerRegistrationCollection handlerRegistrationCollection = new HandlerRegistrationCollection();
private final ScrollHandler scrollHandler = new ScrollHandler() {
@Override
public void onWindowScroll(ScrollEvent event) {
Affix.this.resetPosistion();
}
};
private final ResizeHandler resizeHandler = new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
Affix.this.reset();
}
};
private Affixed affixed = Affixed.TOP;
private int clientHeigth = -1;
private int pinnedOffset = -1;
private int offsetWidth = -1;
private int offsetHeight = -1;
private int layerIndex = 1000;
private int offsetTop = 0;
private int offsetBottom = 0;
private int fixBottom = Integer.MIN_VALUE;
public Affix() {
super(DivElement.TAG);
StyleUtils.toggleStyle(Affix.this, this.affixed, true);
}
protected Affix(Affix source) {
super(source);
this.layerIndex = source.layerIndex;
this.offsetTop = source.offsetTop;
this.offsetBottom = source.offsetBottom;
this.fixBottom = source.fixBottom;
this.setWidget(WidgetUtils.cloneWidget(source.getWidget()));
}
@Override
public IsWidget cloneWidget() {
return new Affix(this);
}
@Override
protected void onLoad() {
super.onLoad();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
Affix.this.reset();
Affix.this.handlerRegistrationCollection.add(Window.addWindowScrollHandler(Affix.this.scrollHandler));
Affix.this.handlerRegistrationCollection.add(Window.addResizeHandler(Affix.this.resizeHandler));
}
});
}
@Override
protected void onUnload() {
super.onUnload();
this.handlerRegistrationCollection.removeHandler();
}
public int getLayerIndex() {
return this.layerIndex;
}
public void setLayerIndex(int zIndex) {
this.layerIndex = zIndex;
this.getElement().getStyle().setZIndex(this.layerIndex);
}
public int getPinnedOffset() {
return this.pinnedOffset;
}
@Override
public int getOffsetWidth() {
return this.offsetWidth;
}
@Override
public int getOffsetHeight() {
return this.offsetHeight;
}
public int getOffsetTop() {
return this.offsetTop;
}
public void setOffsetTop(int offsetTop) {
this.offsetTop = offsetTop;
}
public int getOffsetBottom() {
return this.offsetBottom;
}
public void setOffsetBottom(int offsetBottom) {
this.offsetBottom = offsetBottom;
}
public int getFixBottom() {
return this.fixBottom;
}
public void setFixBottom(int fixBottom) {
this.fixBottom = fixBottom;
}
public void resetPosistion() {
if (!this.isVisible()) {
return;
}
int scrollTop = Window.getScrollTop();
int docHeigth = Document.get().getScrollHeight();
this.getElement().getStyle().clearHeight();
this.offsetHeight = this.getElement().getClientHeight();
int top = this.pinnedOffset - scrollTop - this.offsetTop;
int bottom = docHeigth - scrollTop - this.offsetBottom - this.offsetTop - this.offsetHeight;
if (bottom <= 0 || this.fixBottom != Integer.MIN_VALUE) {
this.toggleAffix(Affixed.BOTTOM);
} else if (top >= 0) {
this.toggleAffix(Affixed.TOP);
} else {
this.toggleAffix(Affixed.AFFIX);
}
}
protected void toggleAffix(Affixed affix) {
Element e = this.getElement();
Style style = e.getStyle();
if (this.affixed != affix) {
this.clearElementStyle();
this.affixed = affix;
StyleUtils.addStyle(e, this.affixed);
}
switch (affix) {
case AFFIX:
style.setTop(this.offsetTop, Unit.PX);
style.setWidth(this.offsetWidth, Unit.PX);
style.setHeight(this.offsetHeight, Unit.PX);
style.setZIndex(this.layerIndex);
e.getParentElement().getStyle().setPaddingTop(this.offsetHeight, Unit.PX);
break;
case BOTTOM:
int docHeigth = Document.get().getScrollHeight();
int scrollTop = Window.getScrollTop();
int bottom = this.offsetBottom - (docHeigth - scrollTop - this.clientHeigth);
if (this.fixBottom != Integer.MIN_VALUE) {
bottom = Math.max(bottom, this.fixBottom);
}
style.setPosition(Position.FIXED);
style.setBottom(bottom, Unit.PX);
style.setWidth(this.offsetWidth, Unit.PX);
style.setHeight(this.offsetHeight, Unit.PX);
style.setZIndex(this.layerIndex);
break;
default:
break;
}
}
public void reset() {
Element e = this.getElement();
StyleUtils.addStyle(e, Affixed.TOP);
this.clearElementStyle();
this.clientHeigth = Window.getClientHeight();
this.pinnedOffset = e.getAbsoluteTop();
this.offsetWidth = e.getClientWidth();
StyleUtils.addStyle(e, this.affixed);
this.resetPosistion();
}
private void clearElementStyle() {
Element e = this.getElement();
Style style = e.getStyle();
style.clearPosition();
style.clearTop();
style.clearBottom();
style.clearWidth();
style.clearHeight();
style.clearZIndex();
e.getParentElement().getStyle().clearPaddingTop();
}
}
| lgpl-3.0 |
adrienlauer/kernel | specs/src/test/java/io/nuun/kernel/api/plugin/request/annotations/InjectedPlugin.java | 4149 | /**
* Copyright (C) 2014 Kametic <epo.jemba@kametic.com>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nuun.kernel.api.plugin.request.annotations;
import io.nuun.kernel.api.di.UnitModule;
import io.nuun.kernel.api.plugin.InitState;
import io.nuun.kernel.api.plugin.KernelService;
import io.nuun.kernel.api.plugin.context.InitContext;
import io.nuun.kernel.api.plugin.request.RequestType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import javax.inject.Inject;
import javax.inject.Named;
import org.kametic.specifications.AbstractSpecification;
/**
* @author epo.jemba{@literal @}kametic.com
*
*/
public class InjectedPlugin extends TestPlugin
{
final Object object = "Epo Jemba";
@Override
public String name()
{
return "injected-plugin";
}
public class MySpecification extends AbstractSpecification<Class<?>>
{
@Inject @Named("itf")
Collection<Class<?>> implementation;
@Override
public boolean isSatisfiedBy(Class<?> candidate)
{
return object != null;
}
}
KernelService kernelService;
@KernelParams("param")
String param;
@Dependent
Plugin1 plugin1;
@Required
Plugin2 plugin2;
@KernelParams("param")
String param1;
/*
* name = "implementation" implies that this Key Collection<Class<?>+"implementation"
* Will be available to the outer specification.
*/
@Scan(value = MySpecification.class , name = "itf")
Collection<Class<?>> interfaces;
@Scan(MySpecification.class) @Round(2)
Collection<Class<?>> implementation;
@Scan(type=RequestType.RESOURCES_REGEX_MATCH , valueString = "properties.txt")
Collection<String> resources;
@Scan(type=RequestType.SUBTYPE_OF_BY_CLASS , valueClass = Plugin1.class)
Collection<Class<?>> childPlugin;
@Override
public InitState init(InitContext initContext)
{
return super.init(initContext);
}
@Override
public UnitModule unitModule()
{
return null;
}
public void test()
{
System.out.println("Constructors");
System.out.println("Enclosing class " + MySpecification.class.getEnclosingClass());
Constructor<?>[] constructors = MySpecification.class.getDeclaredConstructors();
if (constructors != null)
{
for( Constructor<?> constructor : constructors)
{
System.out.println( " => " + constructor.getParameterTypes().length );
System.out.println( " => " + constructor.getParameterTypes()[0].getName() );
MySpecification specification = null;
try
{
specification = (MySpecification) constructor.newInstance(this);
this.new MySpecification();
this.new MySpecification();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
System.out.println( "s " + specification.isSatisfiedBy(getClass()));
}
}
}
}
| lgpl-3.0 |
elmomalmo/jslint4idea | src/main/java/com/malethan/jslint4idea/annotate/JsLintProcessor.java | 1633 | package com.malethan.jslint4idea.annotate;
import com.googlecode.jslint4java.JSLint;
import com.googlecode.jslint4java.JSLintBuilder;
import com.googlecode.jslint4java.JSLintResult;
import com.googlecode.jslint4java.Option;
import java.util.Arrays;
import java.util.List;
/**
* @author Elwyn Malethan <emalethan@specificmedia.com>
*/
public class JsLintProcessor {
private JSLint lint;
public JsLintProcessor(String jsLingCfg) {
this.lint = new JSLintBuilder().fromDefault();
updateJsLintOptions(jsLingCfg);
}
public void updateJsLintOptions(String jslintCfg) {
this.lint.resetOptions();
List<String> options = Arrays.asList(jslintCfg.split(","));
for (Option o : Option.values()) {
if(o.getType() == Boolean.class) {
this.lint.addOption(o, "false");
}
for (String cfgOpt : options) {
if(cfgOpt.startsWith(o.name().toLowerCase())) {
if(o.getType() == Boolean.class) {
this.lint.addOption(o);
} else if(o.getType() == Integer.class) {
String[] pair = cfgOpt.split("=");
this.lint.addOption(o, pair[1]);
}
}
}
}
}
public JsLintIssueSet process(String filename, String text) {
if (filename.endsWith(".js")) {
JSLintResult result = lint.lint(filename, text);
return new JsLintIssueSet(filename, result, text);
} else {
return new JsLintIssueSet();
}
}
}
| lgpl-3.0 |
DivineCooperation/jul | visual/javafx/src/main/java/org/openbase/jul/visual/javafx/transform/JFXColorToHSBColorTransformer.java | 1843 | package org.openbase.jul.visual.javafx.transform;
/*-
* #%L
* JUL Visual JavaFX
* %%
* Copyright (C) 2015 - 2021 openbase.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 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import javafx.scene.paint.Color;
import org.openbase.jul.exception.CouldNotTransformException;
import org.openbase.type.vision.HSBColorType.HSBColor;
/**
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
*/
public class JFXColorToHSBColorTransformer {
public static Color transform(final HSBColor hsbColor, double opacity) throws CouldNotTransformException {
try {
return Color.hsb(hsbColor.getHue(), hsbColor.getSaturation(), hsbColor.getBrightness(), opacity);
} catch (final IllegalArgumentException ex) {
throw new CouldNotTransformException(hsbColor, Color.class, ex);
}
}
public static Color transform(final HSBColor hsbColor) throws CouldNotTransformException {
return transform(hsbColor, 1.0);
}
public static HSBColor transform(final Color color) {
return HSBColor.newBuilder().setHue(color.getHue()).setSaturation(color.getSaturation()).setBrightness(color.getBrightness()).build();
}
}
| lgpl-3.0 |
eenbp/OpenNaaS-0.14-Marketplace | extensions/bundles/vcpe/src/main/java/org/opennaas/extensions/vcpe/repository/VCPENetBootstrapper.java | 2444 | package org.opennaas.extensions.vcpe.repository;
import org.opennaas.core.resources.IResourceBootstrapper;
import org.opennaas.core.resources.ObjectSerializer;
import org.opennaas.core.resources.Resource;
import org.opennaas.core.resources.ResourceException;
import org.opennaas.core.resources.SerializationException;
import org.opennaas.core.resources.descriptor.vcpe.VCPENetworkDescriptor;
import org.opennaas.extensions.vcpe.model.VCPENetworkModel;
public class VCPENetBootstrapper implements IResourceBootstrapper {
@Override
public void bootstrap(Resource resource) throws ResourceException {
VCPENetworkModel model = createEmptyModel(resource);
if (((VCPENetworkDescriptor) resource.getResourceDescriptor()).getvCPEModel()
!= null) {
// load model from the one persisted in the descriptor
model = loadModelFromDescriptor(
(VCPENetworkDescriptor) resource.getResourceDescriptor());
}
resource.setModel(model);
}
@Override
public void revertBootstrap(Resource resource) throws ResourceException {
// persist model into descriptor
storeModelIntoDescriptor((VCPENetworkModel) resource.getModel(), (VCPENetworkDescriptor) resource.getResourceDescriptor());
// reset the model
resetModel(resource);
}
@Override
public void resetModel(Resource resource) throws ResourceException {
resource.setModel(createEmptyModel(resource));
}
private VCPENetworkModel createEmptyModel(Resource resource) {
VCPENetworkModel model = new VCPENetworkModel();
model.setVcpeNetworkId(resource.getResourceIdentifier().getId());
model.setVcpeNetworkName(resource.getResourceDescriptor().getInformation().getName());
model.setCreated(false);
return model;
}
private VCPENetworkModel loadModelFromDescriptor(VCPENetworkDescriptor descriptor)
throws ResourceException {
try {
VCPENetworkModel model = (VCPENetworkModel) ObjectSerializer.fromXml(
descriptor.getvCPEModel(), VCPENetworkModel.class);
return model;
} catch (SerializationException e) {
throw new ResourceException(e);
}
}
private VCPENetworkDescriptor storeModelIntoDescriptor(VCPENetworkModel model,
VCPENetworkDescriptor descriptor) throws ResourceException {
if (model == null) {
descriptor.setvCPEModel(null);
} else {
try {
descriptor.setvCPEModel(ObjectSerializer.toXml(model));
} catch (SerializationException e) {
throw new ResourceException(e);
}
}
return descriptor;
}
}
| lgpl-3.0 |
git-moss/DrivenByMoss | src/main/java/de/mossgrabers/bitwig/framework/hardware/HwTextDisplayImpl.java | 1343 | // Written by Jürgen Moßgraber - mossgrabers.de
// (c) 2017-2022
// Licensed under LGPLv3 - http://www.gnu.org/licenses/lgpl-3.0.txt
package de.mossgrabers.bitwig.framework.hardware;
import de.mossgrabers.framework.controller.hardware.AbstractHwControl;
import de.mossgrabers.framework.controller.hardware.IHwTextDisplay;
import com.bitwig.extension.controller.api.HardwareTextDisplay;
/**
* Implementation of a proxy to a text display on a hardware controller.
*
* @author Jürgen Moßgraber
*/
public class HwTextDisplayImpl extends AbstractHwControl implements IHwTextDisplay
{
private final HardwareTextDisplay textDisplay;
/**
* Constructor.
*
* @param textDisplay The Bitwig text display proxy
*/
public HwTextDisplayImpl (final HardwareTextDisplay textDisplay)
{
super (null, null);
this.textDisplay = textDisplay;
}
/** {@inheritDoc}} */
@Override
public void setBounds (final double x, final double y, final double width, final double height)
{
this.textDisplay.setBounds (x, y, width, height);
}
/** {@inheritDoc}} */
@Override
public void setLine (final int line, final String text)
{
this.textDisplay.line (line).text ().setValue (text);
}
}
| lgpl-3.0 |
Latency/UtopianBot | src/org/rsbot/client/Signlink.java | 174 | package org.rsbot.client;
import java.applet.Applet;
import java.awt.*;
public interface Signlink {
public EventQueue getEventQueue();
public Applet getGameApplet();
}
| lgpl-3.0 |
aotian16/qefeeshare | src/main/java/com/qefee/qefeeshare/UserRepository.java | 285 | package com.qefee.qefeeshare;
import org.springframework.data.repository.CrudRepository;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
public interface UserRepository extends CrudRepository<User, Long> {
}
| lgpl-3.0 |
abdollahpour/xweb-wiki | src/main/java/info/bliki/wiki/template/UCFirst.java | 893 | package info.bliki.wiki.template;
import info.bliki.wiki.model.IWikiModel;
import java.util.List;
/**
* A template parser function for <code>{{ucfirst: ... }}</code> <i>first
* character to upper case</i> syntax. See <a
* href="http://en.wikipedia.org/wiki/Help:Variable#Formatting">Wikipedia -
* Help:Variable#Formatting</a>
*
*/
public class UCFirst extends AbstractTemplateFunction {
public final static ITemplateFunction CONST = new UCFirst();
public UCFirst() {
}
@Override
public String parseFunction(List<String> list, IWikiModel model, char[] src, int beginIndex, int endIndex, boolean isSubst) {
if (list.size() > 0) {
String word = isSubst ? list.get(0) : parseTrim(list.get(0), model);
if (word.length() > 0) {
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
return "";
}
return null;
}
}
| lgpl-3.0 |
kbss-cvut/jopa | ontodriver-owlapi/src/test/java/cz/cvut/kbss/ontodriver/owlapi/query/QueryResultGenerator.java | 5942 | /**
* Copyright (C) 2022 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.ontodriver.owlapi.query;
import cz.cvut.kbss.ontodriver.owlapi.util.OwlapiUtils;
import cz.cvut.kbss.owl2query.model.GroundTerm;
import cz.cvut.kbss.owl2query.model.QueryResult;
import cz.cvut.kbss.owl2query.model.ResultBinding;
import cz.cvut.kbss.owl2query.model.Variable;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLDataFactory;
import org.semanticweb.owlapi.model.OWLObject;
import uk.ac.manchester.cs.owl.owlapi.OWLDataFactoryImpl;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class QueryResultGenerator {
private final OWLDataFactory dataFactory = new OWLDataFactoryImpl();
QueryResult<OWLObject> generate(List<String> variableNames, List<List<Object>> values) {
final List<Variable<OWLObject>> vars = variableNames.stream().map(name -> {
final Variable<OWLObject> var = mock(Variable.class);
when(var.getName()).thenReturn(name);
return var;
}).collect(Collectors.toList());
final QueryResult<OWLObject> result = new QueryResultImpl(vars);
initData(result, values);
return result;
}
private void initData(QueryResult<OWLObject> result, List<List<Object>> values) {
if (values.isEmpty()) {
return;
}
assert result.getResultVars().size() == values.get(0).size();
for (List<Object> row : values) {
final ResultBinding<OWLObject> binding = new ResultBindingImpl();
for (int i = 0; i < row.size(); i++) {
final Object value = row.get(i);
if (value == null) {
binding.put(result.getResultVars().get(i), null);
continue;
}
final GroundTerm<OWLObject> gt = mock(GroundTerm.class);
final OWLObject owlValue;
if (value instanceof URI) {
owlValue = dataFactory.getOWLNamedIndividual(IRI.create(value.toString()));
} else {
owlValue = OwlapiUtils.createOWLLiteralFromValue(value, "en");
}
when(gt.getWrappedObject()).thenReturn(owlValue);
binding.put(result.getResultVars().get(i), gt);
}
result.add(binding);
}
}
private static class QueryResultImpl implements QueryResult<OWLObject> {
private final List<ResultBinding<OWLObject>> bindings = new ArrayList<>();
private final List<Variable<OWLObject>> variables;
private QueryResultImpl(List<Variable<OWLObject>> variables) {
this.variables = variables;
}
@Override
public boolean add(ResultBinding<OWLObject> resultBinding) {
return bindings.add(resultBinding);
}
@Override
public List<Variable<OWLObject>> getResultVars() {
return Collections.unmodifiableList(variables);
}
@Override
public boolean isDistinct() {
return false;
}
@Override
public boolean isEmpty() {
return bindings.isEmpty();
}
@Override
public int size() {
return bindings.size();
}
@Override
public Iterator<ResultBinding<OWLObject>> iterator() {
return bindings.iterator();
}
}
private static class ResultBindingImpl implements ResultBinding<OWLObject> {
private final Map<Variable<OWLObject>, GroundTerm<OWLObject>> map = new HashMap<>();
@Override
public ResultBinding<OWLObject> clone() {
return null;
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public GroundTerm<OWLObject> get(Object key) {
return map.get(key);
}
@Override
public GroundTerm<OWLObject> put(Variable<OWLObject> key, GroundTerm<OWLObject> value) {
return map.put(key, value);
}
@Override
public GroundTerm<OWLObject> remove(Object key) {
return map.remove(key);
}
@Override
public void putAll(Map<? extends Variable<OWLObject>, ? extends GroundTerm<OWLObject>> m) {
map.putAll(m);
}
@Override
public void clear() {
map.clear();
}
@Override
public Set<Variable<OWLObject>> keySet() {
return map.keySet();
}
@Override
public Collection<GroundTerm<OWLObject>> values() {
return map.values();
}
@Override
public Set<Entry<Variable<OWLObject>, GroundTerm<OWLObject>>> entrySet() {
return map.entrySet();
}
}
}
| lgpl-3.0 |
m2sf/m2j | ProtoDotWriter.java | 2368 | /* M2J -- Modula-2 to Java Translator & Compiler
*
* Copyright (c) 2016 The Modula-2 Software Foundation
*
* Author & Maintainer: Benjamin Kowarsch <trijezdci@org.m2sf>
*
* @synopsis
*
* M2J is a multi-dialect Modula-2 to Java translator and via-Java compiler.
* It supports the dialects described in the 3rd and 4th editions of Niklaus
* Wirth's book "Programming in Modula-2" (PIM) published by Springer Verlag,
* and an extended mode with select features from the revised language by
* B.Kowarsch and R.Sutcliffe "Modula-2 Revision 2010" (M2R10).
*
* In translator mode, M2J translates Modula-2 source to Java source files.
* In compiler mode, M2J compiles Modula-2 source via Java source files
* to Java .class files using the host system's resident Java compiler.
*
* @repository
*
* https://github.com/m2sf/m2j
*
* @file
*
* ProtoDotWriter.java
*
* Public interface for AST export to GraphViz DOT.
*
* @license
*
* M2J is free software: you can redistribute and/or modify it under the
* terms of the GNU Lesser General Public License (LGPL) either version 2.1
* or at your choice version 3 as published by the Free Software Foundation.
* However, you may not alter the copyright, author and license information.
*
* M2J 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. Read the license for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with m2j. If not, see <https://www.gnu.org/copyleft/lesser.html>.
*
* NB: Components in the domain part of email addresses are in reverse order.
*/
package org.m2sf.m2j;
interface ProtoDotWriter {
/* ---------------------------------------------------------------------------
* method WriteDot(path, ast)
* ---------------------------------------------------------------------------
* Writes the given abstract syntax tree in Graphviz DOT format to the given
* output file at the given path and returns a paired result with the number
* of characters written and a status code.
* ------------------------------------------------------------------------ */
public Result<Number /* chars written */, IOStatus>
WriteDot (String path, ProtoAstNode ast);
} /* ProtoDotWriter */
/* END OF FILE */ | lgpl-3.0 |
jjm223/MyPet | modules/v1_10_R1/src/main/java/de/Keyle/MyPet/compat/v1_10_R1/entity/types/EntityMySheep.java | 5001 | /*
* This file is part of MyPet
*
* Copyright © 2011-2016 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.compat.v1_10_R1.entity.types;
import de.Keyle.MyPet.api.Configuration;
import de.Keyle.MyPet.api.entity.EntitySize;
import de.Keyle.MyPet.api.entity.MyPet;
import de.Keyle.MyPet.api.entity.types.MySheep;
import de.Keyle.MyPet.compat.v1_10_R1.entity.EntityMyPet;
import de.Keyle.MyPet.compat.v1_10_R1.entity.ai.movement.EatGrass;
import net.minecraft.server.v1_10_R1.*;
import org.bukkit.DyeColor;
@EntitySize(width = 0.7F, height = 1.2349999f)
public class EntityMySheep extends EntityMyPet {
private static final DataWatcherObject<Boolean> ageWatcher = DataWatcher.a(EntityMySheep.class, DataWatcherRegistry.h);
private static final DataWatcherObject<Byte> colorWatcher = DataWatcher.a(EntityMySheep.class, DataWatcherRegistry.a);
public EntityMySheep(World world, MyPet myPet) {
super(world, myPet);
}
@Override
protected String getDeathSound() {
return "entity.sheep.death";
}
@Override
protected String getHurtSound() {
return "entity.sheep.hurt";
}
protected String getLivingSound() {
return "entity.sheep.ambient";
}
public boolean handlePlayerInteraction(EntityHuman entityhuman, EnumHand enumhand, ItemStack itemStack) {
if (super.handlePlayerInteraction(entityhuman, enumhand, itemStack)) {
return true;
}
if (getOwner().equals(entityhuman) && itemStack != null && canUseItem()) {
if (itemStack.getItem() == Items.DYE && itemStack.getData() <= 15 && itemStack.getData() != getMyPet().getColor().getDyeData() && !getMyPet().isSheared()) {
getMyPet().setColor(DyeColor.getByDyeData((byte) itemStack.getData()));
if (!entityhuman.abilities.canInstantlyBuild) {
if (--itemStack.count <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null);
}
}
return true;
} else if (itemStack.getItem() == Items.SHEARS && Configuration.MyPet.Sheep.CAN_BE_SHEARED && !getMyPet().isSheared()) {
getMyPet().setSheared(true);
int woolDropCount = 1 + this.random.nextInt(3);
for (int j = 0; j < woolDropCount; ++j) {
EntityItem entityitem = new EntityItem(this.world, this.locX, this.locY + 1, this.locZ, new ItemStack(Blocks.WOOL, 1, getMyPet().getColor().ordinal()));
entityitem.pickupDelay = 10;
entityitem.motY += (double) (this.random.nextFloat() * 0.05F);
this.world.addEntity(entityitem);
}
makeSound("entity.sheep.shear", 1.0F, 1.0F);
if (!entityhuman.abilities.canInstantlyBuild) {
itemStack.damage(1, entityhuman);
}
return true;
} else if (Configuration.MyPet.Sheep.GROW_UP_ITEM.compare(itemStack) && getMyPet().isBaby() && getOwner().getPlayer().isSneaking()) {
if (!entityhuman.abilities.canInstantlyBuild) {
if (--itemStack.count <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null);
}
}
getMyPet().setBaby(false);
return true;
}
}
return false;
}
protected void initDatawatcher() {
super.initDatawatcher();
this.datawatcher.register(ageWatcher, false); // age
this.datawatcher.register(colorWatcher, (byte) 0); // color/sheared
}
@Override
public void updateVisuals() {
this.datawatcher.set(ageWatcher, getMyPet().isBaby());
byte data = (byte) (getMyPet().isSheared() ? 16 : 0);
this.datawatcher.set(colorWatcher, (byte) (data & 0xF0 | getMyPet().getColor().ordinal() & 0xF));
}
public void playPetStepSound() {
makeSound("entity.sheep.step", 0.15F, 1.0F);
}
public MySheep getMyPet() {
return (MySheep) myPet;
}
public void setPathfinder() {
super.setPathfinder();
petPathfinderSelector.addGoal("EatGrass", new EatGrass(this));
}
} | lgpl-3.0 |
austinv11/Discord4J | rest/src/test/java/discord4j/rest/request/BucketKeyTest.java | 2206 | /*
* This file is part of Discord4J.
*
* Discord4J is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Discord4J 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 Discord4J. If not, see <http://www.gnu.org/licenses/>.
*/
package discord4j.rest.request;
import discord4j.rest.util.RouteUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class BucketKeyTest {
@Test
public void testRouteWithMajorParamSupport() {
String template = "/channels/{channel.id}/messages";
BucketKey key1 = BucketKey.of(template, RouteUtils.expand(template, 111111111));
BucketKey key2 = BucketKey.of(template, RouteUtils.expand(template, 222222222));
assertNotEquals(key1, key2);
assertNotEquals(key1.hashCode(), key2.hashCode());
}
@Test
public void testRouteWithoutMajorParamSupport() {
String template = "/invites/{invite.code}";
BucketKey keyA = BucketKey.of(template, RouteUtils.expand(template, "AAAAAA"));
BucketKey keyB = BucketKey.of(template, RouteUtils.expand(template, "BBBBBB"));
assertEquals(keyA, keyB);
assertEquals(keyA.hashCode(), keyB.hashCode());
}
@Test
public void testRouteWithModifiedTemplate() {
String template1 = "/channels/{channel.id}/messages/{message.id}";
String template2 = "DELETE /channels/{channel.id}/messages/{message.id}";
BucketKey key1 = BucketKey.of(template1, RouteUtils.expand(template1, 1, 2));
BucketKey key2 = BucketKey.of(template2, RouteUtils.expand(template2, 1, 2));
assertNotEquals(key1, key2);
assertNotEquals(key1.hashCode(), key2.hashCode());
}
}
| lgpl-3.0 |
mugenya/arch_app | src/main/java/s2jh/biz/crawl/expo/ExpoStartHtmlParseFilter.java | 558 | package s2jh.biz.crawl.expo;
import lab.s2jh.module.crawl.vo.WebPage;
import com.mongodb.DBObject;
public class ExpoStartHtmlParseFilter extends ExpoBaseHtmlParseFilter {
@Override
public String getUrlFilterRegex() {
return "^http://www.expo-china.com/?$";
}
@Override
public DBObject filterInternal(String url, WebPage webPage, DBObject parsedDBObject) throws Exception {
webPage.addOutlink("http://www.expo-china.com/web/exhi/exhi_search.aspx?Province=0&Industry=-1&Keywords=&page=1");
return null;
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java | 7415 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.duplication.ws;
import com.google.common.annotations.VisibleForTesting;
import static java.util.Optional.ofNullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonarqube.ws.Duplications;
import org.sonarqube.ws.Duplications.Block;
import org.sonarqube.ws.Duplications.ShowResponse;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ShowResponseBuilder {
private final ComponentDao componentDao;
@Inject
public ShowResponseBuilder(DbClient dbClient) {
this.componentDao = dbClient.componentDao();
}
@VisibleForTesting
ShowResponseBuilder(ComponentDao componentDao) {
this.componentDao = componentDao;
}
ShowResponse build(DbSession session, List<DuplicationsParser.Block> blocks, @Nullable String branch, @Nullable String pullRequest) {
Map<String, Reference> refByComponentKey = new LinkedHashMap<>();
ShowResponse.Builder response = ShowResponse.newBuilder();
blocks.stream()
.map(block -> toWsDuplication(block, refByComponentKey))
.forEach(response::addDuplications);
writeFileRefs(session, refByComponentKey, response, branch, pullRequest);
return response.build();
}
private static Duplications.Duplication.Builder toWsDuplication(DuplicationsParser.Block block, Map<String, Reference> refByComponentKey) {
Duplications.Duplication.Builder wsDuplication = Duplications.Duplication.newBuilder();
block.getDuplications().stream()
.map(duplication -> toWsBlock(duplication, refByComponentKey))
.forEach(wsDuplication::addBlocks);
return wsDuplication;
}
private static Block.Builder toWsBlock(Duplication duplication, Map<String, Reference> refByComponentKey) {
Block.Builder block = Block.newBuilder();
if (!duplication.removed()) {
Reference ref = refByComponentKey.computeIfAbsent(duplication.componentDbKey(), k -> new Reference(
Integer.toString(refByComponentKey.size() + 1),
duplication.componentDto(),
duplication.componentDbKey()));
block.setRef(ref.getId());
}
block.setFrom(duplication.from());
block.setSize(duplication.size());
return block;
}
private void writeFileRefs(DbSession session, Map<String, Reference> refByComponentKey, ShowResponse.Builder response, @Nullable String branch, @Nullable String pullRequest) {
Map<String, ComponentDto> projectsByUuid = new HashMap<>();
Map<String, ComponentDto> parentModulesByUuid = new HashMap<>();
for (Map.Entry<String, Reference> entry : refByComponentKey.entrySet()) {
Reference ref = entry.getValue();
ComponentDto file = ref.getDto();
if (file != null) {
ComponentDto project = getProject(file.projectUuid(), projectsByUuid, session);
ComponentDto parentModule = getParentProject(file.moduleUuid(), parentModulesByUuid, session);
response.putFiles(ref.getId(), toWsFile(file, project, parentModule, branch, pullRequest));
} else {
response.putFiles(ref.getId(), toWsFile(ref.getComponentKey(), branch, pullRequest));
}
}
}
private static Duplications.File toWsFile(String componentKey, @Nullable String branch, @Nullable String pullRequest) {
Duplications.File.Builder wsFile = Duplications.File.newBuilder();
String keyWithoutBranch = ComponentDto.removeBranchAndPullRequestFromKey(componentKey);
wsFile.setKey(keyWithoutBranch);
wsFile.setName(StringUtils.substringAfterLast(keyWithoutBranch, ":"));
ofNullable(branch).ifPresent(wsFile::setBranch);
ofNullable(pullRequest).ifPresent(wsFile::setPullRequest);
return wsFile.build();
}
private static Duplications.File toWsFile(ComponentDto file, @Nullable ComponentDto project, @Nullable ComponentDto subProject,
@Nullable String branch, @Nullable String pullRequest) {
Duplications.File.Builder wsFile = Duplications.File.newBuilder();
wsFile.setKey(file.getKey());
wsFile.setUuid(file.uuid());
wsFile.setName(file.longName());
// Do not return sub project if sub project and project are the same
ofNullable(project).ifPresent(p -> {
wsFile.setProject(p.getKey());
wsFile.setProjectUuid(p.uuid());
wsFile.setProjectName(p.longName());
// Do not return sub project if sub project and project are the same
boolean displaySubProject = subProject != null && !subProject.uuid().equals(project.uuid());
if (displaySubProject) {
wsFile.setSubProject(subProject.getKey());
wsFile.setSubProjectUuid(subProject.uuid());
wsFile.setSubProjectName(subProject.longName());
}
ofNullable(branch).ifPresent(wsFile::setBranch);
ofNullable(pullRequest).ifPresent(wsFile::setPullRequest);
});
return wsFile.build();
}
private ComponentDto getProject(String projectUuid, Map<String, ComponentDto> projectsByUuid, DbSession session) {
ComponentDto project = projectsByUuid.get(projectUuid);
if (project == null) {
Optional<ComponentDto> projectOptional = componentDao.selectByUuid(session, projectUuid);
if (projectOptional.isPresent()) {
project = projectOptional.get();
projectsByUuid.put(project.uuid(), project);
}
}
return project;
}
private ComponentDto getParentProject(String rootUuid, Map<String, ComponentDto> subProjectsByUuid, DbSession session) {
ComponentDto project = subProjectsByUuid.get(rootUuid);
if (project == null) {
Optional<ComponentDto> projectOptional = componentDao.selectByUuid(session, rootUuid);
if (projectOptional.isPresent()) {
project = projectOptional.get();
subProjectsByUuid.put(project.uuid(), project);
}
}
return project;
}
private static class Reference {
private final String id;
private final ComponentDto dto;
private final String componentKey;
public Reference(String id, @Nullable ComponentDto dto, String componentKey) {
this.id = id;
this.dto = dto;
this.componentKey = componentKey;
}
public String getId() {
return id;
}
@CheckForNull
public ComponentDto getDto() {
return dto;
}
public String getComponentKey() {
return componentKey;
}
}
}
| lgpl-3.0 |
geniejang/ProblemSolving | Leetcode/src/leetcode/no109_ConvertSortedListToBinarySearchTree/Solution.java | 663 | package leetcode.no109_ConvertSortedListToBinarySearchTree;
import leetcode.ListNode;
import leetcode.TreeNode;
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
return sortedListToBST(head, null);
}
private TreeNode sortedListToBST(ListNode head, ListNode tail) {
if (head == tail) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
TreeNode root = new TreeNode(slow.val);
root.left = sortedListToBST(head, slow);
root.right = sortedListToBST(slow.next, tail);
return root;
}
}
| lgpl-3.0 |
arcuri82/testing_security_development_enterprise_systems | intro/spring/jsf/src/main/java/org/tsdes/intro/spring/jsf/RedirectForwardHandler.java | 573 | package org.tsdes.intro.spring.jsf;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/*
Special bean that we use to handle HTTP requests.
In particular, we want to intercept the requests for the root "/",
and return the content of index.html
*/
@Controller
public class RedirectForwardHandler {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String forward(){
return "forward:index.html";
}
}
| lgpl-3.0 |
gstreamer-java/gst1-java-core | src/org/freedesktop/gstreamer/GstIterator.java | 1713 | /*
* Copyright (c) 2021 Neil C Smith
*
* This file is part of gstreamer-java.
*
* This code is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License version 3 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 3 for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with this work. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freedesktop.gstreamer;
import java.util.ArrayList;
import java.util.List;
import org.freedesktop.gstreamer.glib.NativeObject;
import org.freedesktop.gstreamer.lowlevel.GstIteratorPtr;
import org.freedesktop.gstreamer.lowlevel.GstTypes;
import org.freedesktop.gstreamer.lowlevel.GType;
import org.freedesktop.gstreamer.lowlevel.GValueAPI;
import static org.freedesktop.gstreamer.lowlevel.GstIteratorAPI.GSTITERATOR_API;
/**
* Utility class for working with gstiterator.
*/
class GstIterator {
static <T extends NativeObject> List<T> asList(GstIteratorPtr iter, Class<T> type) {
final GType gtype = GstTypes.typeFor(type);
final GValueAPI.GValue gValue = new GValueAPI.GValue(gtype);
List<T> list = new ArrayList<>();
while (GSTITERATOR_API.gst_iterator_next(iter, gValue) == 1) {
list.add((T) gValue.getValue());
}
gValue.reset();
GSTITERATOR_API.gst_iterator_free(iter);
return list;
}
}
| lgpl-3.0 |
Spoutcraft/SpoutcraftPlugin | src/main/java/org/getspout/spoutapi/gui/Texture.java | 2715 | /*
* This file is part of SpoutcraftPlugin.
*
* Copyright (c) 2011 SpoutcraftDev <http://spoutcraft.org//>
* SpoutcraftPlugin is licensed under the GNU Lesser General Public License.
*
* SpoutcraftPlugin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SpoutcraftPlugin 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, see <http://www.gnu.org/licenses/>.
*/
package org.getspout.spoutapi.gui;
/**
* This allow an image to be downloaded and shown to the user.
* <p/>
* Images must be in either png or jpg format. You may pre-cache images using
* the FileManager, so only the filename is required afterwards.
*/
public interface Texture extends Widget {
/**
* Gets the url of this texture to render
* @return url
*/
public String getUrl();
/**
* Sets the url of this texture to render
* All textures must be of png or jpg type and a size that is a factor of
* 2 (e.g 64x128). Use the alpha channel for hiding empty space.
* @param url to set this texture to
* @return texture
*/
public Texture setUrl(String url);
/**
* Gets if the texture draws the full alpha channel instead of just using a bit-mask.
* @return if it's drawing the alpha channel
*/
public boolean isDrawingAlphaChannel();
/**
* Sets if the texture should draw the full alpha channel instead of just using a bit-mask.
* @param draw to set the drawing state
* @return texture
*/
public Texture setDrawAlphaChannel(boolean draw);
/**
* Set the offset to the top of the image.
* Setting this to a anything other than -1 will draw a 1:1 slice of the
* texture rather than scaling it to fit the width and height.
* @param top the top offset
* @return texture
*/
public Texture setTop(int top);
/**
* Get the offset to the top of the image.
* @return top offset
*/
public int getTop();
/**
* Set the offset to the left of the image.
* Setting this to a anything other than -1 will draw a 1:1 slice of the
* texture rather than scaling it to fit the width and height.
* @param left the left offset
* @return texture
*/
public Texture setLeft(int left);
/**
* Get the offset to the left of the image.
* @return left offset
*/
public int getLeft();
}
| lgpl-3.0 |
messo/Minesweeper | src/main/java/hu/krivan/minesweeper/server/LobbyPhase.java | 4154 | /**
* Copyright (c) 2010 Bálint Kriván <balint@krivan.hu>. All rights reserved.
* Use of this source code is governed by license that can be
* found in the LICENSE file.
*/
package hu.krivan.minesweeper.server;
import java.io.IOException;
import java.util.ArrayList;
/**
* Ezzel kezelünk egy kliens-server kommunikációt, amikor már el van nevezve
* a felhasználónk, tehát játékra kész, de még nem kezdett játszani
*
* @author balint
*/
public class LobbyPhase extends Thread {
private Client client;
private Server server;
private boolean shouldRun = true;
public LobbyPhase(Client client, Server server) {
super("LobbyPhase-" + client.getNickname());
this.client = client;
this.server = server;
}
@Override
public void run() {
try {
String s, cmd, arg;
String[] tokens;
// Most kezeljük a GAME előtti parancsokat.
while (shouldRun) {
s = client.readMessage();
if (s == null) {
//megszakadt a kapcsolat
server.kick(client);
break;
}
tokens = s.split(" ");
if (tokens.length == 0) {
continue;
}
cmd = tokens[0];
if (client.playRequest) { // ha játékra kértük fel a klienst, akkor csak ACCEPT, vagy REFUSE
if (cmd.equals("ACCEPT")) {
client.playRequest = false;
onAcceptedToPlay();
break;
} else if (cmd.equals("REFUSE")) {
client.playRequest = false;
onRefusedToPlay();
}
} else {
if (cmd.equals("PLAYERLIST")) {
sendPlayerList();
} else if (cmd.equals("PLAY")) {
arg = tokens[1];
server.onClientWantsToPlayWith(client, Integer.parseInt(arg));
synchronized (client.challengeObserver) {
// megállítjuk a szálat, ameddig a felkért user el nem fogadja/utasítja a felkérést.
client.challengeObserver.wait();
}
// ha meghozta a döntést, és elfogadta, akkor kilépünk a szálból, hiszen kezdődik a játék
if (client.challengeObserver.accepted) {
break;
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
} catch (InterruptedException ex) {
ex.printStackTrace(System.err);
}
}
private void sendPlayerList() {
StringBuilder sb = new StringBuilder();
ArrayList<Client> room = server.getLobby();
sb.append("+PLAYERLIST\r\n");
sb.append(room.size());
sb.append("\r\n");
for (Client c : room) {
sb.append(c.getNickname());
sb.append("\r\n");
}
// FIXME kell ez ide?
sb.delete(sb.length() - 2, sb.length());
client.sendMessage(sb.toString());
}
private void onRefusedToPlay() {
Client opponent = client.getOpponent();
opponent.sendMessage("REFUSED");
opponent.challengeObserver.accepted = false;
// értesítjük a ClientConnection szálat, hogy kész vagyunk a challenge-el
synchronized (opponent.challengeObserver) {
opponent.challengeObserver.notify();
}
}
private void onAcceptedToPlay() {
Client opponent = client.getOpponent();
opponent.sendMessage("ACCEPTED");
opponent.challengeObserver.accepted = true;
// értesítjük a ClientConnection szálat, hogy kész vagyunk a challenge-el
synchronized (opponent.challengeObserver) {
opponent.challengeObserver.notify();
}
server.startGame(client, opponent);
}
}
| lgpl-3.0 |
ninazeina/SXP | src/main/java/model/entity/Item.java | 2557 | package model.entity;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.annotations.UuidGenerator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@XmlRootElement
@Entity
public class Item {
@XmlElement(name="id")
@UuidGenerator(name="uuid")
@Id
@GeneratedValue(generator="uuid")
private String id;
@XmlElement(name="title")
@NotNull
@Size(min = 3, max = 255)
private String title;
@XmlElement(name="description")
@NotNull
@Size(min = 3, max = 2000)
private String description;
@XmlElement(name="createdAt")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
private Date createdAt;
@XmlElement(name="pbkey")
@NotNull
@Lob
@JsonSerialize(using=controller.tools.BigIntegerSerializer.class)
@JsonDeserialize(using=controller.tools.BigIntegerDeserializer.class)
@JsonFormat(shape=JsonFormat.Shape.STRING)
private BigInteger pbkey;
@XmlElement(name="username")
@NotNull
@Size(min = 2, max = 255)
private String username;
@XmlElement(name="username")
@NotNull
private String userid;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setCreatedAt(Date date) {
createdAt = date;
}
public Date getCreatedAt() {
return createdAt;
}
public BigInteger getPbkey() {
return pbkey;
}
public void setPbkey(BigInteger pbkey) {
this.pbkey = pbkey;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
| lgpl-3.0 |
uniba-dsg/bpp | src/main/generated/org/ws_i/testing/_2009/_03/report/RunConfigType.java | 3899 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// 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: 2012.11.20 at 02:25:55 PM CET
//
package org.ws_i.testing._2009._03.report;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for RunConfigType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RunConfigType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="xsltEngine" type="{http://www.ws-i.org/testing/2009/03/report/}XsltEngineType" minOccurs="0"/>
* <element name="docSource" type="{http://www.ws-i.org/testing/2009/03/report/}DocSourceType" minOccurs="0"/>
* <element name="comments" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RunConfigType", propOrder = {
"timestamp",
"xsltEngine",
"docSource",
"comments"
})
public class RunConfigType {
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar timestamp;
protected XsltEngineType xsltEngine;
protected DocSourceType docSource;
protected String comments;
/**
* Gets the value of the timestamp property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTimestamp() {
return timestamp;
}
/**
* Sets the value of the timestamp property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTimestamp(XMLGregorianCalendar value) {
this.timestamp = value;
}
/**
* Gets the value of the xsltEngine property.
*
* @return
* possible object is
* {@link XsltEngineType }
*
*/
public XsltEngineType getXsltEngine() {
return xsltEngine;
}
/**
* Sets the value of the xsltEngine property.
*
* @param value
* allowed object is
* {@link XsltEngineType }
*
*/
public void setXsltEngine(XsltEngineType value) {
this.xsltEngine = value;
}
/**
* Gets the value of the docSource property.
*
* @return
* possible object is
* {@link DocSourceType }
*
*/
public DocSourceType getDocSource() {
return docSource;
}
/**
* Sets the value of the docSource property.
*
* @param value
* allowed object is
* {@link DocSourceType }
*
*/
public void setDocSource(DocSourceType value) {
this.docSource = value;
}
/**
* Gets the value of the comments property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getComments() {
return comments;
}
/**
* Sets the value of the comments property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setComments(String value) {
this.comments = value;
}
}
| lgpl-3.0 |
SafetyCulture/DroidText | app/src/main/java/bouncycastle/repack/org/bouncycastle/cert/X509v3CertificateBuilder.java | 4684 | package repack.org.bouncycastle.cert;
import repack.org.bouncycastle.asn1.ASN1Encodable;
import repack.org.bouncycastle.asn1.ASN1ObjectIdentifier;
import repack.org.bouncycastle.asn1.DERInteger;
import repack.org.bouncycastle.asn1.x500.X500Name;
import repack.org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import repack.org.bouncycastle.asn1.x509.Time;
import repack.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator;
import repack.org.bouncycastle.asn1.x509.X509CertificateStructure;
import repack.org.bouncycastle.asn1.x509.X509Extension;
import repack.org.bouncycastle.asn1.x509.X509ExtensionsGenerator;
import repack.org.bouncycastle.operator.ContentSigner;
import java.math.BigInteger;
import java.util.Date;
/**
* class to produce an X.509 Version 3 certificate.
*/
public class X509v3CertificateBuilder
{
private V3TBSCertificateGenerator tbsGen;
private X509ExtensionsGenerator extGenerator;
/**
* Create a builder for a version 3 certificate.
*
* @param issuer the certificate issuer
* @param serial the certificate serial number
* @param notBefore the date before which the certificate is not valid
* @param notAfter the date after which the certificate is not valid
* @param subject the certificate subject
* @param publicKeyInfo the info structure for the public key to be associated with this certificate.
*/
public X509v3CertificateBuilder(X500Name issuer, BigInteger serial, Date notBefore, Date notAfter, X500Name subject, SubjectPublicKeyInfo publicKeyInfo)
{
tbsGen = new V3TBSCertificateGenerator();
tbsGen.setSerialNumber(new DERInteger(serial));
tbsGen.setIssuer(issuer);
tbsGen.setStartDate(new Time(notBefore));
tbsGen.setEndDate(new Time(notAfter));
tbsGen.setSubject(subject);
tbsGen.setSubjectPublicKeyInfo(publicKeyInfo);
extGenerator = new X509ExtensionsGenerator();
}
/**
* Set the subjectUniqueID - note: it is very rare that it is correct to do this.
*
* @param uniqueID a boolean array representing the bits making up the subjectUniqueID.
* @return this builder object.
*/
public X509v3CertificateBuilder setSubjectUniqueID(boolean[] uniqueID)
{
tbsGen.setSubjectUniqueID(CertUtils.booleanToBitString(uniqueID));
return this;
}
/**
* Set the issuerUniqueID - note: it is very rare that it is correct to do this.
*
* @param uniqueID a boolean array representing the bits making up the issuerUniqueID.
* @return this builder object.
*/
public X509v3CertificateBuilder setIssuerUniqueID(boolean[] uniqueID)
{
tbsGen.setIssuerUniqueID(CertUtils.booleanToBitString(uniqueID));
return this;
}
/**
* Add a given extension field for the standard extensions tag (tag 3)
*
* @param oid the OID defining the extension type.
* @param isCritical true if the extension is critical, false otherwise.
* @param value the ASN.1 structure that forms the extension's value.
* @return this builder object.
*/
public X509v3CertificateBuilder addExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
ASN1Encodable value)
{
extGenerator.addExtension(oid, isCritical, value);
return this;
}
/**
* Add a given extension field for the standard extensions tag (tag 3)
* copying the extension value from another certificate.
*
* @param oid the OID defining the extension type.
* @param isCritical true if the copied extension is to be marked as critical, false otherwise.
* @param certHolder the holder for the certificate that the extension is to be copied from.
* @return this builder object.
*/
public X509v3CertificateBuilder copyAndAddExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
X509CertificateHolder certHolder)
{
X509CertificateStructure cert = certHolder.toASN1Structure();
X509Extension extension = cert.getTBSCertificate().getExtensions().getExtension(oid);
if(extension == null)
{
throw new NullPointerException("extension " + oid + " not present");
}
extGenerator.addExtension(oid, isCritical, extension.getValue().getOctets());
return this;
}
/**
* Generate an X.509 certificate, based on the current issuer and subject
* using the passed in signer.
*
* @param signer the content signer to be used to generate the signature validating the certificate.
* @return a holder containing the resulting signed certificate.
*/
public X509CertificateHolder build(
ContentSigner signer)
{
tbsGen.setSignature(signer.getAlgorithmIdentifier());
if(!extGenerator.isEmpty())
{
tbsGen.setExtensions(extGenerator.generate());
}
return CertUtils.generateFullCert(signer, tbsGen.generateTBSCertificate());
}
} | lgpl-3.0 |
xXKeyleXx/MyPet | modules/Plugin/src/main/java/de/Keyle/MyPet/entity/types/MyGuardian.java | 2428 | /*
* This file is part of MyPet
*
* Copyright © 2011-2019 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.entity.types;
import de.Keyle.MyPet.api.entity.MyPetType;
import de.Keyle.MyPet.api.player.MyPetPlayer;
import de.Keyle.MyPet.entity.MyPet;
import de.keyle.knbt.TagByte;
import de.keyle.knbt.TagCompound;
import org.bukkit.ChatColor;
public class MyGuardian extends MyPet implements de.Keyle.MyPet.api.entity.types.MyGuardian {
protected boolean isElder = false;
public MyGuardian(MyPetPlayer petOwner) {
super(petOwner);
}
@Override
public MyPetType getPetType() {
return MyPetType.Guardian;
}
@Override
public TagCompound writeExtendedInfo() {
TagCompound info = super.writeExtendedInfo();
info.getCompoundData().put("Elder", new TagByte(isElder));
return info;
}
@Override
public void readExtendedInfo(TagCompound info) {
if (info.containsKey("Elder")) {
setElder(info.getAs("Elder", TagByte.class).getBooleanData());
}
}
public boolean isElder() {
return isElder;
}
public void setElder(boolean flag) {
this.isElder = flag;
if (status == PetState.Here) {
getEntity().ifPresent(entity -> entity.getHandle().updateVisuals());
}
}
@Override
public String toString() {
return "MyGuardian{owner=" + getOwner().getName() + ", name=" + ChatColor.stripColor(petName) + ", exp=" + experience.getExp() + "/" + experience.getRequiredExp() + ", lv=" + experience.getLevel() + ", status=" + status.name() + ", skilltree=" + (skilltree != null ? skilltree.getName() : "-") + ", worldgroup=" + worldGroup + ", elder=" + isElder() + "}";
}
} | lgpl-3.0 |
AlternativeMods/SuperPowers | src/main/java/jkmau5/superpowers/api/package-info.java | 718 | /*
* Copyright 2013 jk-5 and Lordmau5
*
* jk-5 and Lordmau5 License this file to you under the LGPL v3 License (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.gnu.org/licenses/lgpl.html
*
* 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
*/
@API(apiVersion="1.0", owner="SuperPowers", provides="SuperPowersAPI")
package jkmau5.superpowers.api;
| lgpl-3.0 |
hannoman/xxl | src/xxl/core/io/CounterDataInput.java | 4108 | /* XXL: The eXtensible and fleXible Library for data processing
Copyright (C) 2000-2011 Prof. Dr. Bernhard Seeger
Head of the Database Research Group
Department of Mathematics and Computer Science
University of Marburg
Germany
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; If not, see <http://www.gnu.org/licenses/>.
http://code.google.com/p/xxl/
*/
package xxl.core.io;
import java.io.DataInput;
import java.io.IOException;
/**
* Wraps a DataInput and counts the number of bytes which
* are read. The methods that return a String are not supported.
*/
public class CounterDataInput implements DataInput {
/**
* Number of bytes read so far.
*/
protected int size;
/**
* The DataInput which is wrapped.
*/
protected DataInput di;
/**
* Constructs a new DataInput which counts the bytes
* which are read from a wrapped DataInput object.
* @param di DataInput which is wrapped.
*/
public CounterDataInput(DataInput di) {
this.di = di;
size = 0;
}
/**
* Returns the number of bytes read so far.
* @return The number of bytes read so far.
*/
public int getCounter() {
return size;
}
/**
* @see java.io.DataInput#readFully(byte[])
*/
public void readFully(byte[] b) throws IOException {
size += b.length;
di.readFully(b);
}
/**
* @see java.io.DataInput#readFully(byte[], int, int)
*/
public void readFully(byte[] b, int off, int len) throws IOException {
size += len;
di.readFully(b, off, len);
}
/**
* @see java.io.DataInput#skipBytes(int)
*/
public int skipBytes(int n) throws IOException {
size += n;
return di.skipBytes(n);
}
/**
* @see java.io.DataInput#readBoolean()
*/
public boolean readBoolean() throws IOException {
size++;
return di.readBoolean();
}
/**
* @see java.io.DataInput#readByte()
*/
public byte readByte() throws IOException {
size++;
return di.readByte();
}
/**
* @see java.io.DataInput#readUnsignedByte()
*/
public int readUnsignedByte() throws IOException {
size++;
return di.readUnsignedByte();
}
/**
* @see java.io.DataInput#readShort()
*/
public short readShort() throws IOException {
size += 2;
return di.readShort();
}
/**
* @see java.io.DataInput#readUnsignedShort()
*/
public int readUnsignedShort() throws IOException {
size += 2;
return di.readUnsignedShort();
}
/**
* @see java.io.DataInput#readChar()
*/
public char readChar() throws IOException {
size += 2;
return di.readChar();
}
/**
* @see java.io.DataInput#readInt()
*/
public int readInt() throws IOException {
size += 4;
return di.readInt();
}
/**
* @see java.io.DataInput#readLong()
*/
public long readLong() throws IOException {
size += 8;
return di.readLong();
}
/**
* @see java.io.DataInput#readFloat()
*/
public float readFloat() throws IOException {
size += 4;
return di.readFloat();
}
/**
* @see java.io.DataInput#readDouble()
*/
public double readDouble() throws IOException {
size += 8;
return di.readDouble();
}
/**
* This method is not supported by the counter.
* @return throws an UnsupportedOperationException.
* @throws IOException
*/
public String readLine() throws IOException {
throw new UnsupportedOperationException();
}
/**
* This method is not supported by the counter.
* @return throws an UnsupportedOperationException.
* @throws IOException
*/
public String readUTF() throws IOException {
throw new UnsupportedOperationException();
}
}
| lgpl-3.0 |
liflab/sealtest | Source/Core/src/ca/uqac/lif/ecp/ltl/NaryOperator.java | 5332 | /*
Log trace triaging and etc.
Copyright (C) 2016 Sylvain Hallé
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU 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, see <http://www.gnu.org/licenses/>.
*/
package ca.uqac.lif.ecp.ltl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import ca.uqac.lif.ecp.Event;
import ca.uqac.lif.structures.MathList;
/**
* Basic functionalities associated to a <i>n</i>-ary logical operator
* @author Sylvain Hallé
*
* @param <T> The event type
*/
public abstract class NaryOperator<T extends Event> extends Operator<T>
{
protected List<Operator<T>> m_operands;
protected final String m_symbol;
public NaryOperator(String symbol)
{
super();
m_symbol = symbol;
m_operands = new ArrayList<Operator<T>>();
}
@SuppressWarnings("unchecked")
public NaryOperator(String symbol, Object ... ops)
{
super();
m_symbol = symbol;
m_operands = new ArrayList<Operator<T>>();
for (Object o : ops)
{
if (o instanceof Operator<?>)
{
m_operands.add((Operator<T>) o);
}
}
}
@Override
public void addOperand(Operator<T> op)
{
m_operands.add(op);
}
/**
* Computes the hash code of this n-ary operator, starting from
* an initial value
* @param start_value The initial value
* @return The hash code
*/
protected int hashCode(int start_value)
{
for (Operator<T> op : m_operands)
{
if (!op.isDeleted())
{
start_value += op.hashCode();
}
}
return start_value;
}
/**
* Checks whether the children of this operator are equal to that of
* another n-ary operator. This check takes into account the fact that
* children that are marked as deleted in either operator should be
* skipped.
* @param o The other operator
* @return true if their children are equal, false otherwise
*/
protected boolean childrenEquals(NaryOperator<T> o)
{
int i = 0, j = 0;
if (m_value != o.m_value)
{
return false;
}
while (i < m_operands.size() && j < o.m_operands.size())
{
Operator<T> op1 = m_operands.get(i);
Operator<T> op2 = o.m_operands.get(j);
if (op1.isDeleted())
{
i++;
continue;
}
if (op2.isDeleted())
{
j++;
continue;
}
if (!op1.equals(op2))
{
return false;
}
i++;
j++;
}
for (int n = i; n < m_operands.size(); n++)
{
Operator<T> op = m_operands.get(n);
if (!op.isDeleted())
{
return false;
}
}
for (int n = j; n < o.m_operands.size(); n++)
{
Operator<T> op = o.m_operands.get(n);
if (!op.isDeleted())
{
return false;
}
}
return true;
}
/**
* Copies the internal content of this operator into a new instance
* @param o The new instance
* @param with_tree Set to <code>true</code> to also copy data related
* to the operator's evaluation tree
*/
protected void copyInto(NaryOperator<T> o, boolean with_tree)
{
super.copyInto(o, with_tree);
for (Operator<T> op : m_operands)
{
o.m_operands.add(op.copy(with_tree));
}
}
@Override
public String toString()
{
StringBuilder out = new StringBuilder();
for (int i = 0; i < m_operands.size(); i++)
{
if (i > 0)
{
out.append(" ").append(m_symbol).append(" ");
}
out.append("(").append(m_operands.get(i)).append(")");
}
return out.toString();
}
@Override
public void acceptPrefix(HologramVisitor<T> visitor, boolean in_tree)
{
visitor.visit(this);
for (Operator<T> op : m_operands)
{
op.acceptPrefix(visitor, in_tree);
}
visitor.backtrack();
}
@Override
public void acceptPostfix(HologramVisitor<T> visitor, boolean in_tree)
{
for (Operator<T> op : m_operands)
{
op.acceptPostfix(visitor, in_tree);
}
visitor.visit(this);
visitor.backtrack();
}
@Override
public String getRootSymbol()
{
return m_symbol;
}
@Override
public int size(boolean with_tree)
{
int size = 1;
for (Operator<T> op : m_operands)
{
if (!op.isDeleted())
{
size += op.size(with_tree);
}
}
return size;
}
/**
* Gets the number of children in the expression
* @return The number of children
*/
public int childrenCount()
{
return m_operands.size();
}
@Override
public List<Operator<T>> getTreeChildren()
{
MathList<Operator<T>> list = new MathList<Operator<T>>();
list.addAll(m_operands);
return list;
}
@Override
public void delete()
{
m_deleted = true;
for (Operator<T> op : m_operands)
{
op.delete();
}
}
@Override
public void clear()
{
super.clear();
for (Operator<T> op : m_operands)
{
op.clear();
}
}
@Override
public void clean()
{
Iterator<Operator<T>> it = m_operands.iterator();
while (it.hasNext())
{
Operator<T> o = it.next();
if (o.isDeleted())
{
it.remove();
}
o.clean();
}
}
}
| lgpl-3.0 |
Mindtoeye/Hoop | src/org/fife/ui/rsyntaxtextarea/RSyntaxTextAreaDefaultInputMap.java | 3513 | /*
* 10/27/2004
*
* RSyntaxTextAreaDefaultInputMap.java - The default input map for
* RSyntaxTextAreas.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rsyntaxtextarea;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.KeyStroke;
import org.fife.ui.rtextarea.RTADefaultInputMap;
/**
* The default input map for an <code>RSyntaxTextArea</code>.
* Currently, the new key bindings include:
* <ul>
* <li>Shift+Tab indents the current line or currently selected lines
* to the left.
* </ul>
*
* @author Robert Futrell
* @version 1.0
*/
public class RSyntaxTextAreaDefaultInputMap extends RTADefaultInputMap {
/**
* Constructs the default input map for an <code>RSyntaxTextArea</code>.
*/
public RSyntaxTextAreaDefaultInputMap() {
int defaultMod = getDefaultModifier();
//int ctrl = InputEvent.CTRL_MASK;
int shift = InputEvent.SHIFT_MASK;
//int alt = InputEvent.ALT_MASK;
put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, shift), RSyntaxTextAreaEditorKit.rstaDecreaseIndentAction);
put(KeyStroke.getKeyStroke('}'), RSyntaxTextAreaEditorKit.rstaCloseCurlyBraceAction);
put(KeyStroke.getKeyStroke('/'), RSyntaxTextAreaEditorKit.rstaCloseMarkupTagAction);
int os = RSyntaxUtilities.getOS();
if (os==RSyntaxUtilities.OS_WINDOWS || os==RSyntaxUtilities.OS_MAC_OSX) {
// *nix causes trouble with CloseMarkupTagAction and ToggleCommentAction.
// It triggers both KEY_PRESSED ctrl+'/' and KEY_TYPED '/' events when the
// user presses ctrl+'/', but Windows and OS X do not. If we try to "move"
// the KEY_TYPED event for '/' to KEY_PRESSED, it'll work for Linux boxes
// with QWERTY keyboard layouts, but non-QUERTY users won't be able to type
// a '/' character at all then (!). Rather than try to hack together a
// solution by trying to detect the IM locale and do different things for
// different OSes & keyboard layouts, we do the simplest thing and
// (unfortunately) don't have a ToggleCommentAction for *nix out-of-the-box.
// Applications can add one easily enough if they want one.
put(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, defaultMod), RSyntaxTextAreaEditorKit.rstaToggleCommentAction);
}
put(KeyStroke.getKeyStroke(KeyEvent.VK_OPEN_BRACKET, defaultMod), RSyntaxTextAreaEditorKit.rstaGoToMatchingBracketAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseFoldAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandFoldAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DIVIDE, defaultMod), RSyntaxTextAreaEditorKit.rstaCollapseAllFoldsAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_MULTIPLY, defaultMod), RSyntaxTextAreaEditorKit.rstaExpandAllFoldsAction);
// FIXME: The keystroke associated with this action should be dynamic and
// configurable and synchronized with the "trigger" defined in RSyntaxTextArea's
// CodeTemplateManager.
// NOTE: no modifiers => mapped to keyTyped. If we had "0" as a second
// second parameter, we'd get the template action (keyPressed) AND the
// default space action (keyTyped).
//put(KeyStroke.getKeyStroke(' '), RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction);
put(CodeTemplateManager.TEMPLATE_KEYSTROKE, RSyntaxTextAreaEditorKit.rstaPossiblyInsertTemplateAction);
}
} | lgpl-3.0 |
MichaelRoeder/Grph | src/main/java/grph/algo/labelling/ContiguousLabelling.java | 2063 | /*
* (C) Copyright 2009-2013 CNRS.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
Luc Hogie (CNRS, I3S laboratory, University of Nice-Sophia Antipolis)
Aurelien Lancin (Coati research team, Inria)
Christian Glacet (LaBRi, Bordeaux)
David Coudert (Coati research team, Inria)
Fabien Crequis (Coati research team, Inria)
Grégory Morel (Coati research team, Inria)
Issam Tahiri (Coati research team, Inria)
Julien Fighiera (Aoste research team, Inria)
Laurent Viennot (Gang research-team, Inria)
Michel Syska (I3S, University of Nice-Sophia Antipolis)
Nathann Cohen (LRI, Saclay)
*/
package grph.algo.labelling;
import com.carrotsearch.hppc.IntIntMap;
import com.carrotsearch.hppc.IntIntOpenHashMap;
/**
* Contiguous vertex/edge labelling.
* @author lhogie
*
*/
public class ContiguousLabelling extends Relabelling
{
private IntIntMap vertex_label = new IntIntOpenHashMap();
private IntIntMap edge_label = new IntIntOpenHashMap();
@Override
public int getVertexLabel(int v)
{
// if this vertex has already been labelled
if (vertex_label.containsKey(v))
{
return vertex_label.get(v);
}
else
{
// computes the new label
int label = vertex_label.size();
// assign it
vertex_label.put(v, label);
return label;
}
}
@Override
public int getEdgeLabel(int e)
{
if (edge_label.containsKey(e))
{
return edge_label.get(e);
}
else
{
int label = edge_label.size();
edge_label.put(e, label);
return label;
}
}
}
| lgpl-3.0 |
Grasia/phatsim | phat-audio/src/main/java/phat/audio/PHATAudioRenderer.java | 3703 | /*
* Copyright (C) 2014 Pablo Campillo-Sanchez <pabcampi@ucm.es>
*
* This software has been developed as part of the
* SociAAL project directed by Jorge J. Gomez Sanz
* (http://grasia.fdi.ucm.es/sociaal)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package phat.audio;
import com.aurellem.capture.audio.MultiListener;
import com.aurellem.capture.audio.SoundProcessor;
import com.jme3.audio.AudioData;
import com.jme3.audio.AudioNode;
import com.jme3.audio.AudioParam;
import com.jme3.audio.AudioRenderer;
import com.jme3.audio.AudioSource;
import com.jme3.audio.Environment;
import com.jme3.audio.Filter;
import com.jme3.audio.Listener;
import com.jme3.audio.ListenerParam;
/**
*
* @author pablo
*/
public class PHATAudioRenderer implements AudioRenderer, MultiListener {
AudioRenderer audioRenderer;
public PHATAudioRenderer(AudioRenderer audioRenderer) {
this.audioRenderer = audioRenderer;
}
@Override
public void setListener(Listener ll) {
audioRenderer.setListener(ll);
}
@Override
public void setEnvironment(Environment e) {
audioRenderer.setEnvironment(e);
}
@Override
public void playSourceInstance(AudioSource as) {
changeAudio(as);
audioRenderer.playSourceInstance(as);
}
@Override
public void playSource(AudioSource as) {
changeAudio(as);
audioRenderer.playSource(as);
}
private void changeAudio(AudioSource as) {
if(as instanceof AudioNode) {
AudioNode an = (AudioNode) as;
an.setRefDistance(0.1f);
an.setMaxDistance(1000f);
}
audioRenderer.playSourceInstance(as);
}
@Override
public void pauseSource(AudioSource as) {
audioRenderer.pauseSource(as);
}
@Override
public void stopSource(AudioSource as) {
audioRenderer.stopSource(as);
}
@Override
public void updateSourceParam(AudioSource as, AudioParam ap) {
audioRenderer.updateSourceParam(as, ap);
}
@Override
public void updateListenerParam(Listener ll, ListenerParam lp) {
audioRenderer.updateListenerParam(ll, lp);
}
@Override
public void deleteFilter(Filter filter) {
audioRenderer.deleteFilter(filter);
}
@Override
public void deleteAudioData(AudioData ad) {
audioRenderer.deleteAudioData(ad);
}
@Override
public void initialize() {
audioRenderer.initialize();
}
@Override
public void update(float f) {
audioRenderer.update(f);
}
@Override
public void cleanup() {
audioRenderer.cleanup();
}
@Override
public void addListener(Listener ll) {
((MultiListener)audioRenderer).addListener(ll);
}
@Override
public void registerSoundProcessor(Listener ll, SoundProcessor sp) {
((MultiListener)audioRenderer).registerSoundProcessor(ll, sp);
}
@Override
public void registerSoundProcessor(SoundProcessor sp) {
((MultiListener)audioRenderer).registerSoundProcessor(sp);
}
}
| lgpl-3.0 |
christopher-worley/common-app | core-commonapp-model-api/src/main/java/core/data/model/geo/GeoType.java | 1531 | /**
* Copyright 2009 Core Information Solutions LLC
*
* This file is part of Core CommonApp Framework.
*
* Core CommonApp Framework is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Core CommonApp Framework is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with Core CommonApp Framework. If not, see <http://www.gnu.org/licenses/>.
*
*/
package core.data.model.geo;
import core.data.model.DataObject;
import core.data.model.Keyable;
public interface GeoType extends DataObject, Keyable
{
/**
* Getter for description
*
* @return the description
*/
public abstract String getDescription();
/**
* Getter for geoTypeId
*
* @return the geoTypeId
*/
public abstract Integer getGeoTypeId();
/**
* Setter for description
*
* @param description the description to set
*/
public abstract void setDescription(String description);
/**
* Setter for geoTypeId
*
* @param geoTypeId the geoTypeId to set
*/
public abstract void setGeoTypeId(Integer geoTypeId);
} | lgpl-3.0 |
teryk/sonarqube | server/sonar-server/src/test/java/org/sonar/server/permission/PermissionFinderTest.java | 13376 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sonar.core.permission.*;
import org.sonar.core.resource.ResourceDao;
import org.sonar.core.resource.ResourceDto;
import org.sonar.core.resource.ResourceQuery;
import org.sonar.server.exceptions.NotFoundException;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PermissionFinderTest {
@Mock
PermissionDao permissionDao;
@Mock
ResourceDao resourceDao;
@Mock
PermissionTemplateDao permissionTemplateDao;
PermissionFinder finder;
@Before
public void setUp() throws Exception {
when(resourceDao.getResource(any(ResourceQuery.class))).thenReturn(new ResourceDto().setId(100L).setName("org.sample.Sample"));
finder = new PermissionFinder(permissionDao, resourceDao, permissionTemplateDao);
}
@Test
public void find_users() throws Exception {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(
newArrayList(new UserWithPermissionDto().setName("user1").setPermission("user"))
);
UserWithPermissionQueryResult result = finder.findUsersWithPermission(PermissionQuery.builder().permission("user").build());
assertThat(result.users()).hasSize(1);
assertThat(result.hasMoreResults()).isFalse();
}
@Test
public void fail_to_find_users_when_component_not_found() throws Exception {
when(resourceDao.getResource(any(ResourceQuery.class))).thenReturn(null);
try {
finder.findUsersWithPermission(PermissionQuery.builder().permission("user").component("Unknown").build());
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(NotFoundException.class).hasMessage("Component 'Unknown' does not exist");
}
}
@Test
public void find_users_with_paging() throws Exception {
finder.findUsersWithPermission(PermissionQuery.builder().permission("user").pageIndex(3).pageSize(10).build());
ArgumentCaptor<Integer> argumentOffset = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> argumentLimit = ArgumentCaptor.forClass(Integer.class);
verify(permissionDao).selectUsers(any(PermissionQuery.class), anyLong(), argumentOffset.capture(), argumentLimit.capture());
assertThat(argumentOffset.getValue()).isEqualTo(20);
assertThat(argumentLimit.getValue()).isEqualTo(11);
}
@Test
public void find_users_with_paging_having_more_results() throws Exception {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new UserWithPermissionDto().setName("user1").setPermission("user"),
new UserWithPermissionDto().setName("user2").setPermission("user"),
new UserWithPermissionDto().setName("user3").setPermission("user"))
);
UserWithPermissionQueryResult result = finder.findUsersWithPermission(PermissionQuery.builder().permission("user").pageIndex(1).pageSize(2).build());
ArgumentCaptor<Integer> argumentOffset = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> argumentLimit = ArgumentCaptor.forClass(Integer.class);
verify(permissionDao).selectUsers(any(PermissionQuery.class), anyLong(), argumentOffset.capture(), argumentLimit.capture());
assertThat(argumentOffset.getValue()).isEqualTo(0);
assertThat(argumentLimit.getValue()).isEqualTo(3);
assertThat(result.hasMoreResults()).isTrue();
}
@Test
public void find_users_with_paging_having_no_more_results() throws Exception {
when(permissionDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(newArrayList(
new UserWithPermissionDto().setName("user1").setPermission("user"),
new UserWithPermissionDto().setName("user2").setPermission("user"),
new UserWithPermissionDto().setName("user4").setPermission("user"),
new UserWithPermissionDto().setName("user3").setPermission("user"))
);
UserWithPermissionQueryResult result = finder.findUsersWithPermission(PermissionQuery.builder().permission("user").pageIndex(1).pageSize(10).build());
ArgumentCaptor<Integer> argumentOffset = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> argumentLimit = ArgumentCaptor.forClass(Integer.class);
verify(permissionDao).selectUsers(any(PermissionQuery.class), anyLong(), argumentOffset.capture(), argumentLimit.capture());
assertThat(argumentOffset.getValue()).isEqualTo(0);
assertThat(argumentLimit.getValue()).isEqualTo(11);
assertThat(result.hasMoreResults()).isFalse();
}
@Test
public void find_groups() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission(
PermissionQuery.builder().permission("user").membership(PermissionQuery.IN).build());
assertThat(result.groups()).hasSize(1);
assertThat(result.hasMoreResults()).isFalse();
}
@Test
public void find_groups_should_be_paginated() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(newArrayList(
new GroupWithPermissionDto().setName("Anyone").setPermission("user"),
new GroupWithPermissionDto().setName("Admin").setPermission("user"),
new GroupWithPermissionDto().setName("Users").setPermission(null),
new GroupWithPermissionDto().setName("Reviewers").setPermission(null),
new GroupWithPermissionDto().setName("Other").setPermission(null)
));
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission(
PermissionQuery.builder()
.permission("user")
.pageSize(2)
.pageIndex(2)
.build());
assertThat(result.hasMoreResults()).isTrue();
List<GroupWithPermission> groups = result.groups();
assertThat(groups).hasSize(2);
assertThat(groups.get(0).name()).isEqualTo("Users");
assertThat(groups.get(1).name()).isEqualTo("Reviewers");
assertThat(finder.findGroupsWithPermission(
PermissionQuery.builder()
.permission("user")
.pageSize(2)
.pageIndex(3)
.build()).hasMoreResults()).isFalse();
}
@Test
public void find_groups_should_filter_membership() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(newArrayList(
new GroupWithPermissionDto().setName("Anyone").setPermission("user"),
new GroupWithPermissionDto().setName("Admin").setPermission("user"),
new GroupWithPermissionDto().setName("Users").setPermission(null),
new GroupWithPermissionDto().setName("Reviewers").setPermission(null),
new GroupWithPermissionDto().setName("Other").setPermission(null)
));
assertThat(finder.findGroupsWithPermission(
PermissionQuery.builder().permission("user").membership(PermissionQuery.IN).build()).groups()).hasSize(2);
assertThat(finder.findGroupsWithPermission(
PermissionQuery.builder().permission("user").membership(PermissionQuery.OUT).build()).groups()).hasSize(3);
assertThat(finder.findGroupsWithPermission(
PermissionQuery.builder().permission("user").membership(PermissionQuery.ANY).build()).groups()).hasSize(5);
}
@Test
public void find_groups_with_added_anyone_group() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission( PermissionQuery.builder().permission("user")
.pageIndex(1).membership(PermissionQuery.ANY).build());
assertThat(result.groups()).hasSize(2);
GroupWithPermission first = result.groups().get(0);
assertThat(first.name()).isEqualTo("Anyone");
assertThat(first.hasPermission()).isFalse();
}
@Test
public void find_groups_without_adding_anyone_group_when_search_text_do_not_matched() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission(PermissionQuery.builder().permission("user").search("other")
.pageIndex(1).membership(PermissionQuery.ANY).build());
// Anyone group should not be added
assertThat(result.groups()).hasSize(1);
}
@Test
public void find_groups_with_added_anyone_group_when_search_text_matched() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("MyAnyGroup").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission(PermissionQuery.builder().permission("user").search("any")
.pageIndex(1).membership(PermissionQuery.ANY).build());
assertThat(result.groups()).hasSize(2);
}
@Test
public void find_groups_without_adding_anyone_group_when_out_membership_selected() throws Exception {
when(permissionDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermission( PermissionQuery.builder().permission("user")
.pageIndex(1).membership(PermissionQuery.OUT).build());
// Anyone group should not be added
assertThat(result.groups()).hasSize(1);
}
@Test
public void find_users_from_permission_template() throws Exception {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
when(permissionTemplateDao.selectUsers(any(PermissionQuery.class), anyLong(), anyInt(), anyInt())).thenReturn(
newArrayList(new UserWithPermissionDto().setName("user1").setPermission("user"))
);
UserWithPermissionQueryResult result = finder.findUsersWithPermissionTemplate(PermissionQuery.builder().permission("user").template("my_template").build());
assertThat(result.users()).hasSize(1);
assertThat(result.hasMoreResults()).isFalse();
}
@Test
public void fail_to_find_users_from_permission_template_when_template_not_found() throws Exception {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(null);
try {
finder.findUsersWithPermissionTemplate(PermissionQuery.builder().permission("user").template("Unknown").build());
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(NotFoundException.class).hasMessage("Template 'Unknown' does not exist");
}
}
@Test
public void find_groups_from_permission_template() throws Exception {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(new PermissionTemplateDto().setId(1L).setKee("my_template"));
when(permissionTemplateDao.selectGroups(any(PermissionQuery.class), anyLong())).thenReturn(
newArrayList(new GroupWithPermissionDto().setName("users").setPermission("user"))
);
GroupWithPermissionQueryResult result = finder.findGroupsWithPermissionTemplate(
PermissionQuery.builder().permission("user").template("my_template").membership(PermissionQuery.OUT).build());
assertThat(result.groups()).hasSize(1);
assertThat(result.hasMoreResults()).isFalse();
}
@Test
public void fail_to_find_groups_from_permission_template_when_template_not_found() throws Exception {
when(permissionTemplateDao.selectTemplateByKey(anyString())).thenReturn(null);
try {
finder.findGroupsWithPermissionTemplate(PermissionQuery.builder().permission("user").template("Unknown").build());
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(NotFoundException.class).hasMessage("Template 'Unknown' does not exist");
}
}
}
| lgpl-3.0 |
DirectCodeGraveyard/Minetweak | src/main/java/net/minecraft/entity/EntityMinecartEmpty.java | 920 | package net.minecraft.entity;
import net.minecraft.world.World;
public class EntityMinecartEmpty extends EntityMinecart {
public EntityMinecartEmpty(World par1World) {
super(par1World);
}
public EntityMinecartEmpty(World par1World, double par2, double par4, double par6) {
super(par1World, par2, par4, par6);
}
public boolean func_130002_c(EntityPlayer par1EntityPlayer) {
if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer && this.riddenByEntity != par1EntityPlayer) {
return true;
} else if (this.riddenByEntity != null && this.riddenByEntity != par1EntityPlayer) {
return false;
} else {
if (!this.worldObj.isRemote) {
par1EntityPlayer.mountEntity(this);
}
return true;
}
}
public int getMinecartType() {
return 0;
}
}
| lgpl-3.0 |
TKiura/MetBroker3 | MetBroker3/src/servletwrapper/ChizuBrokerServlet.java | 1641 | package servletwrapper;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import net.agmodel.chizubroker.ChizuBrokerImpl;
import net.agmodel.chizudata.ChizuBroker;
import net.agmodel.chizudata.ChizuBrokerHTTP;
import net.agmodel.chizudata.ChizuRequest;
import net.agmodel.wrapperServlet.WrapperServlet;
public class ChizuBrokerServlet extends WrapperServlet {
protected void getBrokerReference(String configPath,String resourceserver_initial_context_factory,String resourceserver_provider_url,String resourceserver_url_pkg_prefixes, String dbDir) throws ServletException{
try{
myBroker = new ChizuBrokerImpl(configPath,resourceserver_initial_context_factory,resourceserver_provider_url,resourceserver_url_pkg_prefixes);
}catch(Exception e){
throw new ServletException(e.getMessage());
}
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
getBrokerReference(configPath,resourceserver_initial_context_factory,resourceserver_provider_url,resourceserver_url_pkg_prefixes, null);
}
protected void handlePost(
int code,
String remoteHost,
ObjectInputStream in,
ObjectOutputStream out)
throws Exception {
String sessionID = null;
switch (code) {
case (ChizuBrokerHTTP.GETREGION) :
ChizuBroker chizuBroker = (ChizuBroker) myBroker;
sessionID = (String) in.readObject();
out.writeObject(
chizuBroker.getChizu(
sessionID,
(ChizuRequest) in.readObject()));
break;
default :
super.handlePost(code,remoteHost,in,out);
} //switch
}
}
| lgpl-3.0 |
huliqing/LuoYing | ly-kernel/src/name/huliqing/luoying/object/logic/____bak20161121_FightLogic.java | 2779 | /*
* LuoYing is a program used to make 3D RPG game.
* Copyright (c) 2014-2016 Huliqing <31703299@qq.com>
*
* This file is part of LuoYing.
*
* LuoYing is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LuoYing 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 LuoYing. If not, see <http://www.gnu.org/licenses/>.
*/
//package name.huliqing.luoying.object.logic;
//
//import name.huliqing.luoying.object.action.FightAction;
//import name.huliqing.luoying.data.LogicData;
//import name.huliqing.luoying.object.Loader;
//import name.huliqing.luoying.object.actor.Actor;
//import name.huliqing.luoying.object.entity.Entity;
//import name.huliqing.luoying.object.module.ActionModule;
//
///**
// * 战斗逻辑
// * @author huliqing
// */
//public class FightLogic extends AbstractLogic {
//// private static final Logger LOG = Logger.getLogger(FightLogic.class.getName());
//
// private FightAction fightAction;
// private ActionModule actionModule;
//
// // ---- inner
//
// @Override
// public void setData(LogicData data) {
// super.setData(data);
// fightAction = (FightAction) Loader.load(data.getAsString("fightAction"));
// }
//
// @Override
// public void initialize() {
// super.initialize();
// actionModule = actor.getModuleManager().getModule(ActionModule.class);
// }
//
// @Override
// protected void doLogic(float tpf) {
// // remove20161102
//// Entity t = actorService.getTarget(actor);
//// if (t != null && !actorService.isDead(t)
//// && actorService.isEnemy(t, actor)
//// && t.getScene() != null) {
////
//// fightAction.setEnemy(t);
//// actionService.playAction(actor, fightAction);
//// }
//
// Entity target = getTarget();
//
// // 只有Actor才有属性
// if (!(target instanceof Actor)) {
// return;
// }
// if (target.getScene() == null) {
// return;
// }
//
// if (isEnemy(target)) {
// fightAction.setEnemy(target);
// actionModule.startAction(fightAction);
// }
// }
//
//}
| lgpl-3.0 |
SergiyKolesnikov/fuji | examples/MobileMedia8-fuji-compilable/base/lancs/mobilemedia/core/threads/BaseThread.java | 712 | package lancs.mobilemedia.core.threads;
import de.ovgu.cide.jakutil.*;
/**
* Base Thread class. Most commands will execute within a thread (to avoid screen
* contention and hardware interrupts).
* At the moment, there is no useful functionality beyond what Runnable already provides.
* But we may wish to add some parent features in later.
*/
public class BaseThread implements Runnable {
/**
* Constructor
*/
public BaseThread(){
System.out.println("BaseThread:: 0 Param Constructor used: Using default values");
}
/**
* Start the thread running
*/
public void run(){
System.out.println("Starting BaseThread::run()");
System.out.println("Finishing Baseathread::run()");
}
}
| lgpl-3.0 |
SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/model-management/definition-core/src/main/java/com/sirma/itt/seip/definition/rest/DefinitionRestService.java | 8866 | /*
*
*/
package com.sirma.itt.seip.definition.rest;
import static com.sirma.itt.seip.rest.utils.request.params.RequestParams.KEY_ID;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.transaction.Transactional;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.json.JSONObject;
import com.sirma.itt.seip.convert.TypeConverter;
import com.sirma.itt.seip.definition.DefinitionService;
import com.sirma.itt.seip.definition.DeletedDefinitionInfo;
import com.sirma.itt.seip.definition.MutableDefinitionService;
import com.sirma.itt.seip.domain.definition.DefinitionModel;
import com.sirma.itt.seip.domain.definition.GenericDefinition;
import com.sirma.itt.seip.json.JsonUtil;
import com.sirma.itt.seip.rest.RestUtil;
import com.sirma.itt.seip.rest.exceptions.BadRequestException;
import com.sirma.itt.seip.rest.utils.Versions;
import com.sirma.itt.seip.serialization.convert.OutputFormat;
import com.sirma.itt.seip.serialization.xstream.XStreamConvertableWrapper;
/**
* Rest service for working with definitions.
*
* @author BBonev
*/
@Transactional
@Path("/definitions")
@Produces(MediaType.APPLICATION_JSON)
public class DefinitionRestService {
@Inject
private DefinitionService definitionService;
@Inject
private MutableDefinitionService mutableDefinitionService;
@Inject
private TypeConverter typeConverter;
/**
* Retrieves {@link DefinitionModel}s for passed definition ids. The ids are passed as query parameters. Only the
* definition that are found will be returned in the result map.
*
* @param definitionIds
* the ids of the definitions, which should be retrieved
* @return map with definition ids as keys and build {@link DefinitionModelObject} for the found definitions as
* values
*/
@GET
@Consumes(Versions.V2_JSON)
@Produces(Versions.V2_JSON)
public Map<String, DefinitionModelObject> getDefinitionModels(@QueryParam(KEY_ID) List<String> definitionIds) {
if (definitionIds.isEmpty()) {
throw new BadRequestException("There are no definition ids in the request.");
}
return definitionIds.stream().map(definitionService::find).filter(Objects::nonNull).collect(
Collectors.toMap(DefinitionModel::getIdentifier, new DefinitionModelObject()::setDefinitionModel));
}
/**
* List all definitions in the system.
*
* @return the response
*/
@GET
public Response listAll() {
return RestUtil.buildDataResponse(collectSimpleDefinitionInfo(definitionService.getAllDefinitions()));
}
/**
* Gets the latest definition revision as json.
*
* @param definitionId
* the definition id
* @return the definition
*/
@GET
@Path("{definitionId}")
public Response getLastDefinition(@PathParam("definitionId") String definitionId) {
return getDefinitionAs(definitionId, null, OutputFormat.JSON);
}
/**
* Gets specific definition revision as json.
*
* @param definitionId
* the definition id
* @param revision
* the revision
* @return the definition
*/
@GET
@Path("{definitionId}/{revision}")
public Response getConcreteDefinition(@PathParam("definitionId") String definitionId,
@PathParam("revision") Long revision) {
return getDefinitionAs(definitionId, revision, OutputFormat.JSON);
}
/**
* Gets the latest definition revision as XML.
*
* @param definitionId
* the definition id
* @return the definition
*/
@GET
@Path("{definitionId}")
@Produces(MediaType.APPLICATION_XML)
public Response getLastDefinitionAsXML(@PathParam("definitionId") String definitionId) {
return getDefinitionAs(definitionId, null, OutputFormat.XML);
}
/**
* Gets specific definition revision as XML.
*
* @param definitionId
* the definition id
* @param revision
* the revision
* @return the definition
*/
@GET
@Path("{definitionId}/{revision}")
@Produces(MediaType.APPLICATION_XML)
public Response getConcreteDefinitionAsXML(@PathParam("definitionId") String definitionId,
@PathParam("revision") Long revision) {
return getDefinitionAs(definitionId, revision, OutputFormat.XML);
}
/**
* Gets the definition as the specified format.
*
* @param definitionId
* the definition id
* @param revision
* the revision
* @param outputFormat
* the need output format
* @return the definition as
*/
private Response getDefinitionAs(String definitionId, Long revision, OutputFormat outputFormat) {
DefinitionModel model;
if (revision == null) {
model = definitionService.find(definitionId);
} else {
model = definitionService.getDefinition(GenericDefinition.class, definitionId, revision);
}
if (model == null) {
return RestUtil.buildErrorResponse(Status.NOT_FOUND,
"Definition with id " + definitionId + " and revision " + revision + " was not found");
}
XStreamConvertableWrapper wrapper = new XStreamConvertableWrapper(outputFormat, model);
if (outputFormat == OutputFormat.XML) {
String xml = typeConverter.convert(String.class, wrapper);
return RestUtil.buildResponse(Status.OK, xml);
}
JSONObject response = typeConverter.convert(JSONObject.class, wrapper);
return RestUtil.buildDataResponse(response);
}
/**
* Collect simple definition info.
*
* @param allDefinitions
* the all definitions
* @return the collection
*/
private static Collection<JSONObject> collectSimpleDefinitionInfo(Stream<DefinitionModel> allDefinitions) {
return allDefinitions.map(definitionModel -> {
JSONObject jsonObject = new JSONObject();
JsonUtil.addToJson(jsonObject, "definitionId", definitionModel.getIdentifier());
JsonUtil.addToJson(jsonObject, "definitionRevision", definitionModel.getRevision());
JsonUtil.addToJson(jsonObject, "type", definitionModel.getType());
return jsonObject;
}).collect(Collectors.toList());
}
/**
* Delete definition.
*
* @param definitionId
* the definition id
* @param revision
* the revision
* @return the response
*/
@DELETE
@Path("{definitionId}/{revision}")
public Response deleteDefinition(@PathParam("definitionId") String definitionId,
@PathParam("revision") Long revision) {
if (revision == null) {
return RestUtil.buildErrorResponse(Status.BAD_REQUEST, "Revision number should be specified.");
}
DeletedDefinitionInfo definitionInfo = mutableDefinitionService.deleteDefinition(GenericDefinition.class,
definitionId, revision);
return RestUtil
.buildDataResponse(Collections.singletonList(typeConverter.convert(JSONObject.class, definitionInfo)));
}
/**
* Delete all definition revisions effectively removing the definition from the application.
*
* @param definitionId
* the definition id
* @return the response
*/
@DELETE
@Path("{definitionId}/allRevisions")
public Response deleteDefinitionAllRevisions(@PathParam("definitionId") String definitionId) {
Collection<DeletedDefinitionInfo> definitionInfo = mutableDefinitionService
.deleteAllDefinitionRevisions(GenericDefinition.class, definitionId);
return RestUtil.buildDataResponse(typeConverter.convert(JSONObject.class, definitionInfo));
}
/**
* Delete all old definition revisions and leaving only the latest definition revision. Useful for definition
* cleanup.
*
* @param definitionId
* the definition id
* @return the response
*/
@DELETE
@Path("{definitionId}/oldRevisions")
public Response deleteDefinitionOldRevisions(@PathParam("definitionId") String definitionId) {
Collection<DeletedDefinitionInfo> definitionInfo = mutableDefinitionService
.deleteOldDefinitionRevisions(GenericDefinition.class, definitionId);
return RestUtil.buildDataResponse(typeConverter.convert(JSONObject.class, definitionInfo));
}
/**
* Delete all old definition revisions and leaving only the latest definition revision. Useful for definition
* cleanup.
*
* @param definitionId
* the definition id
* @return the response
*/
@DELETE
@Path("{definitionId}/lastRevision")
public Response deleteLastDefinitionRevision(@PathParam("definitionId") String definitionId) {
DeletedDefinitionInfo definitionInfo = mutableDefinitionService.deleteLastDefinition(GenericDefinition.class,
definitionId);
return RestUtil
.buildDataResponse(Collections.singletonList(typeConverter.convert(JSONObject.class, definitionInfo)));
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-db-dao/src/main/java/org/sonar/db/SQXMLMapperBuilder.java | 2216 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.db;
import java.io.InputStream;
import java.util.Map;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.session.Configuration;
/**
* Subclass of {@link XMLMapperBuilder} which fixes the fact that {@link XMLMapperBuilder} does not support loading
* Mapper interfaces which belongs to the ClassLoader of a plugin.
*/
public class SQXMLMapperBuilder extends XMLMapperBuilder {
private final Class<?> mapperType;
public SQXMLMapperBuilder(Class<?> mapperType, InputStream inputStream, Configuration configuration, Map<String, XNode> sqlFragments) {
super(inputStream, configuration, mapperType.getName(), sqlFragments);
this.mapperType = mapperType;
}
@Override
public void parse() {
if (!configuration.isResourceLoaded(mapperType.getName())) {
super.parse();
retryBindMapperForNamespace();
}
super.parse();
}
private void retryBindMapperForNamespace() {
if (!configuration.hasMapper(mapperType)) {
// Spring may not know the real resource name so we set a flag
// to prevent loading again this resource from the mapper interface
// look at MapperAnnotationBuilder#loadXmlResource
configuration.addLoadedResource("namespace:" + mapperType.getName());
configuration.addMapper(mapperType);
}
}
}
| lgpl-3.0 |
SmartITEngineering/smart-event-hub | hub-api/src/main/java/com/smartitengineering/event/hub/api/Channel.java | 2441 | /*
It is a application for event distribution to event n-consumers with m-sources.
Copyright (C) 2010 "Imran M Yousuf <imran@smartitengineering.com>"
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 3 of the License, or any later
version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.smartitengineering.event.hub.api;
import java.net.URI;
import java.util.Date;
/**
* A channel for broadcasting events. Consumers can only listen to channels that
* are currently available and GET request will not create any channel. Events
* can not be broadcasted with a channel.
* @author imyousuf
* @since 0.1
*/
public interface Channel {
static final String HUB_SUB_RESOURCE_PATH = "hub";
public int getPosition();
/**
* Retrieve the name of the channel. It has to be unique and case insensitive
* in nature.
* @return Name of the channel; should never be null or blank.
*/
public String getName();
public String getDescription();
/**
* Return the auth token for the channel. All clients intending to listen to
* this channel must supply auth token besides the authentication tokens.
* @return Authorization token for this channel
*/
public String getAuthToken();
/**
* Retrieves the creation date time of channel. It will be either created by
* the {@link HubPersistentStorer persistent storer} if configured or by the
* RESTful service which receives the channel information.
* @return Creation date time of this channel
*/
public Date getCreationDateTime();
public Date getLastModifiedDate();
/**
* Return the auto expiry date time of this channel. If this channel is not
* deleted then at the designated date time this channel will be deleted from
* the server.
* @return The expiration date time.
*/
public Date getAutoExpiryDateTime();
/**
* Retrieves the current filter for this channel
* @return Filter of this channel
*/
public Filter getFilter();
}
| lgpl-3.0 |
robcowell/dynamicreports | dynamicreports-core/src/main/java/net/sf/dynamicreports/report/builder/component/HyperLinkComponentBuilder.java | 2319 | /**
* DynamicReports - Free Java reporting library for creating reports dynamically
*
* Copyright (C) 2010 - 2012 Ricardo Mariaca
* http://dynamicreports.sourceforge.net
*
* This file is part of DynamicReports.
*
* DynamicReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.dynamicreports.report.builder.component;
import net.sf.dynamicreports.report.base.component.DRHyperLinkComponent;
import net.sf.dynamicreports.report.builder.HyperLinkBuilder;
import net.sf.dynamicreports.report.builder.expression.Expressions;
import net.sf.dynamicreports.report.constant.Constants;
import net.sf.dynamicreports.report.definition.expression.DRIExpression;
/**
* @author Ricardo Mariaca (dynamicreports@gmail.com)
*/
@SuppressWarnings("unchecked")
public abstract class HyperLinkComponentBuilder<T extends HyperLinkComponentBuilder<T, U>, U extends DRHyperLinkComponent> extends DimensionComponentBuilder<T, U> {
private static final long serialVersionUID = Constants.SERIAL_VERSION_UID;
public HyperLinkComponentBuilder(U component) {
super(component);
}
public T setAnchorName(String anchorName) {
getObject().setAnchorNameExpression(Expressions.text(anchorName));
return (T) this;
}
public T setAnchorName(DRIExpression<String> anchorNameExpression) {
getObject().setAnchorNameExpression(anchorNameExpression);
return (T) this;
}
public T setBookmarkLevel(Integer bookmarkLevel) {
getObject().setBookmarkLevel(bookmarkLevel);
return (T) this;
}
public T setHyperLink(HyperLinkBuilder hyperLink) {
if (hyperLink != null) {
getObject().setHyperLink(hyperLink.getHyperLink());
}
else {
getObject().setHyperLink(null);
}
return (T) this;
}
}
| lgpl-3.0 |
CoderAtParadise/crystal-magic | src/main/java/crystalmagic/client/gui/ModGuiConfig.java | 541 | package crystalmagic.client.gui;
import crystalmagic.common.lib.config.CMConfig;
import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.fml.client.config.GuiConfig;
public class ModGuiConfig extends GuiConfig{
public ModGuiConfig(GuiScreen guiScreen) {
super(guiScreen, (new ConfigElement(CMConfig.config.getCategory("worldgen"))).getChildElements(), "assets/crystalmagic", false, false, GuiConfig.getAbridgedConfigPath(CMConfig.config.toString()));
}
}
| lgpl-3.0 |
TeamMetallurgy/Agriculture2 | src/main/java/com/teammetallurgy/agriculture/machine/frier/ItemRendererFrier.java | 1767 | package com.teammetallurgy.agriculture.machine.frier;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.IItemRenderer;
import org.lwjgl.opengl.GL11;
import com.teammetallurgy.agriculture.BlockList;
import cpw.mods.fml.client.FMLClientHandler;
public class ItemRendererFrier implements IItemRenderer
{
private ResourceLocation texture = new ResourceLocation("agriculture:textures/models/machines/frier.png");
private ModelFrier model = new ModelFrier();
@Override
public boolean handleRenderType(ItemStack itemStack, ItemRenderType type)
{
if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.frier != Block.getBlockFromItem(itemStack.getItem())) return false;
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack itemStack, ItemRendererHelper helper)
{
if (itemStack == null || itemStack.getItem() == null) return false;
if (BlockList.frier != Block.getBlockFromItem(itemStack.getItem())) return false;
return true;
}
@Override
public void renderItem(ItemRenderType type, ItemStack item, Object... data)
{
GL11.glPushMatrix();
GL11.glTranslatef(0.5F, 1.4F, 0.5F);
GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
if (type == ItemRenderType.EQUIPPED)
{
GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
}
FMLClientHandler.instance().getClient().renderEngine.bindTexture(texture);
this.model.setDoorAngle(0);
this.model.renderAll();
GL11.glPopMatrix();
}
}
| lgpl-3.0 |
TeamLapen/Vampirism | src/main/java/de/teamlapen/vampirism/world/loot/TentSpawnerCondition.java | 1663 | package de.teamlapen.vampirism.world.loot;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import de.teamlapen.vampirism.core.ModLoot;
import de.teamlapen.vampirism.tileentity.TentTileEntity;
import net.minecraft.loot.ILootSerializer;
import net.minecraft.loot.LootConditionType;
import net.minecraft.loot.LootContext;
import net.minecraft.loot.LootParameters;
import net.minecraft.loot.conditions.ILootCondition;
import net.minecraft.tileentity.TileEntity;
import javax.annotation.Nonnull;
public class TentSpawnerCondition implements ILootCondition {
private final static TentSpawnerCondition INSTANCE = new TentSpawnerCondition();
public static IBuilder builder() {
return () -> INSTANCE;
}
@Nonnull
@Override
public LootConditionType getType() {
return ModLoot.is_tent_spawner;
}
@Override
public boolean test(LootContext lootContext) {
TileEntity t = lootContext.getParamOrNull(LootParameters.BLOCK_ENTITY);
if (t instanceof TentTileEntity) {
return ((TentTileEntity) t).isSpawner();
}
return false;
}
public static class Serializer implements ILootSerializer<TentSpawnerCondition> {
@Nonnull
@Override
public TentSpawnerCondition deserialize(@Nonnull JsonObject json, @Nonnull JsonDeserializationContext context) {
return INSTANCE;
}
@Override
public void serialize(@Nonnull JsonObject json, @Nonnull TentSpawnerCondition value, @Nonnull JsonSerializationContext context) {
}
}
}
| lgpl-3.0 |
gmt-europe/JSDOServer | src/main/java/nl/gmt/jsdo/schema/JsdoPropertyType.java | 806 | package nl.gmt.jsdo.schema;
public enum JsdoPropertyType {
CHARACTER("CHARACTER", "string"),
LONGCHAR("LONGCHAR", "string"),
LOGICAL("LOGICAL", "boolean"),
DECIMAL("DECIMAL", "number"),
INT64("INT64", "integer"),
INTEGER("INTEGER", "integer"),
ROWID("ROWID", "string"),
DATE("DATE", "string"),
DATETIME("DATETIME", "string"),
DATETIME_TZ("DATETIME-TZ", "string"),
CLOB("CLOB", "string"),
LOB("LOB", "string");
private final String ablType;
private final String type;
private JsdoPropertyType(String ablType, String type) {
this.ablType = ablType;
this.type = type;
}
public String getAblType() {
return ablType;
}
public String getType() {
return type;
}
}
| lgpl-3.0 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/matrix/factory/DefaultSparseMatrixFactory.java | 1657 | /*
* Copyright (C) 2008-2015 by Holger Arndt
*
* This file is part of the Universal Java Matrix Package (UJMP).
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* UJMP 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.
*
* UJMP 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 UJMP; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package org.ujmp.core.matrix.factory;
import org.ujmp.core.Matrix;
import org.ujmp.core.SparseMatrix;
import org.ujmp.core.doublematrix.impl.DefaultSparseRowDoubleMatrix2D;
import org.ujmp.core.objectmatrix.impl.DefaultSparseObjectMatrix;
public class DefaultSparseMatrixFactory extends AbstractMatrixFactory<SparseMatrix> {
public SparseMatrix zeros(long rows, long columns) {
return new DefaultSparseRowDoubleMatrix2D(rows, columns);
}
public SparseMatrix zeros(long... size) {
return new DefaultSparseObjectMatrix(size);
}
public SparseMatrix sparse(Matrix nonZeros) {
return DefaultSparseObjectMatrix.fromNonZeros(nonZeros);
}
}
| lgpl-3.0 |
TeamLapen/Vampirism | src/main/java/de/teamlapen/vampirism/client/gui/AlchemicalCauldronScreen.java | 2624 | package de.teamlapen.vampirism.client.gui;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;
import de.teamlapen.vampirism.core.ModBlocks;
import de.teamlapen.vampirism.inventory.container.AlchemicalCauldronContainer;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class AlchemicalCauldronScreen extends ContainerScreen<AlchemicalCauldronContainer> {
private static final ResourceLocation BACKGROUND = new ResourceLocation("vampirism:textures/gui/alchemical_cauldron.png");
public AlchemicalCauldronScreen(AlchemicalCauldronContainer inventorySlotsIn, PlayerInventory inventoryPlayer, ITextComponent name) {
super(inventorySlotsIn, inventoryPlayer, name);
}
@Override
public void render(MatrixStack stack, int mouseX, int mouseY, float partialTicks) {
this.renderBackground(stack);
super.render
(stack, mouseX, mouseY, partialTicks);
this.renderTooltip(stack, mouseX, mouseY);
}
@Override
protected void renderBg(MatrixStack stack, float partialTicks, int mouseX, int mouseY) {
RenderSystem.color4f(1, 1, 1, 1);
this.minecraft.getTextureManager().bind(BACKGROUND);
int i = (this.width - this.imageWidth) / 2;
int j = (this.height - this.imageHeight) / 2;
this.blit(stack, i, j, 0, 0, this.imageWidth, this.imageHeight);
int k = menu.getLitProgress();
if (k > 0) this.blit(stack, i + 56, j + 36 + 12 - k, 176, 12 - k, 14, k + 1);
int l = menu.getBurnProgress();
this.blit(stack, i + 79, j + 34, 176, 14, l + 1, 16);
l = l / 24 * 30;
this.blit(stack, i + 142, j + 28 + 30 - l, 176, 60 - l, 12, l);
}
@Override
protected void renderLabels(MatrixStack stack, int mouseX, int mouseY) {
ITextComponent name = new TranslationTextComponent("tile.vampirism.alchemical_cauldron.display", minecraft.player.getDisplayName().copy().withStyle(TextFormatting.DARK_BLUE), ModBlocks.alchemical_cauldron.getName());
this.font.draw(stack, name, 5, 6, 0x404040);
this.font.draw(stack, this.inventory.getDisplayName(), (float) this.inventoryLabelX, (float) this.inventoryLabelY, 4210752);
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/main/java/org/sonar/server/computation/task/projectanalysis/qualitygate/QualityGateStatusHolder.java | 1548 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.computation.task.projectanalysis.qualitygate;
import java.util.Map;
public interface QualityGateStatusHolder {
/**
* The global status of the quality gate (if there is a quality gate on the project).
*
* @throws IllegalStateException if status has not yet been set in the holder
* @see QualityGateHolder#getQualityGate()
*/
QualityGateStatus getStatus();
/**
* The status per condition of the quality gate (if there is a quality gate on the project).
*
* @throws IllegalStateException if status has not yet been set in the holder
* @see QualityGateHolder#getQualityGate()
*/
Map<Condition, ConditionStatus> getStatusPerConditions();
}
| lgpl-3.0 |
andforce/SmartZPN | app/src/main/java/org/zarroboogs/smartzpn/core/ProxyConfigLoader.java | 15406 | package org.zarroboogs.smartzpn.core;
import android.content.Context;
import java.io.FileInputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.zarroboogs.smartzpn.R;
import org.zarroboogs.smartzpn.utils.ProxyUtils;
import org.zarroboogs.smartzpn.tunnel.Config;
import org.zarroboogs.smartzpn.tunnel.httpconnect.HttpConnectConfig;
import org.zarroboogs.smartzpn.tunnel.shadowsocks.ShadowsocksConfig;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ProxyConfigLoader {
private static final ProxyConfigLoader sInstance = new ProxyConfigLoader();
public final static boolean IS_DEBUG = true;
private ArrayList<IPAddress> mIPList;
private ArrayList<IPAddress> mDnsServers;
private ArrayList<IPAddress> mRouteList;
private ArrayList<Config> mProxyConfigList;
private HashMap<String, Boolean> mDomainMap;
private int m_dns_ttl;
private String m_welcome_info;
private String m_session_name;
private String m_user_agent;
private boolean m_outside_china_use_proxy = true;
private boolean m_isolate_http_host_header = true;
private int m_mtu;
private OnProxyConfigLoadListener mOnProxyConfigLoadListener;
public void setOnProxyConfigLoadListener(OnProxyConfigLoadListener loadListener){
this.mOnProxyConfigLoadListener = loadListener;
}
public static ProxyConfigLoader getsInstance() {
return sInstance;
}
public class IPAddress {
public final String Address;
public final int PrefixLength;
public IPAddress(String address, int prefixLength) {
this.Address = address;
this.PrefixLength = prefixLength;
}
public IPAddress(String ipAddresString) {
String[] arrStrings = ipAddresString.split("/");
String address = arrStrings[0];
int prefixLength = 32;
if (arrStrings.length > 1) {
prefixLength = Integer.parseInt(arrStrings[1]);
}
this.Address = address;
this.PrefixLength = prefixLength;
}
@Override
public String toString() {
return String.format(Locale.ENGLISH, "%s/%d", Address, PrefixLength);
}
@Override
public boolean equals(Object o) {
return o != null && this.toString().equals(o.toString());
}
}
public ProxyConfigLoader() {
mIPList = new ArrayList<IPAddress>();
mDnsServers = new ArrayList<IPAddress>();
mRouteList = new ArrayList<IPAddress>();
mProxyConfigList = new ArrayList<Config>();
mDomainMap = new HashMap<String, Boolean>();
Timer m_Timer = new Timer();
m_Timer.schedule(timerTask, 120000, 120000);//每两分钟刷新一次。
}
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
refreshProxyServer();//定时更新dns缓存
}
//定时更新dns缓存
void refreshProxyServer() {
try {
for (int i = 0; i < mProxyConfigList.size(); i++) {
try {
Config config = mProxyConfigList.get(0);
InetAddress address = InetAddress.getByName(config.ServerAddress.getHostName());
if (address != null && !address.equals(config.ServerAddress.getAddress())) {
config.ServerAddress = new InetSocketAddress(address, config.ServerAddress.getPort());
}
} catch (Exception ignored) {
}
}
} catch (Exception ignored) {
}
}
};
public Config getDefaultProxy() {
if (mProxyConfigList.size() > 0) {
return mProxyConfigList.get(0);
} else {
return null;
}
}
public Config getDefaultTunnelConfig(InetSocketAddress destAddress) {
return getDefaultProxy();
}
public IPAddress getDefaultLocalIP() {
if (mIPList.size() > 0) {
return mIPList.get(0);
} else {
return new IPAddress("10.8.0.2", 32);
}
}
public ArrayList<IPAddress> getDnsServers() {
return mDnsServers;
}
public ArrayList<IPAddress> getRouteList() {
return mRouteList;
}
public int getDnsTTL() {
if (m_dns_ttl < 30) {
m_dns_ttl = 30;
}
return m_dns_ttl;
}
public String getWelcomeInfo() {
return m_welcome_info;
}
public String getSessionName() {
if (m_session_name == null) {
m_session_name = getDefaultProxy().ServerAddress.getHostName();
}
return m_session_name;
}
public String getUserAgent() {
if (m_user_agent == null || m_user_agent.isEmpty()) {
m_user_agent = System.getProperty("http.agent");
}
return m_user_agent;
}
public int getMTU() {
if (m_mtu > 1400 && m_mtu <= 20000) {
return m_mtu;
} else {
return 20000;
}
}
private Boolean getDomainState(String domain) {
domain = domain.toLowerCase();
while (domain.length() > 0) {
Boolean stateBoolean = mDomainMap.get(domain);
if (stateBoolean != null) {
return stateBoolean;
} else {
int start = domain.indexOf('.') + 1;
if (start > 0 && start < domain.length()) {
domain = domain.substring(start);
} else {
return null;
}
}
}
return null;
}
public boolean needProxy(String host, int ip) {
if (host != null) {
Boolean stateBoolean = getDomainState(host);
if (stateBoolean != null) {
return stateBoolean;
}
}
if (ProxyUtils.isFakeIP(ip))
return true;
if (m_outside_china_use_proxy && ip != 0) {
return !ChinaIpMaskManager.isIPInChina(ip);
}
return false;
}
public boolean isIsolateHttpHostHeader() {
return m_isolate_http_host_header;
}
private String[] downloadConfig(String url) throws Exception {
try {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).get().build();
Call call = okHttpClient.newCall(request);
Response response = call.execute();
String line = response.body().string();
return line.split("\n");
} catch (Exception e) {
String error = e.getLocalizedMessage();
throw new Exception(String.format("Download config file from %s failed. %s", url, error));
}
}
private String[] readConfigFromFile(String path) throws Exception {
StringBuilder sBuilder = new StringBuilder();
FileInputStream inputStream = null;
try {
byte[] buffer = new byte[8192];
int count = 0;
inputStream = new FileInputStream(path);
while ((count = inputStream.read(buffer)) > 0) {
sBuilder.append(new String(buffer, 0, count, "UTF-8"));
}
return sBuilder.toString().split("\\n");
} catch (Exception e) {
throw new Exception(String.format("Can't read config file: %s", path));
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ignored) {
}
}
}
}
public void loadFromUrl(final Context context, final String url){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
ChinaIpMaskManager.loadFromFile(context.getResources().openRawResource(R.raw.ipmask));//加载中国的IP段,用于IP分流。
String[] lines = null;
if (url.charAt(0) == '/') {
try {
lines = readConfigFromFile(url);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
lines = downloadConfig(url);
} catch (Exception e) {
e.printStackTrace();
}
}
mIPList.clear();
mDnsServers.clear();
mRouteList.clear();
mProxyConfigList.clear();
mDomainMap.clear();
int lineNumber = 0;
for (String line : lines) {
lineNumber++;
String[] items = line.split("\\s+");
if (items.length < 2) {
continue;
}
String tagString = items[0].toLowerCase(Locale.ENGLISH).trim();
try {
if (!tagString.startsWith("#")) {
if (ProxyConfigLoader.IS_DEBUG)
System.out.println(line);
switch (tagString) {
case "ip":
addIPAddressToList(items, 1, mIPList);
break;
case "dns":
addIPAddressToList(items, 1, mDnsServers);
break;
case "route":
addIPAddressToList(items, 1, mRouteList);
break;
case "proxy":
addProxyToList(items, 1);
break;
case "direct_domain":
addDomainToHashMap(items, 1, false);
break;
case "proxy_domain":
addDomainToHashMap(items, 1, true);
break;
case "dns_ttl":
m_dns_ttl = Integer.parseInt(items[1]);
break;
case "welcome_info":
m_welcome_info = line.substring(line.indexOf(" ")).trim();
break;
case "session_name":
m_session_name = items[1];
break;
case "user_agent":
m_user_agent = line.substring(line.indexOf(" ")).trim();
break;
case "outside_china_use_proxy":
m_outside_china_use_proxy = convertToBool(items[1]);
break;
case "isolate_http_host_header":
m_isolate_http_host_header = convertToBool(items[1]);
break;
case "mtu":
m_mtu = Integer.parseInt(items[1]);
break;
}
}
} catch (Exception e) {
try {
throw new Exception(String.format(Locale.ENGLISH, "SmartProxy config file parse error: line:%d, tag:%s, error:%s", lineNumber, tagString, e));
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
//查找默认代理。
if (mProxyConfigList.size() == 0) {
tryAddProxy(lines);
}
if (mOnProxyConfigLoadListener != null){
mOnProxyConfigLoadListener.onProxyConfigLoad();
}
}
});
thread.start();
}
private void tryAddProxy(String[] lines) {
for (String line : lines) {
Pattern p = Pattern.compile("proxy\\s+([^:]+):(\\d+)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(line);
while (m.find()) {
HttpConnectConfig config = new HttpConnectConfig();
config.ServerAddress = new InetSocketAddress(m.group(1), Integer.parseInt(m.group(2)));
if (!mProxyConfigList.contains(config)) {
mProxyConfigList.add(config);
mDomainMap.put(config.ServerAddress.getHostName(), false);
}
}
}
}
private void addProxyToList(String[] items, int offset) throws Exception {
for (int i = offset; i < items.length; i++) {
String proxyString = items[i].trim();
Config config = null;
if (proxyString.startsWith("ss://")) {
config = ShadowsocksConfig.parse(proxyString);
} else {
if (!proxyString.toLowerCase().startsWith("http://")) {
proxyString = "http://" + proxyString;
}
config = HttpConnectConfig.parse(proxyString);
}
if (!mProxyConfigList.contains(config)) {
mProxyConfigList.add(config);
mDomainMap.put(config.ServerAddress.getHostName(), false);
}
}
}
private void addDomainToHashMap(String[] items, int offset, Boolean state) {
for (int i = offset; i < items.length; i++) {
String domainString = items[i].toLowerCase().trim();
if (domainString.charAt(0) == '.') {
domainString = domainString.substring(1);
}
mDomainMap.put(domainString, state);
}
}
private boolean convertToBool(String valueString) {
if (valueString == null || valueString.isEmpty())
return false;
valueString = valueString.toLowerCase(Locale.ENGLISH).trim();
return valueString.equals("on") || valueString.equals("1") || valueString.equals("true") || valueString.equals("yes");
}
private void addIPAddressToList(String[] items, int offset, ArrayList<IPAddress> list) {
for (int i = offset; i < items.length; i++) {
String item = items[i].trim().toLowerCase();
if (item.startsWith("#")) {
break;
} else {
IPAddress ip = new IPAddress(item);
if (!list.contains(ip)) {
list.add(ip);
}
}
}
}
interface OnProxyConfigLoadListener{
public void onProxyConfigLoad();
}
}
| lgpl-3.0 |
casmi/casmi | src/main/java/casmi/graphics/element/Text.java | 13652 | /*
* casmi
* http://casmi.github.com/
* Copyright (C) 2011, Xcoo, Inc.
*
* casmi is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package casmi.graphics.element;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import javax.media.opengl.GL2;
import javax.media.opengl.GLException;
import javax.media.opengl.glu.GLU;
import casmi.graphics.font.Font;
import com.jogamp.opengl.util.awt.TextRenderer;
/**
* Text class. Wrap JOGL and make it easy to use.
*
* @author Y. Ban, T. Takeuchi
*/
public class Text extends Element {
private Font font;
private String str;
private String[] strArray;
private FontRenderContext frc;
private TextLayout[] layout;
private TextRenderer textRenderer;
private TextAlign align = TextAlign.LEFT;
private double leading = 0.0;
/**
* Creates a new Text object.
*/
public Text() {
this(null);
}
/**
* Creates a new Text object using letters to be displayed.
*
* @param text The letters to be displayed.
*/
public Text(String text) {
this(text, new Font());
}
/**
* Creates a new Text object using letters to be displayed, and Font.
*
* @param text The letters to be displayed.
* @param font The font of text.
*/
public Text(String text, Font font) {
this(text, font, 0, 0, 0);
}
/**
* Creates a new Text object using letters to be displayed, x,y-coordinate.
*
* @param text The letters to be displayed.
* @param x The x-coordinate of text.
* @param y The y-coordinate of text.
*/
public Text(String text, double x, double y) {
this(text, new Font(), x, y);
}
/**
* Creates a new Text object using letters to be displayed, x,y-coordinate and Font.
*
* @param text The letters to be displayed.
* @param font The font of text.
* @param x The x-coordinate of text.
* @param y The y-coordinate of text.
*/
public Text(String text, Font font, double x, double y) {
this(text, font, x, y, 0);
}
/**
* Creates a new Text object using letters to be displayed, x,y,z-coordinate.
*
* @param text The letters to be displayed.
* @param x The x-coordinate of text.
* @param y The y-coordinate of text.
* @param z The z-coordinate of text.
*/
public Text(String text, double x, double y, double z) {
this(text, new Font(), x, y, z);
}
/**
* Creates a new Text object using letters to be displayed, x,y,z-coordinate and Font.
*
* @param text The letters to be displayed.
* @param font The font of text.
* @param x The x-coordinate of text.
* @param y The y-coordinate of text.
* @param z The z-coordinate of text.
*/
public Text(String text, Font font, double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
this.font = font;
if (text == null) {
this.str = "";
} else {
this.str = text;
}
strArray = this.str.split("\n");
leading = font.getSize() * 1.2;
try {
textRenderer = new TextRenderer(font.getAWTFont(), true, true);
frc = new FontRenderContext(new AffineTransform(), false, false);
layout = new TextLayout[strArray.length];
for (int i = 0; i < strArray.length; ++i) {
layout[i] = new TextLayout(strArray[i], font.getAWTFont(), frc);
}
} catch (java.lang.IllegalArgumentException e) {
// Ignore
}
}
@Override
public void reset(GL2 gl) {
try {
textRenderer = new TextRenderer(font.getAWTFont(), true, true);
frc = new FontRenderContext(new AffineTransform(), false, false);
layout = new TextLayout[strArray.length];
for (int i = 0; i < strArray.length; ++i) {
layout[i] = new TextLayout(strArray[i], font.getAWTFont(), frc);
}
} catch (java.lang.IllegalArgumentException e) {
// Ignore
}
}
@Override
public void render(GL2 gl, GLU glu, int width, int height, boolean selection) {
if (fillColor.getAlpha() < 1.0 || strokeColor.getAlpha() < 1.0 || !isDepthTest())
gl.glDisable(GL2.GL_DEPTH_TEST);
gl.glPushMatrix();
{
move(gl);
if (!selection) {
textRenderer.begin3DRendering();
{
if (stroke) {
textRenderer.setColor((float)getSceneStrokeColor().getRed(),
(float)getSceneStrokeColor().getGreen(),
(float)getSceneStrokeColor().getBlue(),
(float)getSceneStrokeColor().getAlpha());
} else if (fill) {
textRenderer.setColor((float)getSceneFillColor().getRed(),
(float)getSceneFillColor().getGreen(),
(float)getSceneFillColor().getBlue(),
(float)getSceneFillColor().getAlpha());
}
double tmpX = 0.0;
double tmpY = 0.0;
for (int i = 0; i < strArray.length; ++i) {
switch (align) {
case LEFT:
break;
case CENTER:
tmpX = -getWidth(i) / 2.0;
break;
case RIGHT:
tmpX = -getWidth(i);
break;
default:
break;
}
try {
textRenderer.draw3D(strArray[i], (float)tmpX, (float)(tmpY - leading * i), (float)z, 1.0f);
} catch (ArrayIndexOutOfBoundsException e) {
// Ignore
break;
}
}
}
textRenderer.end3DRendering();
} else {
double tmpX = 0.0;
double tmpY = 0.0;
for (int i = 0; i < strArray.length; ++i) {
switch (align) {
case LEFT:
break;
case CENTER:
tmpX = -getWidth(i) / 2.0;
break;
case RIGHT:
tmpX = -getWidth(i);
break;
default:
break;
}
gl.glBegin(GL2.GL_QUADS);
{
gl.glVertex2d(tmpX, (tmpY - leading * i) - getDescent(i));
gl.glVertex2d(tmpX, (tmpY - leading * i) + getAscent(i));
gl.glVertex2d(tmpX + getWidth(i), (tmpY - leading * i) + getAscent(i));
gl.glVertex2d(tmpX + getWidth(i), (tmpY - leading * i) - getDescent(i));
}
gl.glEnd();
}
}
}
gl.glPopMatrix();
if (fillColor.getAlpha() < 1.0 || strokeColor.getAlpha() < 1.0 || !isDepthTest())
gl.glEnable(GL2.GL_DEPTH_TEST);
}
/**
* Returns descent of the current font at its current size and line.
*
* @param line The number of lines.
* @return The descent of text.
*/
public final double getDescent(int line) {
if (layout[line] == null) return 0;
return layout[line].getDescent();
}
/**
* Returns ascent of the current font at its current size and line.
*
* @param line The number of lines.
* @return The ascent of text.
*/
public final double getAscent(int line) {
if (layout[line] == null) return 0;
return layout[line].getAscent();
}
/**
* Returns descent of the current font at its current size.
*
* @return The descent of text.
*/
public final double getDescent() {
return getDescent(0);
}
/**
* Returns ascent of the current font at its current size.
*
* @return The ascent of text.
*/
public final double getAscent() {
return getAscent(0);
}
/**
* Returns letter's width of the current font at its current size.
*
* @return The letter's width.
*/
public final double getWidth() {
return getWidth(0);
}
/**
* Returns letter's height of the current font at its current size.
*
* @return The letter's height.
*/
public final double getHeight() {
return getHeight(0);
}
/**
* Returns letter's width of the current font at its current size and line.
*
* @param line The number of lines.
* @return The letter's width.
*
* @throws GLException If the textRenderer is not valid; calls the reset method and creates a
* new textRenderer.
*/
public final double getWidth(int line) {
if (strArray.length == 0) return 0.0;
try {
return textRenderer.getBounds(strArray[line]).getWidth();
} catch (GLException e) {
reset = true;
}
return 0.0;
}
/**
* Returns letter's height of the current font at its current size and line.
*
* @param line The number of lines.
* @return The letter's height.
*
* @throws GLException If the textRenderer is not valid; calls the reset method and creates a
* new textRenderer.
*/
public final double getHeight(int line) {
if (strArray.length == 0) return 0.0;
try {
return textRenderer.getBounds(strArray[line]).getHeight();
} catch (GLException e) {
reset = true;
}
return 0.0;
}
/**
* Returns the TextLayout of this Text.
*
* @return The TextLayout of this Text.
*/
public final TextLayout getLayout() {
return layout[0];
}
/**
* Returns the TextLayout of the i line.
*
* @param line The number of lines.
* @return The TextLayout of the i line.
*/
public final TextLayout getLayout(int line) {
return layout[line];
}
/**
* Returns the current alignment for drawing text. The parameters LEFT, CENTER, and RIGHT set
* the display characteristics of the letters in relation to the values for the x and y
* parameters of the text() function.
*
* @return The TextAlign of the text.
*/
public final TextAlign getAlign() {
return align;
}
/**
* Sets the current alignment for drawing text. The parameters LEFT, CENTER, and RIGHT set the
* display characteristics of the letters in relation to the values for the x and y parameters
* of the text() function.
*
* @param align Either LEFT, CENTER or LIGHT.
*/
public void setAlign(TextAlign align) {
this.align = align;
}
public void setLeading(double leading) {
this.leading = leading;
}
/**
* Returns the leading of this letters.
*
* @return The leading of this Text.
*/
public double getLeading() {
return leading;
}
public int getLine() {
return strArray.length;
}
/**
* Returns the letters of this Text.
*
* @return The letters of this Text.
*/
public String getText() {
return str;
}
/**
* Sets the letters of this Text.
*
* @param str The letters to be displayed.
*/
public void setText(String str) {
this.str = str;
setArrayText(str);
}
protected String[] getArrayText() {
return strArray;
}
protected void setArrayText(String str) {
strArray = null;
this.str = str;
strArray = this.str.split("\n");
}
/**
* Returns the TextRenderer of this Text.
*
* @return The TextRenderer of this Text.
*/
public TextRenderer getRenderer() {
return textRenderer;
}
/**
* Returns the Font of this Text.
*
* @return The Font of the Text.
*/
public final Font getFont() {
return font;
}
/**
* Sets the Font of this Text.
*
* @param font The Font of the Text.
*/
public final void setFont(Font font) {
this.font = font;
textRenderer = new TextRenderer(font.getAWTFont(), true, true);
}
/**
* Check texture is enable or not.
*/
@Override
public boolean isEnableTexture() {
return true;
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/test/java/org/sonar/server/permission/ws/template/AddGroupToTemplateActionTest.java | 7604 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission.ws.template;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.web.UserRole;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.permission.PermissionQuery;
import org.sonar.db.permission.template.PermissionTemplateDto;
import org.sonar.db.user.GroupDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.permission.ws.BasePermissionWsTest;
import org.sonar.server.ws.TestRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.security.DefaultGroups.ANYONE;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.CODEVIEWER;
import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_GROUP_NAME;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_PERMISSION;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_ID;
import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_TEMPLATE_NAME;
public class AddGroupToTemplateActionTest extends BasePermissionWsTest<AddGroupToTemplateAction> {
private PermissionTemplateDto template;
private GroupDto group;
@Override
protected AddGroupToTemplateAction buildWsAction() {
return new AddGroupToTemplateAction(db.getDbClient(), newPermissionWsSupport(), userSession);
}
@Before
public void setUp() {
template = insertTemplate();
group = db.users().insertGroup(db.getDefaultOrganization(), "group-name");
}
@Test
public void add_group_to_template() throws Exception {
loginAsAdminOnDefaultOrganization();
newRequest(group.getName(), template.getUuid(), CODEVIEWER);
assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(group.getName());
}
@Test
public void add_group_to_template_by_name() throws Exception {
loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_GROUP_NAME, group.getName())
.setParam(PARAM_PERMISSION, CODEVIEWER)
.setParam(PARAM_TEMPLATE_NAME, template.getName().toUpperCase())
.execute();
assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(group.getName());
}
@Test
public void add_with_group_id() throws Exception {
loginAsAdminOnDefaultOrganization();
newRequest()
.setParam(PARAM_TEMPLATE_ID, template.getUuid())
.setParam(PARAM_PERMISSION, CODEVIEWER)
.setParam(PARAM_GROUP_ID, String.valueOf(group.getId()))
.execute();
assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(group.getName());
}
@Test
public void does_not_add_a_group_twice() throws Exception {
loginAsAdminOnDefaultOrganization();
newRequest(group.getName(), template.getUuid(), ISSUE_ADMIN);
newRequest(group.getName(), template.getUuid(), ISSUE_ADMIN);
assertThat(getGroupNamesInTemplateAndPermission(template, ISSUE_ADMIN)).containsExactly(group.getName());
}
@Test
public void add_anyone_group_to_template() throws Exception {
loginAsAdminOnDefaultOrganization();
newRequest(ANYONE, template.getUuid(), CODEVIEWER);
assertThat(getGroupNamesInTemplateAndPermission(template, CODEVIEWER)).containsExactly(ANYONE);
}
@Test
public void fail_if_add_anyone_group_to_admin_permission() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
expectedException.expectMessage(String.format("It is not possible to add the '%s' permission to the group 'Anyone'", UserRole.ADMIN));
newRequest(ANYONE, template.getUuid(), ADMIN);
}
@Test
public void fail_if_not_a_project_permission() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(IllegalArgumentException.class);
newRequest(group.getName(), template.getUuid(), GlobalPermissions.PROVISIONING);
}
@Test
public void fail_if_not_admin_of_default_organization() throws Exception {
userSession.logIn();
expectedException.expect(ForbiddenException.class);
newRequest(group.getName(), template.getUuid(), CODEVIEWER);
}
@Test
public void fail_if_group_params_missing() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
newRequest(null, template.getUuid(), CODEVIEWER);
}
@Test
public void fail_if_permission_missing() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(IllegalArgumentException.class);
newRequest(group.getName(), template.getUuid(), null);
}
@Test
public void fail_if_template_uuid_and_name_missing() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(BadRequestException.class);
newRequest(group.getName(), null, CODEVIEWER);
}
@Test
public void fail_if_group_does_not_exist() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("No group with name 'unknown-group-name'");
newRequest("unknown-group-name", template.getUuid(), CODEVIEWER);
}
@Test
public void fail_if_template_key_does_not_exist() throws Exception {
loginAsAdminOnDefaultOrganization();
expectedException.expect(NotFoundException.class);
expectedException.expectMessage("Permission template with id 'unknown-key' is not found");
newRequest(group.getName(), "unknown-key", CODEVIEWER);
}
private void newRequest(@Nullable String groupName, @Nullable String templateKey, @Nullable String permission) throws Exception {
TestRequest request = newRequest();
if (groupName != null) {
request.setParam(PARAM_GROUP_NAME, groupName);
}
if (templateKey != null) {
request.setParam(PARAM_TEMPLATE_ID, templateKey);
}
if (permission != null) {
request.setParam(PARAM_PERMISSION, permission);
}
request.execute();
}
private List<String> getGroupNamesInTemplateAndPermission(PermissionTemplateDto template, String permission) {
PermissionQuery query = PermissionQuery.builder().setPermission(permission).build();
return db.getDbClient().permissionTemplateDao()
.selectGroupNamesByQueryAndTemplate(db.getSession(), query, template.getOrganizationUuid(), template.getId());
}
}
| lgpl-3.0 |
JorgeVector/OfertaGuiadaVector | src/main/java/com/isb/og/wsdl/ofegui/ComIsbSanoguServiciosdirogEFCbEvalCondTrasParcPPSType.java | 5466 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// 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: 2017.06.05 at 02:19:47 PM CEST
//
package com.isb.og.wsdl.ofegui;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for com.isb.sanogu.serviciosdirog.e.f.cb.EvalCondTrasParcPP_S_Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="com.isb.sanogu.serviciosdirog.e.f.cb.EvalCondTrasParcPP_S_Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="importe" type="{http://www.isban.es/webservices/TDCc}IMPORTE_Type" minOccurs="0"/>
* <element name="participaciones" type="{http://www.isban.es/webservices/TDCs}PARTICIPACIONES_RETENIDAS_Type" minOccurs="0"/>
* <element name="ultFecVal" type="{http://www.isban.es/webservices/TDCs}FECHA_GENERICA_Type" minOccurs="0"/>
* <element name="valorLiq" type="{http://www.isban.es/webservices/TDCc}VALOR_LIQUIDATIVO_PP_Type" minOccurs="0"/>
* <element name="indOperPend" type="{http://www.isban.es/webservices/TDCs}INDICADOR_SI-NO_Type" minOccurs="0"/>
* <element name="indicadorOk" type="{http://www.isban.es/webservices/TDCs}INDICADOR_SI-NO_Type" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "com.isb.sanogu.serviciosdirog.e.f.cb.EvalCondTrasParcPP_S_Type", propOrder = {
"importe",
"participaciones",
"ultFecVal",
"valorLiq",
"indOperPend",
"indicadorOk"
})
public class ComIsbSanoguServiciosdirogEFCbEvalCondTrasParcPPSType {
protected IMPORTEType importe;
protected BigDecimal participaciones;
protected XMLGregorianCalendar ultFecVal;
protected VALORLIQUIDATIVOPPType valorLiq;
protected String indOperPend;
protected String indicadorOk;
/**
* Gets the value of the importe property.
*
* @return
* possible object is
* {@link IMPORTEType }
*
*/
public IMPORTEType getImporte() {
return importe;
}
/**
* Sets the value of the importe property.
*
* @param value
* allowed object is
* {@link IMPORTEType }
*
*/
public void setImporte(IMPORTEType value) {
this.importe = value;
}
/**
* Gets the value of the participaciones property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getParticipaciones() {
return participaciones;
}
/**
* Sets the value of the participaciones property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setParticipaciones(BigDecimal value) {
this.participaciones = value;
}
/**
* Gets the value of the ultFecVal property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getUltFecVal() {
return ultFecVal;
}
/**
* Sets the value of the ultFecVal property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setUltFecVal(XMLGregorianCalendar value) {
this.ultFecVal = value;
}
/**
* Gets the value of the valorLiq property.
*
* @return
* possible object is
* {@link VALORLIQUIDATIVOPPType }
*
*/
public VALORLIQUIDATIVOPPType getValorLiq() {
return valorLiq;
}
/**
* Sets the value of the valorLiq property.
*
* @param value
* allowed object is
* {@link VALORLIQUIDATIVOPPType }
*
*/
public void setValorLiq(VALORLIQUIDATIVOPPType value) {
this.valorLiq = value;
}
/**
* Gets the value of the indOperPend property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIndOperPend() {
return indOperPend;
}
/**
* Sets the value of the indOperPend property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIndOperPend(String value) {
this.indOperPend = value;
}
/**
* Gets the value of the indicadorOk property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIndicadorOk() {
return indicadorOk;
}
/**
* Sets the value of the indicadorOk property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIndicadorOk(String value) {
this.indicadorOk = value;
}
}
| unlicense |
stchepanhagn/normmas-sim | src/env/normmas/StatisticsBase.java | 1597 | package normmas;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
public class StatisticsBase {
private static StatisticsBase instance;
protected ConcurrentHashMap<String, Double> base;
private StatisticsBase() {
this.base = new ConcurrentHashMap<String, Double>();
}
public static StatisticsBase getInstance() {
if (instance == null) {
instance = new StatisticsBase();
}
return instance;
}
public boolean containsStat(String name) {
return this.base.containsKey(name);
}
public void addStat(String name, double value) {
if (!this.base.containsKey(name)) {
this.base.put(name, value);
}
}
public void updateStat(String name, double value) {
if (this.base.containsKey(name)) {
this.base.replace(name, value);
}
}
public void addOrUpdateStat(String name, double value) {
if (this.base.containsKey(name)) {
this.base.replace(name, value);
} else {
this.base.put(name, value);
}
}
public void statUp(String name) {
if (!this.base.containsKey(name)) {
this.addStat(name, 0);
}
double value = this.base.get(name);
this.base.replace(name, ++value);
}
public double readStat(String name) {
if (this.base.containsKey(name)) {
Double stat = this.base.get(name);
if (stat == null)
return 0;
return stat;
}
else {
return 0;
}
}
@Override
public String toString() {
String result = "Statistic\tValue\n";
for (Entry<String, Double> entry: this.base.entrySet()) {
result = result.concat(entry.getKey() + "\t" + entry.getValue() + "\n");
}
return result;
}
}
| unlicense |
codeApeFromChina/resource | frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/jms/connection/SmartConnectionFactory.java | 1270 | /*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jms.connection;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
/**
* Extension of the <code>javax.jms.ConnectionFactory</code> interface,
* indicating how to release Connections obtained from it.
*
* @author Juergen Hoeller
* @since 2.0.2
*/
public interface SmartConnectionFactory extends ConnectionFactory {
/**
* Should we stop the Connection, obtained from this ConnectionFactory?
* @param con the Connection to check
* @return whether a stop call is necessary
* @see javax.jms.Connection#stop()
*/
boolean shouldStop(Connection con);
}
| unlicense |
zhaoccx/COM | JavaServletCart/src/dao/ItemsDAO.java | 3300 | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import entity.Items;
import util.DBHelper;
//ÉÌÆ·µÄÒµÎñÂß¼Àà
public class ItemsDAO {
// »ñµÃËùÓеÄÉÌÆ·ÐÅÏ¢
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // ÉÌÆ·¼¯ºÏ
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // SQLÓï¾ä
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// °ÑÒ»¸öÉÌÆ·¼ÓÈ뼯ºÏ
}
return list; // ·µ»Ø¼¯ºÏ¡£
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// ÊÍ·ÅÊý¾Ý¼¯¶ÔÏó
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// ÊÍ·ÅÓï¾ä¶ÔÏó
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// ¸ù¾ÝÉÌÆ·±àºÅ»ñµÃÉÌÆ·×ÊÁÏ
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQLÓï¾ä
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// ÊÍ·ÅÊý¾Ý¼¯¶ÔÏó
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// ÊÍ·ÅÓï¾ä¶ÔÏó
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
// »ñÈ¡×î½üä¯ÀÀµÄǰÎåÌõÉÌÆ·ÐÅÏ¢
public ArrayList<Items> getViewList(String list) {
System.out.println("list:" + list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount = 5; // ÿ´Î·µ»ØÇ°ÎåÌõ¼Ç¼
if (list != null && list.length() > 0) {
String[] arr = list.split(",");
System.out.println("arr.length=" + arr.length);
// Èç¹ûÉÌÆ·¼Ç¼´óÓÚµÈÓÚ5Ìõ
if (arr.length >= 5) {
for (int i = arr.length - 1; i >= arr.length - iCount; i--) {
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
} else {
for (int i = arr.length - 1; i >= 0; i--) {
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
} else {
return null;
}
}
}
| unlicense |
GHJGHJJHG/CTYJava | Hello/src/helloLong.java | 3340 | public class helloLong{
public static void main(String[]String){
/*\u0077\u006F\u0077\u0020\u0075\u006E\u0069\u0063\u006F\u0064\u0065\u0020\u0069\u0073\u0020\u0066\u0075\u006E\u002A\u002F
\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u0020\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u003D\u0033\u0032\u003B
\u0061\u0028\u0061\u0028\u006E\u0065\u0077\u0020\u006A\u0061\u0076\u0061\u002E\u0075\u0074\u0069\u006C
\u002E\u0052\u0061\u006E\u0064\u006F\u006D\u0028\u0039\u0031\u0036\u0038\u0037\u0030\u0035\u0029\u0029\u0029\u003B
\u0050\u0072\u0069\u006E\u0074\u0053\u0074\u0072\u0065\u0061\u006D\u002E\u0070\u0072\u0069\u006E\u0074
\u0028\u0028\u0063\u0068\u0061\u0072\u0029\u0028\u002B\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u0029\u0029\u003B
\u0061\u0028\u0061\u0028\u006E\u0065\u0077\u0020\u006A\u0061\u0076\u0061\u002E\u0075\u0074\u0069\u006C\u002E
\u0052\u0061\u006E\u0064\u006F\u006D\u0028\u0032\u0039\u0032\u0030\u0034\u0032\u0035\u0029\u0029\u0029\u003B
\u0050\u0072\u0069\u006E\u0074\u0053\u0074\u0072\u0065\u0061\u006D\u002E\u0070\u0072\u0069\u006E\u0074\u006C\u006E
\u0028\u0028\u0063\u0068\u0061\u0072\u0029\u0028\u0031\u002B\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u0029\u0029\u003B
\u007D\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0076\u006F\u0069\u0064\u0020\u0061\u0028\u0063\u0068\u0061\u0072
\u005B\u005D\u006A\u0061\u0076\u0061\u0029\u007B\u006A\u0061\u0076\u0061\u005B\u0030\u005D\u003D
\u0043\u0068\u0061\u0072\u0061\u0063\u0074\u0065\u0072\u002E\u0074\u006F\u0055\u0070\u0070\u0065\u0072\u0043\u0061\u0073\u0065
\u0028\u006A\u0061\u0076\u0061\u005B\u0030\u005D\u0029\u003B\u0050\u0072\u0069\u006E\u0074\u0053\u0074\u0072\u0065\u0061\u006D
\u002E\u0070\u0072\u0069\u006E\u0074\u0028\u006A\u0061\u0076\u0061\u0029\u003B\u007D\u0073\u0074\u0061\u0074\u0069\u0063
\u006A\u0061\u0076\u0061\u002E\u0069\u006F\u002E\u0050\u0072\u0069\u006E\u0074\u0053\u0074\u0072\u0065\u0061\u006D
\u0050\u0072\u0069\u006E\u0074\u0053\u0074\u0072\u0065\u0061\u006D\u003D\u0053\u0079\u0073\u0074\u0065\u006D\u002E\u006F\u0075\u0074\u003B
\u0073\u0074\u0061\u0074\u0069\u0063\u0020\u0063\u0068\u0061\u0072\u005B\u005D\u0061\u0028\u006A\u0061\u0076\u0061\u002E\u0075\u0074\u0069\u006C
\u002E\u0052\u0061\u006E\u0064\u006F\u006D\u0020\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u0029\u007B\u0063\u0068\u0061\u0072\u0020
\u0052\u0061\u006E\u0064\u006F\u006D\u005B\u005D\u002C\u0045\u0078\u0063\u0065\u0070\u0074\u0069\u006F\u006E\u003B\u0066\u006F\u0072
\u0028\u0045\u0078\u0063\u0065\u0070\u0074\u0069\u006F\u006E\u003D\u0030\u002C\u0052\u0061\u006E\u0064\u006F\u006D\u003D\u006E\u0065\u0077
\u0063\u0068\u0061\u0072\u005B\u0035\u005D\u003B\u0045\u0078\u0063\u0065\u0070\u0074\u0069\u006F\u006E\u003C\u0035\u003B\u0052\u0061\u006E\u0064\u006F\u006D
\u005B\u0045\u0078\u0063\u0065\u0070\u0074\u0069\u006F\u006E\u002D\u0031\u005D\u003D\u0028\u0063\u0068\u0061\u0072\u0029\u0028
\u0049\u006E\u0074\u0065\u0067\u0065\u0072\u002E\u006E\u0065\u0078\u0074\u0049\u006E\u0074\u0028\u0032\u0037\u0029\u002B\u0039\u0037\u0029\u0029
\u0045\u0078\u0063\u0065\u0070\u0074\u0069\u006F\u006E\u002B\u002B\u003B\u0072\u0065\u0074\u0075\u0072\u006E\u0020\u0052\u0061\u006E\u0064\u006F\u006D\u003B\u002F\u002A*/
}
}
| unlicense |
clilystudio/NetBook | allsrc/com/ximalaya/ting/android/opensdk/datatrasfer/CommonRequest$28.java | 1392 | package com.ximalaya.ting.android.opensdk.datatrasfer;
import com.squareup.okhttp.I;
import com.ximalaya.ting.android.opensdk.httputil.BaseResponse;
import com.ximalaya.ting.android.opensdk.httputil.ExecutorDelivery;
import com.ximalaya.ting.android.opensdk.httputil.IHttpCallBack;
import com.ximalaya.ting.android.opensdk.model.tag.TagList;
import java.lang.reflect.Type;
import java.util.List;
class CommonRequest$28
implements IHttpCallBack
{
public void onFailure(int paramInt, String paramString)
{
CommonRequest.access$0().postError(paramInt, paramString, this.val$callback);
}
public void onResponse(I paramI)
{
BaseResponse localBaseResponse = new BaseResponse(paramI);
Type localType = new CommonRequest.28.1(this).getType();
try
{
List localList = (List)localBaseResponse.getResponseBodyStringToObject(localType);
TagList localTagList = new TagList();
localTagList.setTagList(localList);
CommonRequest.access$0().postSuccess(this.val$callback, localTagList);
return;
}
catch (Exception localException)
{
CommonRequest.access$0().postError(603, "parse data error", this.val$callback);
}
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest.28
* JD-Core Version: 0.6.0
*/ | unlicense |
codeApeFromChina/resource | frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/core/Conventions.java | 11273 | /*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core;
import java.io.Externalizable;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* Provides methods to support various naming and other conventions used
* throughout the framework. Mainly for internal use within the framework.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public abstract class Conventions {
/**
* Suffix added to names when using arrays.
*/
private static final String PLURAL_SUFFIX = "List";
/**
* Set of interfaces that are supposed to be ignored
* when searching for the 'primary' interface of a proxy.
*/
private static final Set ignoredInterfaces = new HashSet();
static {
ignoredInterfaces.add(Serializable.class);
ignoredInterfaces.add(Externalizable.class);
ignoredInterfaces.add(Cloneable.class);
ignoredInterfaces.add(Comparable.class);
}
/**
* Determine the conventional variable name for the supplied
* <code>Object</code> based on its concrete type. The convention
* used is to return the uncapitalized short name of the <code>Class</code>,
* according to JavaBeans property naming rules: So,
* <code>com.myapp.Product</code> becomes <code>product</code>;
* <code>com.myapp.MyProduct</code> becomes <code>myProduct</code>;
* <code>com.myapp.UKProduct</code> becomes <code>UKProduct</code>.
* <p>For arrays, we use the pluralized version of the array component type.
* For <code>Collection</code>s we attempt to 'peek ahead' in the
* <code>Collection</code> to determine the component type and
* return the pluralized version of that component type.
* @param value the value to generate a variable name for
* @return the generated variable name
*/
public static String getVariableName(Object value) {
Assert.notNull(value, "Value must not be null");
Class valueClass = null;
boolean pluralize = false;
if (value.getClass().isArray()) {
valueClass = value.getClass().getComponentType();
pluralize = true;
}
else if (value instanceof Collection) {
Collection collection = (Collection) value;
if (collection.isEmpty()) {
throw new IllegalArgumentException("Cannot generate variable name for an empty Collection");
}
Object valueToCheck = peekAhead(collection);
valueClass = getClassForValue(valueToCheck);
pluralize = true;
}
else {
valueClass = getClassForValue(value);
}
String name = ClassUtils.getShortNameAsProperty(valueClass);
return (pluralize ? pluralize(name) : name);
}
/**
* Determine the conventional variable name for the supplied parameter,
* taking the generic collection type (if any) into account.
* @param parameter the method or constructor parameter to generate a variable name for
* @return the generated variable name
*/
public static String getVariableNameForParameter(MethodParameter parameter) {
Assert.notNull(parameter, "MethodParameter must not be null");
Class valueClass = null;
boolean pluralize = false;
if (parameter.getParameterType().isArray()) {
valueClass = parameter.getParameterType().getComponentType();
pluralize = true;
}
else if (Collection.class.isAssignableFrom(parameter.getParameterType())) {
if (JdkVersion.isAtLeastJava15()) {
valueClass = GenericCollectionTypeResolver.getCollectionParameterType(parameter);
}
if (valueClass == null) {
throw new IllegalArgumentException("Cannot generate variable name for non-typed Collection parameter type");
}
pluralize = true;
}
else {
valueClass = parameter.getParameterType();
}
String name = ClassUtils.getShortNameAsProperty(valueClass);
return (pluralize ? pluralize(name) : name);
}
/**
* Determine the conventional variable name for the return type of the supplied method,
* taking the generic collection type (if any) into account.
* @param method the method to generate a variable name for
* @return the generated variable name
*/
public static String getVariableNameForReturnType(Method method) {
return getVariableNameForReturnType(method, method.getReturnType(), null);
}
/**
* Determine the conventional variable name for the return type of the supplied method,
* taking the generic collection type (if any) into account, falling back to the
* given return value if the method declaration is not specific enough (i.e. in case of
* the return type being declared as <code>Object</code> or as untyped collection).
* @param method the method to generate a variable name for
* @param value the return value (may be <code>null</code> if not available)
* @return the generated variable name
*/
public static String getVariableNameForReturnType(Method method, Object value) {
return getVariableNameForReturnType(method, method.getReturnType(), value);
}
/**
* Determine the conventional variable name for the return type of the supplied method,
* taking the generic collection type (if any) into account, falling back to the
* given return value if the method declaration is not specific enough (i.e. in case of
* the return type being declared as <code>Object</code> or as untyped collection).
* @param method the method to generate a variable name for
* @param resolvedType the resolved return type of the method
* @param value the return value (may be <code>null</code> if not available)
* @return the generated variable name
*/
public static String getVariableNameForReturnType(Method method, Class resolvedType, Object value) {
Assert.notNull(method, "Method must not be null");
if (Object.class.equals(resolvedType)) {
if (value == null) {
throw new IllegalArgumentException("Cannot generate variable name for an Object return type with null value");
}
return getVariableName(value);
}
Class valueClass = null;
boolean pluralize = false;
if (resolvedType.isArray()) {
valueClass = resolvedType.getComponentType();
pluralize = true;
}
else if (Collection.class.isAssignableFrom(resolvedType)) {
if (JdkVersion.isAtLeastJava15()) {
valueClass = GenericCollectionTypeResolver.getCollectionReturnType(method);
}
if (valueClass == null) {
if (!(value instanceof Collection)) {
throw new IllegalArgumentException(
"Cannot generate variable name for non-typed Collection return type and a non-Collection value");
}
Collection collection = (Collection) value;
if (collection.isEmpty()) {
throw new IllegalArgumentException(
"Cannot generate variable name for non-typed Collection return type and an empty Collection value");
}
Object valueToCheck = peekAhead(collection);
valueClass = getClassForValue(valueToCheck);
}
pluralize = true;
}
else {
valueClass = resolvedType;
}
String name = ClassUtils.getShortNameAsProperty(valueClass);
return (pluralize ? pluralize(name) : name);
}
/**
* Convert <code>String</code>s in attribute name format (lowercase, hyphens separating words)
* into property name format (camel-cased). For example, <code>transaction-manager</code> is
* converted into <code>transactionManager</code>.
*/
public static String attributeNameToPropertyName(String attributeName) {
Assert.notNull(attributeName, "'attributeName' must not be null");
if (attributeName.indexOf("-") == -1) {
return attributeName;
}
char[] chars = attributeName.toCharArray();
char[] result = new char[chars.length -1]; // not completely accurate but good guess
int currPos = 0;
boolean upperCaseNext = false;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == '-') {
upperCaseNext = true;
}
else if (upperCaseNext) {
result[currPos++] = Character.toUpperCase(c);
upperCaseNext = false;
}
else {
result[currPos++] = c;
}
}
return new String(result, 0, currPos);
}
/**
* Return an attribute name qualified by the supplied enclosing {@link Class}. For example,
* the attribute name '<code>foo</code>' qualified by {@link Class} '<code>com.myapp.SomeClass</code>'
* would be '<code>com.myapp.SomeClass.foo</code>'
*/
public static String getQualifiedAttributeName(Class enclosingClass, String attributeName) {
Assert.notNull(enclosingClass, "'enclosingClass' must not be null");
Assert.notNull(attributeName, "'attributeName' must not be null");
return enclosingClass.getName() + "." + attributeName;
}
/**
* Determines the class to use for naming a variable that contains
* the given value.
* <p>Will return the class of the given value, except when
* encountering a JDK proxy, in which case it will determine
* the 'primary' interface implemented by that proxy.
* @param value the value to check
* @return the class to use for naming a variable
*/
private static Class getClassForValue(Object value) {
Class valueClass = value.getClass();
if (Proxy.isProxyClass(valueClass)) {
Class[] ifcs = valueClass.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
Class ifc = ifcs[i];
if (!ignoredInterfaces.contains(ifc)) {
return ifc;
}
}
}
else if (valueClass.getName().lastIndexOf('$') != -1 && valueClass.getDeclaringClass() == null) {
// '$' in the class name but no inner class -
// assuming it's a special subclass (e.g. by OpenJPA)
valueClass = valueClass.getSuperclass();
}
return valueClass;
}
/**
* Pluralize the given name.
*/
private static String pluralize(String name) {
return name + PLURAL_SUFFIX;
}
/**
* Retrieves the <code>Class</code> of an element in the <code>Collection</code>.
* The exact element for which the <code>Class</code> is retreived will depend
* on the concrete <code>Collection</code> implementation.
*/
private static Object peekAhead(Collection collection) {
Iterator it = collection.iterator();
if (!it.hasNext()) {
throw new IllegalStateException(
"Unable to peek ahead in non-empty collection - no element found");
}
Object value = it.next();
if (value == null) {
throw new IllegalStateException(
"Unable to peek ahead in non-empty collection - only null element found");
}
return value;
}
}
| unlicense |
0359xiaodong/HNdroid | src/com/gluegadget/hndroid/KarmaWidget.java | 4264 | package com.gluegadget.hndroid;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.Queue;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
public class KarmaWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if (appWidgetIds == null) {
appWidgetIds = appWidgetManager.getAppWidgetIds(
new ComponentName(context, KarmaWidget.class));
}
UpdateService.requestUpdate(appWidgetIds);
context.startService(new Intent(context, UpdateService.class));
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
KarmaWidgetConfigurationActivity.deleteUsername(context, appWidgetIds[i]);
}
}
public static class UpdateService extends Service implements Runnable {
private static Object sLock = new Object();
private static Queue<Integer> sAppWidgetIds = new LinkedList<Integer>();
private static boolean sThreadRunning = false;
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
synchronized (sLock) {
if (!sThreadRunning) {
sThreadRunning = true;
new Thread(this).start();
}
}
}
public static void requestUpdate(int[] appWidgetIds) {
synchronized (sLock) {
for (int appWidgetId : appWidgetIds) {
sAppWidgetIds.add(appWidgetId);
}
}
}
public RemoteViews buildUpdate(Context context) {
return null;
}
@Override
public IBinder onBind(Intent intent) {
// no need to bind
return null;
}
@Override
public void run() {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
while (hasMoreUpdates()) {
int appWidgetId = getNextUpdate();
updateAppWidget(getApplicationContext(), appWidgetManager, appWidgetId);
}
}
private static boolean hasMoreUpdates() {
synchronized (sLock) {
boolean hasMore = !sAppWidgetIds.isEmpty();
if (!hasMore) {
sThreadRunning = false;
}
return hasMore;
}
}
private static int getNextUpdate() {
synchronized (sLock) {
if (sAppWidgetIds.peek() == null) {
return AppWidgetManager.INVALID_APPWIDGET_ID;
} else {
return sAppWidgetIds.poll();
}
}
}
}
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
String username = (String) KarmaWidgetConfigurationActivity.loadUsername(context, appWidgetId);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.karma_widget);
try {
URL url;
url = new URL("http://news.ycombinator.com/user?id=" + username);
URLConnection connection;
connection = url.openConnection();
InputStream in = connection.getInputStream();
HtmlCleaner cleaner = new HtmlCleaner();
TagNode node = cleaner.clean(in);
Object[] userInfo = node.evaluateXPath("//form[@method='post']/table/tbody/tr/td[2]");
if (userInfo.length > 3) {
TagNode karmaNode = (TagNode)userInfo[2];
views.setTextViewText(R.id.username, username);
views.setTextViewText(R.id.karma, karmaNode.getChildren().iterator().next().toString().trim());
} else {
views.setTextViewText(R.id.username, "unknown");
views.setTextViewText(R.id.karma, "0");
}
appWidgetManager.updateAppWidget(appWidgetId, views);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XPatherException e) {
e.printStackTrace();
}
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
| unlicense |
TomatoPana/TerceraMano | TerceraMano/src/main/java/com/ceti/terceramano/Object1.java | 3924 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ceti.terceramano;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author USUARIO
*/
@Entity
@Table(name = "object")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Object1.findAll", query = "SELECT o FROM Object1 o")
, @NamedQuery(name = "Object1.findByIdobject", query = "SELECT o FROM Object1 o WHERE o.idobject = :idobject")
, @NamedQuery(name = "Object1.findByNameObject", query = "SELECT o FROM Object1 o WHERE o.nameObject = :nameObject")
, @NamedQuery(name = "Object1.findByNewOwner", query = "SELECT o FROM Object1 o WHERE o.newOwner = :newOwner")
, @NamedQuery(name = "Object1.findByOrgOwner", query = "SELECT o FROM Object1 o WHERE o.orgOwner = :orgOwner")})
public class Object1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private Integer idobject;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "name_object")
private String nameObject;
@Basic(optional = false)
@NotNull
@Lob
@Size(min = 1, max = 65535)
private String description;
@Column(name = "new_owner")
private Integer newOwner;
@Basic(optional = false)
@NotNull
@Column(name = "org_owner")
private int orgOwner;
public Object1() {
}
public Object1(Integer idobject) {
this.idobject = idobject;
}
public Object1(Integer idobject, String nameObject, String description, int orgOwner) {
this.idobject = idobject;
this.nameObject = nameObject;
this.description = description;
this.orgOwner = orgOwner;
}
public Integer getIdobject() {
return idobject;
}
public void setIdobject(Integer idobject) {
this.idobject = idobject;
}
public String getNameObject() {
return nameObject;
}
public void setNameObject(String nameObject) {
this.nameObject = nameObject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getNewOwner() {
return newOwner;
}
public void setNewOwner(Integer newOwner) {
this.newOwner = newOwner;
}
public int getOrgOwner() {
return orgOwner;
}
public void setOrgOwner(int orgOwner) {
this.orgOwner = orgOwner;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idobject != null ? idobject.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Object1)) {
return false;
}
Object1 other = (Object1) object;
if ((this.idobject == null && other.idobject != null) || (this.idobject != null && !this.idobject.equals(other.idobject))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.ceti.terceramano.Object1[ idobject=" + idobject + " ]";
}
}
| unlicense |
pepe1914/jfx-zoglpipeline | src-zogl1/com/sun/prism/zogl/natif/es2defs/DrawableInfoRec.java | 649 | /* DrawableInfoRec.java */
package com.sun.prism.zogl.natif.es2defs;
/**
* This class is only used for the GLDrawable.<br>
* Define the structure to hold the resources and properties of drawable.<br>
* Not really used actually, only reference(Can be removed).<br>
*
* @author ZZZ. No copyright(c). Public Domain.
*/
//public
abstract class DrawableInfoRec extends ZNativeRec {
//jboolean onScreen;
//HDC hdc;
//HWND hwnd;
//EGLDisplay *egldisplay;
//EGLSurface eglsurface;
//Display *display;
//Window win;
//jlong win;
/**
* Create a new instance.
*/
protected DrawableInfoRec() {
}
}
| unlicense |
dkandalov/katas | java/src/main/java/katas/java/lambdabehave/HelloSpec.java | 486 | package katas.java.lambdabehave;
import com.insightfullogic.lambdabehave.JunitSuiteRunner;
import com.insightfullogic.lambdabehave.Suite;
import org.junit.runner.RunWith;
import katas.java.skiplist.SkipList0;
@RunWith(JunitSuiteRunner.class)
@SuppressWarnings("ClassInitializerMayBeStatic")
public class HelloSpec {{
Suite.describe("skip list", it -> {
it.should("have size", expect -> {
expect.that(new SkipList0().isEmpty()).is(true);
});
});
}}
| unlicense |
Parker8283/ThaumcraftMobAspects | src/main/java/iguanaman/thaumcraftmobaspects/UpdateChecker.java | 3438 | package iguanaman.thaumcraftmobaspects;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraftforge.common.MinecraftForge;
import com.google.gson.stream.JsonReader;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent;
public class UpdateChecker {
public static UpdateChecker instance = new UpdateChecker();
public enum Result {
UNINITIALIZED(0),
CURRENT(1),
OUTDATED(2),
ERRORED(3),
DISABLED(4),
DEV_VERSION(5);
private int code;
private Result (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
private static final String VERSION_JSON_URL = "https://raw.githubusercontent.com/Parker8283/ThaumcraftMobAspects/master/version.json";
public static Result runUpdateCheck() {
String modver = ModInfo.VERSION;
String mcver = MinecraftForge.MC_VERSION;
if(modver.equals("@MOD_VERSION@")) {
return Result.DEV_VERSION;
} else if(!ModInfo.IS_RELEASE) {
return Result.DISABLED;
}
JsonReader reader = null;
try {
URL remoteJsonFile = new URL(VERSION_JSON_URL);
URLConnection con = remoteJsonFile.openConnection();
con.setConnectTimeout(1000);
con.setReadTimeout(1000);
InputStream is = con.getInputStream();
reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.beginArray();
while(reader.hasNext()) {
reader.beginObject();
while(reader.hasNext()) {
String name = reader.nextName();
if(name.equalsIgnoreCase("minecraft")) {
if(reader.nextString().equals(mcver)) {
name = reader.nextName();
if(name.equalsIgnoreCase("version")) {
String readver = reader.nextString();
if(!readver.equals(modver)) {
return Result.OUTDATED;
} else {
return Result.CURRENT;
}
} else {
reader.skipValue();
}
} else {
continue;
}
} else {
reader.skipValue();
}
}
reader.endObject();
}
reader.endArray();
} catch(Exception e) {
IguanaLog.log.error("There was an error in the version checker");
e.printStackTrace();
} finally {
try {
if(reader != null) {
reader.close();
}
} catch(IOException e) {
IguanaLog.log.error("There was an error in closing the JSON reader in the update checker");
e.printStackTrace();
}
}
return Result.ERRORED;
}
public class UpdaterEventHook {
@SubscribeEvent
public void onPlayerLogin(PlayerLoggedInEvent event) {
if(ThaumcraftMobAspects.instance.result != Result.CURRENT) {
if(ThaumcraftMobAspects.instance.result == Result.DEV_VERSION) {
IguanaLog.log.info("You are running a dev copy of the mod. Update Checker Disabled.");
} else if(ThaumcraftMobAspects.instance.result == Result.DISABLED) {
IguanaLog.log.info("The update checker has been disabled because you're running a snapshot.");
} else if(ThaumcraftMobAspects.instance.result == Result.OUTDATED) {
event.player.addChatMessage(new ChatComponentTranslation("msg.updater.outdated"));
} else {
IguanaLog.log.error("There was an error in checking for updates.");
}
} else {
IguanaLog.log.info("Your copy of Thaumcraft Mob Aspects is up to date.");
}
}
}
}
| unlicense |
picodotdev/blog-ejemplos | SpringBootJaxrsOauth/src/main/java/io/github/picodotdev/blogbitix/springbootjaxrsoauth/MessageResource.java | 571 | package io.github.picodotdev.blogbitix.springbootjaxrsoauth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Component
@Path("/message")
public class MessageResource {
@Autowired
private MessageService messageService;
@GET
@Produces("application/json")
public Message message(@QueryParam("message") String message) {
return messageService.create(message);
}
} | unlicense |
litesoft/LiteSoftLocales | src/org/litesoft/locales/server/CollectingSupplierUpdateProcessor.java | 2898 | package org.litesoft.locales.server;
import org.litesoft.commonfoundation.console.*;
import org.litesoft.commonfoundation.exceptions.*;
import org.litesoft.commonfoundation.indent.*;
import org.litesoft.commonfoundation.typeutils.*;
import org.litesoft.locales.shared.tables.*;
import java.util.*;
public abstract class CollectingSupplierUpdateProcessor implements SupplierUpdateProcessor {
protected final LocalizationSupplier mSupplier;
protected final Console mConsole;
protected final ConsoleIndentableWriter mWriter;
protected final LocaleFileUtils.Paths mLocaleFiles;
public CollectingSupplierUpdateProcessor( LocalizationSupplier pSupplier, Console pConsole, LocaleFileUtils.Paths pLocaleFiles ) {
mSupplier = pSupplier;
mWriter = new ConsoleIndentableWriter( mConsole = pConsole );
mLocaleFiles = pLocaleFiles.with( new OurLocaleExceptionHandler() );
}
protected void dumpAdditionalIssues() {
}
protected void dump( ListIndentableWriter pCollection, String pLabel ) {
pCollection.close();
List<String> zLines = pCollection.getLines();
if ( !zLines.isEmpty() ) {
mWriter.printLn( pLabel + ":" );
mWriter.indent();
for ( String zLine : zLines ) {
mWriter.printLn( zLine );
}
mWriter.outdent();
}
}
private class OurLocaleExceptionHandler implements LocaleExceptionHandler {
private final ListIndentableWriter mMalformed = new ListIndentableWriter();
private final ListIndentableWriter mDupEntries = new ListIndentableWriter();
private final ListIndentableWriter mErrored = new ListIndentableWriter();
@Override
public boolean handled( int pOffset, String pLine, RuntimeException pRTE ) {
String zReport = "Line[" + pOffset + "]: " + pLine;
return
add( zReport, pRTE instanceof MalformedException, mMalformed, null ) ||
add( zReport, pRTE instanceof DupEntryException, mDupEntries, null ) ||
add( zReport, true, mErrored, pRTE );
}
private boolean add( String pReport, boolean pAdd, ListIndentableWriter pCollector, RuntimeException pRTE ) {
if ( pAdd ) {
if ( pRTE != null ) {
pReport += " | " + pRTE.getMessage();
}
pCollector.printLn( pReport );
return true;
}
return false;
}
@Override
public void completedProcessing( String pPath ) {
mWriter.indent();
dump( mMalformed, "Malformed" );
dump( mDupEntries, "Dup Entries" );
dump( mErrored, "Other Errors" );
dumpAdditionalIssues();
mWriter.outdent();
mWriter.close();
}
}
}
| unlicense |
raywang999/TIJ4 | Chapter7/src/Exercise1.java | 1591 | /*
Create a Cycle class, with subclasses Unicycle, Bicycle and Tricycle. Demonstrate
that an instance of each type can be upcast to Cycle via a ride( ) method.
*/
/*
Exercise 17: (2) Using the Cycle hierarchy from Exercise 1, add a balance( )
method to Unicycle and Bicycle, but not to Tricycle. Create instances of all
three types and upcast them to an array of Cycle. Try to call balance( ) on
each element of the array and observe the results. Downcast and call
balance( ) and observe what happens.
*/
class Cycle{
// protected int wheels;
void pedal(int i){ }
void ride(Cycle c,int i){
c.pedal(10);
System.out.println("Riding a " + c);
int wheels = wheels(i);
System.out.println("wheels : " + wheels);
}
int wheels(int i){
return i;
}
}
class Unicycle extends Cycle{
Unicycle() {
ride(this, 1);
}
void balance(){}
}
class Bicycle extends Cycle{
Bicycle() {
ride(this, 2);
}
void balance(){}
}
class Tricycle extends Cycle{
Tricycle(){
ride(this, 3);
}
}
public class Exercise1 {
public static void main(String[] args){
Unicycle u = new Unicycle();
Bicycle b = new Bicycle();
Tricycle t = new Tricycle();
u.ride(u, 1);
b.ride(b, 2);
t.ride(t, 3);
Cycle[] cycles = {
new Unicycle(),
new Bicycle(),
new Tricycle()
};
((Unicycle)cycles[0]).balance();
((Bicycle)cycles[1]).balance();
//! ((Tricycle)cycles[2]).balance(); //hopeless
}
}
| unlicense |
erdikoch/Dormitory-Management-System-Cs476 | DMS/src/Background/CreditCardPayment.java | 1313 | package background;
import java.util.Date;
public class CreditCardPayment extends Payment {
private String cardName;
private int roomPrice;
private int totalDebt;
private int disbursement;
private Date accomodationTime;
private int remainingDebt;
public int getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(int roomPrice) {
this.roomPrice = roomPrice;
}
public int getTotalDebt() {
return totalDebt;
}
public void setTotalDebt(int totalDebt) {
this.totalDebt = totalDebt;
}
public double getDisbursement() {
return disbursement;
}
public void setDisbursement(int disbursement) {
this.disbursement = disbursement;
}
public Date getAccomodationTime() {
return accomodationTime;
}
public void setAccomodationTime(Date accomodationTime) {
this.accomodationTime = accomodationTime;
}
public void setRemainingDebt(int remainingDebt) {
this.remainingDebt = remainingDebt;
}
public CreditCardPayment() {
this.cardName = "No card name";
}
public CreditCardPayment(String cardName, String expireDate,
String creditCardNum) {
this.cardName = cardName;
}
public void setCardName(String cardName) {
if (!cardName.equals("") || !cardName.equals(" ")) {
this.cardName = cardName;
}
}
public String getCardName() {
return cardName;
}
} | unlicense |
LordNash/Weather-APP | app/src/main/java/teamtreehouse/com/stormy/adapters/HourAdapter.java | 2711 | package teamtreehouse.com.stormy.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import teamtreehouse.com.stormy.R;
import teamtreehouse.com.stormy.weather.Hour;
/**
* Created by Bacha on 7/29/2015.
*/
public class HourAdapter extends RecyclerView.Adapter<HourAdapter.HourViewHolder> {
private Hour[] mHours;
private Context mContext;
public HourAdapter(Context context,Hour[] hours){
mHours = hours;
mContext=context;
}
@Override
public HourViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.hourly_list_item, parent, false);
HourViewHolder viewHolder = new HourViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(HourViewHolder holder, int position) {
holder.bindHour(mHours[position]);
}
@Override
public int getItemCount() {
return mHours.length;
}
public class HourViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mTimeLabel;
public TextView mSummaryLabel;
public TextView mTemperatureLabel;
public ImageView mIconImageView;
public HourViewHolder(View itemView) {
super(itemView);
mTimeLabel=(TextView) itemView.findViewById(R.id.timeLabel);
mSummaryLabel= (TextView) itemView.findViewById(R.id.summaryLabel);
mTemperatureLabel = (TextView) itemView.findViewById(R.id.temperatureLabel);
mIconImageView = (ImageView) itemView.findViewById(R.id.iconImageView);
itemView.setOnClickListener(this);
}
public void bindHour(Hour hour){
mTimeLabel.setText(hour.getHour());
mSummaryLabel.setText(hour.getSummary());
mTemperatureLabel.setText(hour.getTemperature()+"");
mIconImageView.setImageResource(hour.getIconId());
}
@Override
public void onClick(View view) {
String time = mTimeLabel.getText().toString();
String temperature = mTemperatureLabel.getText().toString();
String summary = mSummaryLabel.getText().toString();
String message = String.format("At %s it will be %s and %s",
time,temperature,summary);
Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
}
}
}
| unlicense |
vthriller/opensymphony-compass-backup | src/main/src/org/compass/needle/coherence/DefaultCoherenceLockFactory.java | 2528 | /*
* Copyright 2004-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.compass.needle.coherence;
import java.io.IOException;
import com.tangosol.net.NamedCache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.store.Lock;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.LockObtainFailedException;
/**
* A locak factory using.
*
* @author kimchy
*/
public class DefaultCoherenceLockFactory extends LockFactory {
private static final Log log = LogFactory.getLog(DefaultCoherenceLockFactory.class);
private NamedCache cache;
private String indexName;
public DefaultCoherenceLockFactory(NamedCache cache, String indexName) {
this.cache = cache;
this.indexName = indexName;
}
public void clearLock(String lockName) throws IOException {
cache.unlock(new FileLockKey(indexName, lockName));
}
public Lock makeLock(String lockName) {
return new CoherenceLock(lockName);
}
public class CoherenceLock extends Lock {
private FileLockKey fileLock;
public CoherenceLock(String lockName) {
this.fileLock = new FileLockKey(indexName, lockName);
}
public boolean isLocked() {
// TOOD how to we really check if something is locked?
return false;
}
public boolean obtain() throws IOException {
return cache.lock(fileLock);
}
public boolean obtain(long lockWaitTimeout) throws LockObtainFailedException, IOException {
return cache.lock(fileLock, lockWaitTimeout);
}
public void release() {
try {
cache.unlock(fileLock);
} catch (Exception e) {
if (log.isWarnEnabled()) {
log.warn("Failed to release locke on index [" + indexName + "]", e);
}
}
}
}
} | apache-2.0 |
codders/k2-sling-fork | bundles/servlets/resolver/src/main/java/org/apache/sling/servlets/resolver/internal/defaults/DefaultServlet.java | 2136 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.servlets.resolver.internal.defaults;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
/**
* The <code>DefaultServlet</code> is a very simple default resource handler.
* <p>
* The default servlet is not registered to handle any concrete resource type.
* Rather it is used internally on demand.
*/
public class DefaultServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
Resource resource = request.getResource();
// cannot handle the request for missing resources
if (resource instanceof NonExistingResource) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
"Resource not found at path " + resource.getPath());
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Cannot find servlet to handle resource " + resource.getPath());
}
}
}
| apache-2.0 |
AndroidBase/DrawableView | library/src/main/java/me/panavtec/drawableview/internal/SerializablePath.java | 1697 | package me.panavtec.drawableview.internal;
import android.graphics.Path;
import java.io.Serializable;
import java.util.ArrayList;
public class SerializablePath extends Path implements Serializable {
private ArrayList<float[]> pathPoints;
private int color;
private float width;
public SerializablePath() {
super();
pathPoints = new ArrayList<>();
}
public SerializablePath(SerializablePath p) {
super(p);
pathPoints = p.pathPoints;
}
public void addPathPoints(float[] points) {
this.pathPoints.add(points);
}
public void saveMoveTo(float x, float y) {
super.moveTo(x, y);
addPathPoints(new float[]{x, y});
}
public void saveLineTo(float x, float y) {
super.lineTo(x, y);
addPathPoints(new float[]{x, y});
}
public void saveReset() {
super.reset();
pathPoints.clear();
}
public void savePoint() {
if (pathPoints.size() > 0) {
float[] points = pathPoints.get(0);
saveLineTo(points[0] + 1, points[1] + 1);
}
}
public void loadPathPointsAsQuadTo() {
float[] initPoints = pathPoints.get(0);
this.moveTo(initPoints[0], initPoints[1]);
for (int j = 1 ; j < pathPoints.size() ; j++) {
float[] pointSet = pathPoints.get(j);
this.lineTo(pointSet[0], pointSet[1]);
}
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
}
| apache-2.0 |
AndroidWXH/coolweather | app/src/main/java/com/coolweather/android/ChooseAreaFragment.java | 8343 | package com.coolweather.android;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;
import com.coolweather.android.util.HttpUtil;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by wang on 2017/6/13.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE=0;
public static final int LEVEL_CITY=1;
public static final int LEVEL_COUNTY=2;
private TextView tvTitle;
private ListView listView;
private Button backBtn;
private ProgressDialog progressDialog;
private List<String> dataList=new ArrayList<>();
private List<Province> provinceList;
private List<City> cityList;
private List<County> countyList;
private int currentLevel;
private ArrayAdapter<String> adapter;
private Province selectProvince;
private City selectCity;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.choose_area_frag,container,false);
tvTitle= (TextView) view.findViewById(R.id.tv_title);
backBtn=(Button)view.findViewById(R.id.btn_back);
listView=(ListView)view.findViewById(R.id.list_view);
adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (currentLevel==LEVEL_PROVINCE){
selectProvince=provinceList.get(i);
queryCities();
}else if (currentLevel==LEVEL_CITY){
selectCity =cityList.get(i);
queryCounties();
}else if(currentLevel==LEVEL_COUNTY){
String weatherId=countyList.get(i).getWeatherId();
if (getActivity() instanceof MainActivity){
Intent intent=new Intent(getActivity(),WeatherActivity.class);
intent.putExtra("weather_id",weatherId);
startActivity(intent);
getActivity().finish();
}else if (getActivity() instanceof WeatherActivity){
WeatherActivity activity=(WeatherActivity) getActivity();
activity.drawerLayout.closeDrawer(Gravity.START);
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentLevel==LEVEL_CITY){
queryProvinces();
}else if (currentLevel==LEVEL_COUNTY){
queryCities();
}
}
});
queryProvinces();
}
private void queryProvinces(){
tvTitle.setText("中国");
backBtn.setVisibility(View.GONE);
provinceList= DataSupport.findAll(Province.class);
if (provinceList.size()>0){
dataList.clear();
for (Province province:provinceList){
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel=LEVEL_PROVINCE;
}else {
String address="http://guolin.tech/api/china";
queryFromServer(address,"province");
}
}
private void queryCities(){
tvTitle.setText(selectProvince.getProvinceName());
backBtn.setVisibility(View.VISIBLE);
cityList=DataSupport.where("provinceid=?",String.valueOf(selectProvince.getId())).find(City.class);
if (cityList.size()>0){
dataList.clear();
for (City city:cityList){
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel=LEVEL_CITY;
}else {
String address="http://guolin.tech/api/china/"+selectProvince.getProvinceCode();
queryFromServer(address,"city");
}
}
private void queryCounties(){
tvTitle.setText(selectCity.getCityName());
backBtn.setVisibility(View.VISIBLE);
countyList=DataSupport.where("cityid=?",String.valueOf(selectCity.getId())).find(County.class);
if (countyList.size()>0){
dataList.clear();
for (County county:countyList){
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel=LEVEL_COUNTY;
}else{
String address="http://guolin.tech/api/china/"+selectProvince.getProvinceCode()+"/"+
selectCity.getCityCode();
queryFromServer(address,"county");
}
}
private void queryFromServer(String address, final String type){
showProgressDialog();
HttpUtil.sendOKHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseTest=response.body().string();
boolean result=false;
if ("province".equals(type)){
result=HttpUtil.handleProvinceResponse(responseTest);
}else if ("city".equals(type)){
result=HttpUtil.handleCityResponse(responseTest,selectProvince.getId());
}else if ("county".equals(type)){
result=HttpUtil.handleCountyResponse(responseTest, selectCity.getId());
}
if (result){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if ("province".equals(type)){
queryProvinces();
}else if ("city".equals(type)){
queryCities();
}else if ("county".equals(type)){
queryCounties();
}
closeProgressDialog();
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getActivity(),"加载失败!",Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void showProgressDialog(){
if (progressDialog==null){
progressDialog=new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
private void closeProgressDialog(){
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
| apache-2.0 |
nihaooo/ZhinengGuanjia | app/src/main/java/explame/com/imooctestone/fragment/WeChatFragment.java | 3902 | package explame.com.imooctestone.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import explame.com.imooctestone.R;
import explame.com.imooctestone.adapter.WeChatAdapter;
import explame.com.imooctestone.entity.WeChatData;
import explame.com.imooctestone.ui.WebViewActivity;
import explame.com.imooctestone.utils.L;
import explame.com.imooctestone.utils.StaticClass;
/*
* 项目名: ImoocTestOne
* 包名: explame.com.imooctestone.fragment
* 时间 2017/5/2.
* 创建者: qzhuorui
* 描述: TODO
*/
public class WeChatFragment extends Fragment {
private ListView mListView;
private List<WeChatData> mList = new ArrayList<>();
//存储title
private List<String> mListTitle = new ArrayList<>();
//存储新闻地址
private List<String> mListUrl = new ArrayList<>();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_wechat, null);
findview(view);
return view;
}
private void findview(View view) {
mListView = (ListView) view.findViewById(R.id.mListView);
//解析接口
String url = "http://v.juhe.cn/weixin/query?key=" + StaticClass.WECHAT_KEY;
RxVolley.get(url, new HttpCallback() {
@Override
public void onSuccess(String t) {
// Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
prasingJson(t);
}
});
//点击事件
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
L.i("position :" + position);
Intent intent = new Intent(getActivity(), WebViewActivity.class);
intent.putExtra("title", mListTitle.get(position));
intent.putExtra("url", mListUrl.get(position));
startActivity(intent);
/**
* intent两种方法传值
*
* Bundle bundle = new Bundle();
* bundle.putString("key","value");
* intent.putExtras(bundle);
*/
}
});
}
private void prasingJson(String t) {
try {
JSONObject jsonObject = new JSONObject(t);
JSONObject jsonresult = jsonObject.getJSONObject("result");
JSONArray jsonList = jsonresult.getJSONArray("list");
for (int i = 0; i < jsonList.length(); i++) {
JSONObject json = (JSONObject) jsonList.get(i);
WeChatData data = new WeChatData();
String title = json.getString("title");
String url = json.getString("url");
data.setSource(title);
data.setImgUrl(json.getString("firstImg"));
mList.add(data);
//保存信息
mListTitle.add(title);
mListUrl.add(url);
}
WeChatAdapter adapter = new WeChatAdapter(getActivity(), mList);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
omacarena/novaburst.flowcolab | app/modules/account/account.service.client/src/main/org/flowcolab/account/service/client/dto/role/RoleCreateRequest.java | 91 | package org.flowcolab.account.service.client.dto.role;
public class RoleCreateRequest {
}
| apache-2.0 |
vivantech/kc_fixes | src/main/java/org/kuali/kra/protocol/actions/submit/ProtocolSubmitActionRuleBase.java | 8837 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kra.protocol.actions.submit;
import org.apache.commons.lang.StringUtils;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KeyConstants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.protocol.ProtocolDocumentBase;
import org.kuali.kra.rules.ResearchDocumentRuleBase;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.krad.bo.BusinessObject;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.util.GlobalVariables;
import java.util.HashMap;
import java.util.Map;
/**
* Validate a protocol submission to the IRB for review.
*/
/**
* This class...
*/
public abstract class ProtocolSubmitActionRuleBase extends ResearchDocumentRuleBase implements ExecuteProtocolSubmitActionRule {
private static final String MANDATORY = "M";
private ParameterService parameterService;
public boolean processSubmitAction(ProtocolDocumentBase document, ProtocolSubmitAction submitAction) {
boolean isValid = validateSubmissionType(document, submitAction);
isValid &= validateProtocolReviewType(submitAction);
if (StringUtils.isNotBlank(submitAction.getSubmissionTypeCode())
&& StringUtils.isNotBlank(submitAction.getProtocolReviewTypeCode())) {
isValid &= isValidSubmReviewType(submitAction);
}
if (isMandatory()) {
isValid &= validateCommittee(submitAction);
isValid &= validateSchedule(submitAction);
}
isValid &= validateReviewers(submitAction);
isValid &= checkNoSpoofing(submitAction);
return isValid;
}
/**
* If the committee is mandatory, verify that a committee has been selected.
*/
private boolean validateCommittee(ProtocolSubmitAction submitAction) {
boolean valid = true;
if (StringUtils.isBlank(submitAction.getNewCommitteeId())) {
valid = false;
GlobalVariables.getMessageMap().putError(Constants.PROTOCOL_SUBMIT_ACTION_PROPERTY_KEY + ".committeeId",
KeyConstants.ERROR_PROTOCOL_COMMITTEE_NOT_SELECTED);
}
return valid;
}
/**
* If the schedule is mandatory, verify that a schedule has been selected.
*/
private boolean validateSchedule(ProtocolSubmitAction submitAction) {
boolean valid = true;
if (StringUtils.isBlank(submitAction.getNewScheduleId())) {
valid = false;
GlobalVariables.getMessageMap().putError(Constants.PROTOCOL_SUBMIT_ACTION_PROPERTY_KEY + ".scheduleId",
KeyConstants.ERROR_PROTOCOL_SCHEDULE_NOT_SELECTED);
}
return valid;
}
/**
* Validate the Submission Type.
*/
private boolean validateSubmissionType(ProtocolDocumentBase document, ProtocolSubmitAction submitAction) {
boolean isValid = true;
String submissionTypeCode = submitAction.getSubmissionTypeCode();
if (StringUtils.isBlank(submissionTypeCode)) {
// If the user didn't select a submission type, i.e. he/she choose the "select:" option,
// then the Submission Type Code will be "blank".
isValid = false;
GlobalVariables.getMessageMap().putError(Constants.PROTOCOL_SUBMIT_ACTION_PROPERTY_KEY + ".submissionTypeCode",
KeyConstants.ERROR_PROTOCOL_SUBMISSION_TYPE_NOT_SELECTED);
}
else {
isValid = isValidSubmTypeQual(submitAction);
}
return isValid;
}
/**
* Validate the ProtocolBase Review Type.
*/
private boolean validateProtocolReviewType(ProtocolSubmitAction submitAction) {
boolean isValid = true;
String protocolReviewTypeCode = submitAction.getProtocolReviewTypeCode();
if (StringUtils.isBlank(protocolReviewTypeCode)) {
// If the user didn't select a review type, i.e. he/she choose the "select:" option,
// then the ProtocolBase Review Type Code will be "blank".
isValid = false;
GlobalVariables.getMessageMap().putError(Constants.PROTOCOL_SUBMIT_ACTION_PROPERTY_KEY + ".protocolReviewTypeCode",
KeyConstants.ERROR_PROTOCOL_REVIEW_TYPE_NOT_SELECTED);
}
else if (isReviewTypeInvalid(protocolReviewTypeCode)) {
isValid = false;
this.reportError(Constants.PROTOCOL_SUBMIT_ACTION_PROPERTY_KEY + ".protocolReviewTypeCode",
KeyConstants.ERROR_PROTOCOL_REVIEW_TYPE_INVALID, new String[] { protocolReviewTypeCode });
}
return isValid;
}
/**
* Validate the reviewers.
*/
private boolean validateReviewers(ProtocolSubmitAction submitAction) {
boolean isValid = true;
return isValid;
}
/**
*
* This method checks to make sure that the reviewers list submitted is actually the same as that made available for that
* protocol, committee and schedule, i.e. no spoofing of hidden input fields has taken place.
*
* @param submitAction
* @return
*/
public boolean checkNoSpoofing(ProtocolSubmitAction submitAction) {
boolean isValid = true;
return isValid;
}
private boolean isValidSubmReviewType(ProtocolSubmitAction submitAction) {
boolean valid = true;
if (StringUtils.isNotBlank(submitAction.getSubmissionTypeCode())
&& StringUtils.isNotBlank(submitAction.getProtocolReviewTypeCode())) {
}
return valid;
}
private boolean isValidSubmTypeQual(ProtocolSubmitAction submitAction) {
boolean valid = true;
if (StringUtils.isNotBlank(submitAction.getSubmissionTypeCode())) {
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put("submissionTypeCode", submitAction.getSubmissionTypeCode());
}
return valid;
}
protected abstract Class<? extends ProtocolSubmissionTypeBase> getProtocolSubmissionTypeClassHook();
private boolean isReviewTypeInvalid(String reviewTypeCode) {
return !existsUnique(getProtocolReviewTypeClassHook(), "reviewTypeCode", reviewTypeCode);
}
protected abstract Class<? extends ProtocolReviewTypeBase> getProtocolReviewTypeClassHook();
/**
* Returns true if exactly one instance of a given business object type exists in the Database; false otherwise.
*
* @param boType
* @param propertyName the name of the BO field to query
* @param keyField the field to test against.
* @return true if one object exists; false if no objects or more than one are found
*/
private boolean existsUnique(Class<? extends BusinessObject> boType, String propertyName, String keyField) {
if (keyField != null) {
BusinessObjectService businessObjectService = KraServiceLocator.getService(BusinessObjectService.class);
Map<String, String> fieldValues = new HashMap<String, String>();
fieldValues.put(propertyName, keyField);
if (businessObjectService.countMatching(boType, fieldValues) == 1) {
return true;
}
}
return false;
}
/**
* Is it mandatory for the submission to contain the committee and schedule?
*
* @return true if mandatory; otherwise false
*/
private boolean isMandatory() {
final String param = this.getParameterService().getParameterValueAsString(getProtocolDocumentClassHook(),
Constants.PARAMETER_IRB_COMM_SELECTION_DURING_SUBMISSION);
return StringUtils.equalsIgnoreCase(MANDATORY, param);
}
protected abstract Class<? extends ProtocolDocumentBase> getProtocolDocumentClassHook();
/**
* Looks up and returns the ParameterService.
*
* @return the parameter service.
*/
protected ParameterService getParameterService() {
if (this.parameterService == null) {
this.parameterService = KraServiceLocator.getService(ParameterService.class);
}
return this.parameterService;
}
}
| apache-2.0 |
ppamorim/ExoPlayer | library/src/main/java/com/google/android/exoplayer/extractor/mp4/Mp4Extractor.java | 17013 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.extractor.mp4;
import com.google.android.exoplayer.extractor.Extractor;
import com.google.android.exoplayer.extractor.ExtractorInput;
import com.google.android.exoplayer.extractor.ExtractorOutput;
import com.google.android.exoplayer.extractor.PositionHolder;
import com.google.android.exoplayer.extractor.SeekMap;
import com.google.android.exoplayer.extractor.TrackOutput;
import com.google.android.exoplayer.extractor.mp4.Atom.ContainerAtom;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.NalUnitUtil;
import com.google.android.exoplayer.util.ParsableByteArray;
import com.google.android.exoplayer.util.Util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* Extracts data from an unfragmented MP4 file.
*/
public final class Mp4Extractor implements Extractor, SeekMap {
// Parser states.
private static final int STATE_AFTER_SEEK = 0;
private static final int STATE_READING_ATOM_HEADER = 1;
private static final int STATE_READING_ATOM_PAYLOAD = 2;
private static final int STATE_READING_SAMPLE = 3;
// Brand stored in the ftyp atom for QuickTime media.
private static final int BRAND_QUICKTIME = Util.getIntegerCodeForString("qt ");
/**
* When seeking within the source, if the offset is greater than or equal to this value (or the
* offset is negative), the source will be reloaded.
*/
private static final long RELOAD_MINIMUM_SEEK_DISTANCE = 256 * 1024;
// Temporary arrays.
private final ParsableByteArray nalStartCode;
private final ParsableByteArray nalLength;
private final ParsableByteArray atomHeader;
private final Stack<ContainerAtom> containerAtoms;
private int parserState;
private int atomType;
private long atomSize;
private int atomHeaderBytesRead;
private ParsableByteArray atomData;
private int sampleSize;
private int sampleBytesWritten;
private int sampleCurrentNalBytesRemaining;
// Extractor outputs.
private ExtractorOutput extractorOutput;
private Mp4Track[] tracks;
private boolean isQuickTime;
public Mp4Extractor() {
atomHeader = new ParsableByteArray(Atom.LONG_HEADER_SIZE);
containerAtoms = new Stack<>();
nalStartCode = new ParsableByteArray(NalUnitUtil.NAL_START_CODE);
nalLength = new ParsableByteArray(4);
enterReadingAtomHeaderState();
}
@Override
public boolean sniff(ExtractorInput input) throws IOException, InterruptedException {
return Sniffer.sniffUnfragmented(input);
}
@Override
public void init(ExtractorOutput output) {
extractorOutput = output;
}
@Override
public void seek() {
containerAtoms.clear();
atomHeaderBytesRead = 0;
sampleBytesWritten = 0;
sampleCurrentNalBytesRemaining = 0;
parserState = STATE_AFTER_SEEK;
}
@Override
public int read(ExtractorInput input, PositionHolder seekPosition)
throws IOException, InterruptedException {
while (true) {
switch (parserState) {
case STATE_AFTER_SEEK:
if (input.getPosition() == 0) {
enterReadingAtomHeaderState();
} else {
parserState = STATE_READING_SAMPLE;
}
break;
case STATE_READING_ATOM_HEADER:
if (!readAtomHeader(input)) {
return RESULT_END_OF_INPUT;
}
break;
case STATE_READING_ATOM_PAYLOAD:
if (readAtomPayload(input, seekPosition)) {
return RESULT_SEEK;
}
break;
default:
return readSample(input, seekPosition);
}
}
}
// SeekMap implementation.
@Override
public boolean isSeekable() {
return true;
}
@Override
public long getPosition(long timeUs) {
long earliestSamplePosition = Long.MAX_VALUE;
for (int trackIndex = 0; trackIndex < tracks.length; trackIndex++) {
TrackSampleTable sampleTable = tracks[trackIndex].sampleTable;
int sampleIndex = sampleTable.getIndexOfEarlierOrEqualSynchronizationSample(timeUs);
if (sampleIndex == TrackSampleTable.NO_SAMPLE) {
// Handle the case where the requested time is before the first synchronization sample.
sampleIndex = sampleTable.getIndexOfLaterOrEqualSynchronizationSample(timeUs);
}
tracks[trackIndex].sampleIndex = sampleIndex;
long offset = sampleTable.offsets[sampleIndex];
if (offset < earliestSamplePosition) {
earliestSamplePosition = offset;
}
}
return earliestSamplePosition;
}
// Private methods.
private void enterReadingAtomHeaderState() {
parserState = STATE_READING_ATOM_HEADER;
atomHeaderBytesRead = 0;
}
private boolean readAtomHeader(ExtractorInput input) throws IOException, InterruptedException {
if (atomHeaderBytesRead == 0) {
// Read the standard length atom header.
if (!input.readFully(atomHeader.data, 0, Atom.HEADER_SIZE, true)) {
return false;
}
atomHeaderBytesRead = Atom.HEADER_SIZE;
atomHeader.setPosition(0);
atomSize = atomHeader.readUnsignedInt();
atomType = atomHeader.readInt();
}
if (atomSize == Atom.LONG_SIZE_PREFIX) {
// Read the extended atom size.
int headerBytesRemaining = Atom.LONG_HEADER_SIZE - Atom.HEADER_SIZE;
input.readFully(atomHeader.data, Atom.HEADER_SIZE, headerBytesRemaining);
atomHeaderBytesRead += headerBytesRemaining;
atomSize = atomHeader.readUnsignedLongToLong();
}
if (shouldParseContainerAtom(atomType)) {
long endPosition = input.getPosition() + atomSize - atomHeaderBytesRead;
containerAtoms.add(new ContainerAtom(atomType, endPosition));
enterReadingAtomHeaderState();
} else if (shouldParseLeafAtom(atomType)) {
// We don't support parsing of leaf atoms that define extended atom sizes, or that have
// lengths greater than Integer.MAX_VALUE.
Assertions.checkState(atomHeaderBytesRead == Atom.HEADER_SIZE);
Assertions.checkState(atomSize <= Integer.MAX_VALUE);
atomData = new ParsableByteArray((int) atomSize);
System.arraycopy(atomHeader.data, 0, atomData.data, 0, Atom.HEADER_SIZE);
parserState = STATE_READING_ATOM_PAYLOAD;
} else {
atomData = null;
parserState = STATE_READING_ATOM_PAYLOAD;
}
return true;
}
/**
* Processes the atom payload. If {@link #atomData} is null and the size is at or above the
* threshold {@link #RELOAD_MINIMUM_SEEK_DISTANCE}, {@code true} is returned and the caller should
* restart loading at the position in {@code positionHolder}. Otherwise, the atom is read/skipped.
*/
private boolean readAtomPayload(ExtractorInput input, PositionHolder positionHolder)
throws IOException, InterruptedException {
long atomPayloadSize = atomSize - atomHeaderBytesRead;
long atomEndPosition = input.getPosition() + atomPayloadSize;
boolean seekRequired = false;
if (atomData != null) {
input.readFully(atomData.data, atomHeaderBytesRead, (int) atomPayloadSize);
if (atomType == Atom.TYPE_ftyp) {
isQuickTime = processFtypAtom(atomData);
} else if (!containerAtoms.isEmpty()) {
containerAtoms.peek().add(new Atom.LeafAtom(atomType, atomData));
}
} else {
// We don't need the data. Skip or seek, depending on how large the atom is.
if (atomPayloadSize < RELOAD_MINIMUM_SEEK_DISTANCE) {
input.skipFully((int) atomPayloadSize);
} else {
positionHolder.position = input.getPosition() + atomPayloadSize;
seekRequired = true;
}
}
while (!containerAtoms.isEmpty() && containerAtoms.peek().endPosition == atomEndPosition) {
Atom.ContainerAtom containerAtom = containerAtoms.pop();
if (containerAtom.type == Atom.TYPE_moov) {
// We've reached the end of the moov atom. Process it and prepare to read samples.
processMoovAtom(containerAtom);
containerAtoms.clear();
parserState = STATE_READING_SAMPLE;
return false;
} else if (!containerAtoms.isEmpty()) {
containerAtoms.peek().add(containerAtom);
}
}
enterReadingAtomHeaderState();
return seekRequired;
}
/**
* Process an ftyp atom to determine whether the media is QuickTime.
*
* @param atomData The ftyp atom data.
* @return True if the media is QuickTime. False otherwise.
*/
private static boolean processFtypAtom(ParsableByteArray atomData) {
atomData.setPosition(Atom.HEADER_SIZE);
int majorBrand = atomData.readInt();
if (majorBrand == BRAND_QUICKTIME) {
return true;
}
atomData.skipBytes(4); // minor_version
while (atomData.bytesLeft() > 0) {
if (atomData.readInt() == BRAND_QUICKTIME) {
return true;
}
}
return false;
}
/** Updates the stored track metadata to reflect the contents of the specified moov atom. */
private void processMoovAtom(ContainerAtom moov) {
List<Mp4Track> tracks = new ArrayList<>();
long earliestSampleOffset = Long.MAX_VALUE;
for (int i = 0; i < moov.containerChildren.size(); i++) {
Atom.ContainerAtom atom = moov.containerChildren.get(i);
if (atom.type != Atom.TYPE_trak) {
continue;
}
Track track = AtomParsers.parseTrak(atom, moov.getLeafAtomOfType(Atom.TYPE_mvhd),
isQuickTime);
if (track == null) {
continue;
}
Atom.ContainerAtom stblAtom = atom.getContainerAtomOfType(Atom.TYPE_mdia)
.getContainerAtomOfType(Atom.TYPE_minf).getContainerAtomOfType(Atom.TYPE_stbl);
TrackSampleTable trackSampleTable = AtomParsers.parseStbl(track, stblAtom);
if (trackSampleTable.sampleCount == 0) {
continue;
}
Mp4Track mp4Track = new Mp4Track(track, trackSampleTable, extractorOutput.track(i));
// Each sample has up to three bytes of overhead for the start code that replaces its length.
// Allow ten source samples per output sample, like the platform extractor.
int maxInputSize = trackSampleTable.maximumSize + 3 * 10;
mp4Track.trackOutput.format(track.mediaFormat.copyWithMaxInputSize(maxInputSize));
tracks.add(mp4Track);
long firstSampleOffset = trackSampleTable.offsets[0];
if (firstSampleOffset < earliestSampleOffset) {
earliestSampleOffset = firstSampleOffset;
}
}
this.tracks = tracks.toArray(new Mp4Track[0]);
extractorOutput.endTracks();
extractorOutput.seekMap(this);
}
/**
* Attempts to extract the next sample in the current mdat atom for the specified track.
* <p>
* Returns {@link #RESULT_SEEK} if the source should be reloaded from the position in
* {@code positionHolder}.
* <p>
* Returns {@link #RESULT_END_OF_INPUT} if no samples are left. Otherwise, returns
* {@link #RESULT_CONTINUE}.
*
* @param input The {@link ExtractorInput} from which to read data.
* @param positionHolder If {@link #RESULT_SEEK} is returned, this holder is updated to hold the
* position of the required data.
* @return One of the {@code RESULT_*} flags in {@link Extractor}.
* @throws IOException If an error occurs reading from the input.
* @throws InterruptedException If the thread is interrupted.
*/
private int readSample(ExtractorInput input, PositionHolder positionHolder)
throws IOException, InterruptedException {
int trackIndex = getTrackIndexOfEarliestCurrentSample();
if (trackIndex == TrackSampleTable.NO_SAMPLE) {
return RESULT_END_OF_INPUT;
}
Mp4Track track = tracks[trackIndex];
TrackOutput trackOutput = track.trackOutput;
int sampleIndex = track.sampleIndex;
long position = track.sampleTable.offsets[sampleIndex];
long skipAmount = position - input.getPosition() + sampleBytesWritten;
if (skipAmount < 0 || skipAmount >= RELOAD_MINIMUM_SEEK_DISTANCE) {
positionHolder.position = position;
return RESULT_SEEK;
}
input.skipFully((int) skipAmount);
sampleSize = track.sampleTable.sizes[sampleIndex];
if (track.track.nalUnitLengthFieldLength != -1) {
// Zero the top three bytes of the array that we'll use to parse nal unit lengths, in case
// they're only 1 or 2 bytes long.
byte[] nalLengthData = nalLength.data;
nalLengthData[0] = 0;
nalLengthData[1] = 0;
nalLengthData[2] = 0;
int nalUnitLengthFieldLength = track.track.nalUnitLengthFieldLength;
int nalUnitLengthFieldLengthDiff = 4 - track.track.nalUnitLengthFieldLength;
// NAL units are length delimited, but the decoder requires start code delimited units.
// Loop until we've written the sample to the track output, replacing length delimiters with
// start codes as we encounter them.
while (sampleBytesWritten < sampleSize) {
if (sampleCurrentNalBytesRemaining == 0) {
// Read the NAL length so that we know where we find the next one.
input.readFully(nalLength.data, nalUnitLengthFieldLengthDiff, nalUnitLengthFieldLength);
nalLength.setPosition(0);
sampleCurrentNalBytesRemaining = nalLength.readUnsignedIntToInt();
// Write a start code for the current NAL unit.
nalStartCode.setPosition(0);
trackOutput.sampleData(nalStartCode, 4);
sampleBytesWritten += 4;
sampleSize += nalUnitLengthFieldLengthDiff;
} else {
// Write the payload of the NAL unit.
int writtenBytes = trackOutput.sampleData(input, sampleCurrentNalBytesRemaining, false);
sampleBytesWritten += writtenBytes;
sampleCurrentNalBytesRemaining -= writtenBytes;
}
}
} else {
while (sampleBytesWritten < sampleSize) {
int writtenBytes = trackOutput.sampleData(input, sampleSize - sampleBytesWritten, false);
sampleBytesWritten += writtenBytes;
sampleCurrentNalBytesRemaining -= writtenBytes;
}
}
trackOutput.sampleMetadata(track.sampleTable.timestampsUs[sampleIndex],
track.sampleTable.flags[sampleIndex], sampleSize, 0, null);
track.sampleIndex++;
sampleBytesWritten = 0;
sampleCurrentNalBytesRemaining = 0;
return RESULT_CONTINUE;
}
/**
* Returns the index of the track that contains the earliest current sample, or
* {@link TrackSampleTable#NO_SAMPLE} if no samples remain.
*/
private int getTrackIndexOfEarliestCurrentSample() {
int earliestSampleTrackIndex = TrackSampleTable.NO_SAMPLE;
long earliestSampleOffset = Long.MAX_VALUE;
for (int trackIndex = 0; trackIndex < tracks.length; trackIndex++) {
Mp4Track track = tracks[trackIndex];
int sampleIndex = track.sampleIndex;
if (sampleIndex == track.sampleTable.sampleCount) {
continue;
}
long trackSampleOffset = track.sampleTable.offsets[sampleIndex];
if (trackSampleOffset < earliestSampleOffset) {
earliestSampleOffset = trackSampleOffset;
earliestSampleTrackIndex = trackIndex;
}
}
return earliestSampleTrackIndex;
}
/** Returns whether the extractor should parse a leaf atom with type {@code atom}. */
private static boolean shouldParseLeafAtom(int atom) {
return atom == Atom.TYPE_mdhd || atom == Atom.TYPE_mvhd || atom == Atom.TYPE_hdlr
|| atom == Atom.TYPE_stsd || atom == Atom.TYPE_stts || atom == Atom.TYPE_stss
|| atom == Atom.TYPE_ctts || atom == Atom.TYPE_elst || atom == Atom.TYPE_stsc
|| atom == Atom.TYPE_stsz || atom == Atom.TYPE_stco || atom == Atom.TYPE_co64
|| atom == Atom.TYPE_tkhd || atom == Atom.TYPE_ftyp;
}
/** Returns whether the extractor should parse a container atom with type {@code atom}. */
private static boolean shouldParseContainerAtom(int atom) {
return atom == Atom.TYPE_moov || atom == Atom.TYPE_trak || atom == Atom.TYPE_mdia
|| atom == Atom.TYPE_minf || atom == Atom.TYPE_stbl || atom == Atom.TYPE_edts;
}
private static final class Mp4Track {
public final Track track;
public final TrackSampleTable sampleTable;
public final TrackOutput trackOutput;
public int sampleIndex;
public Mp4Track(Track track, TrackSampleTable sampleTable, TrackOutput trackOutput) {
this.track = track;
this.sampleTable = sampleTable;
this.trackOutput = trackOutput;
}
}
}
| apache-2.0 |
paulswithers/openlogjava | OpenLogOSGi/com.paulwithers.openLog/src/com/paulwithers/openLog/el/StarterValueBinding.java | 2034 | package com.paulwithers.openLog.el;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.PropertyNotFoundException;
import com.ibm.xsp.binding.ValueBindingEx;
public class StarterValueBinding extends ValueBindingEx {
private String _expression;
public StarterValueBinding() {
super();
}
public StarterValueBinding(String expression) {
super();
_expression = expression;
}
@Override
public Class<?> getType(FacesContext arg0) throws EvaluationException, PropertyNotFoundException {
// TODO Insert your code that would determine the class to be returned
// In this sample, we'll just always return a string
return String.class;
}
@Override
public Object getValue(FacesContext arg0) throws EvaluationException, PropertyNotFoundException {
// TODO Insert your code that would generate the value to return
// In this sample, we simply reflect the original expression...
return _expression;
}
@Override
public boolean isReadOnly(FacesContext arg0) throws EvaluationException, PropertyNotFoundException {
// TODO Insert your code that determines whether the binding is readonly.
// In this sample, we are always readonly
return true;
}
@Override
public void setValue(FacesContext arg0, Object arg1) throws EvaluationException, PropertyNotFoundException {
// TODO Insert your code that does whatever you want from an active set on the value
// In this sample, we do nothing
}
@Override
public Object saveState(FacesContext paramFacesContext) {
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = super.saveState(paramFacesContext);
arrayOfObject[1] = this._expression;
return arrayOfObject;
}
@Override
public void restoreState(FacesContext paramFacesContext, Object paramObject) {
Object[] arrayOfObject = (Object[]) paramObject;
super.restoreState(paramFacesContext, arrayOfObject[0]);
this._expression = ((String) arrayOfObject[1]);
}
}
| apache-2.0 |
openmg/metagraph-driver-java | src/main/java/io/metagraph/driver/Graph.java | 3766 | package io.metagraph.driver;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* graph.
* Created by (zhaoliang@metagraph.io) on (17-2-7).
*/
public class Graph {
public static final Logger logger = LoggerFactory.getLogger(Graph.class);
private Strategies strategy = Strategies.standard;
private String host;
private String graphId;
private String requestUrl;
private String token;
private String format = "/graphs/%s/traversal";
public Graph(String host, String graphId, String token) {
this.host = host;
this.graphId = graphId;
this.token = token;
this.requestUrl = format(this.graphId);
}
/**
* execute gremlin script in remote graph cluster.
*
* @param gremlinScript for example : g.V().hasLabel('person')
* @param mode tp or ap
*/
public String gremlin(String gremlinScript, String mode) throws IOException {
String resultJson = Request.Get(requestUrl + "?gremlin=" + gremlinScript + "&mode=" + mode)
.addHeader("content-type", "application/json").addHeader("Authenticate", token)
.connectTimeout(1000 * 30)
.socketTimeout(1000 * 30)
.execute()
.returnContent()
.asString();
logger.info("[gremlin][GET: /graphs/graphId/traversal] parameter gremlinScript={}, mode={},graphId={}; result is {}", gremlinScript, mode, graphId, resultJson);
// TODO: 17-2-15 convert graphSon to Object.
return resultJson;
}
/**
* execute traversal in remote graph cluster.
*
* @param json :
* {
* "request_id": {
* "@type": "g:UUID",
* "@value": "id"
* },
* "op": "bytecode",
* "processor": "traversal",
* "args": {
* "gremlin": "string of a bytecode",
* "aliases": {
* "g": "standard or bsp"
* }
* }
* }
* @return {
* "request_id": "4f62ff27-aabb-4b8c-85df-44b0a6355870",
* "status": {
* "message": "",
* "code": 200,
* "attributes": {}
* },
* "result": {
* "data": [
* {
* "id": 1,
* "label": "graph",
* "type": "vertex",
* "properties": {
* "name": [
* {
* "id": 0,
* "value": "mg-graph"
* }
* ]
* }
* }
* ],
* "meta": {}
* }
* }
*/
public String traversal(String json) throws IOException {
logger.info("requestURL = {}", requestUrl);
String resultJson = Request.Post(requestUrl).bodyString(json, ContentType.APPLICATION_JSON)
.addHeader("content-type", "application/json").addHeader("Authenticate", token)
.connectTimeout(1000 * 30)
.socketTimeout(1000 * 30)
.execute()
.returnContent()
.asString();
logger.info("[traversal][Post: /graphs/graphId/traversal] parameter json={},graphId={}; result is {}", json, graphId, resultJson);
return resultJson;
}
/**
* the request url of REST.
*
* @param graphId graph id
* @return for example : http://www.company.com/graphs/graphId/traversal
*/
private String format(String graphId) {
return String.format(host + format, graphId);
}
public String getGraphId() {
return graphId;
}
public void setGraphId(String graphId) {
this.graphId = graphId;
}
}
| apache-2.0 |
spiritpeak/MyiBase4J | iBase4J-Common/src/main/java/org/ibase4j/core/support/cache/jedis/JedisTemplate.java | 3235 | package org.ibase4j.core.support.cache.jedis;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.ibase4j.core.util.InstanceUtil;
import org.ibase4j.core.util.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
/**
* @author ShenHuaJie
* @version 2016年5月20日 下午3:19:19
*/
@Component
public class JedisTemplate {
private static final Logger logger = LogManager.getLogger();
private static ShardedJedisPool shardedJedisPool = null;
private static Integer EXPIRE = PropertiesUtil.getInt("redis.expiration");
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
// 获取线程
private ShardedJedis getJedis() {
if (shardedJedisPool == null) {
synchronized (EXPIRE) {
if (shardedJedisPool == null) {
JedisPoolConfig poolConfig = jedisConnectionFactory.getPoolConfig();
JedisShardInfo shardInfo = jedisConnectionFactory.getShardInfo();
List<JedisShardInfo> list = InstanceUtil.newArrayList(shardInfo);
shardedJedisPool = new ShardedJedisPool(poolConfig, list);
}
}
}
return shardedJedisPool.getResource();
}
public <K> K run(String key, Executor<K> executor, Integer... expire) {
ShardedJedis jedis = getJedis();
if (jedis == null) {
return null;
}
try {
K result = executor.execute(jedis);
if (jedis.exists(key)) {
if (expire == null || expire.length == 0) {
jedis.expire(key, EXPIRE);
} else if (expire.length == 1) {
jedis.expire(key, expire[0]);
}
}
return result;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
public <K> K run(byte[] key, Executor<K> executor, Integer... expire) {
ShardedJedis jedis = getJedis();
if (jedis == null) {
return null;
}
try {
K result = executor.execute(jedis);
if (jedis.exists(key)) {
if (expire == null || expire.length == 0) {
jedis.expire(key, EXPIRE);
} else if (expire.length == 1) {
jedis.expire(key, expire[0]);
}
}
return result;
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
}
| apache-2.0 |
mmm2a/game-center | src/com/morgan/server/util/flag/Flags.java | 1765 | package com.morgan.server.util.flag;
import javax.annotation.Nullable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.morgan.server.util.cmdline.CommandLine;
/**
* Global class for maintaining and manipulating flags for a binary.
*
* @author mark@mark-morgan.net (Mark Morgan)
*/
public final class Flags {
private static Flags instance = null;
private final CommandLine commandLine;
private Flags(CommandLine commandLine) {
this.commandLine = Preconditions.checkNotNull(commandLine);
}
/**
* Gets the string representation for the given flag name. If the flag was not set, this
* method returns {@code null}.
*/
@Nullable public String getStringRepresentationFor(String flagName) {
return commandLine.getFlagMap().get(flagName);
}
/**
* Gets the list of arguments that were given to the program.
*/
public ImmutableList<String> getArguments() {
return commandLine.getArguments();
}
/**
* Gets the current instance for the global flags data store. This method cannot be called until
* {@link #initializeWith(CommandLine)} is successfully called.
*/
public static Flags getInstance() {
return Preconditions.checkNotNull(instance);
}
/**
* Initialize the global flags data store with the given input commandline. This method may only
* be called once during an application's lifetime.
*/
public static void initializeWith(CommandLine commandLine) {
Preconditions.checkState(instance == null);
overrideWith(commandLine);
}
@VisibleForTesting public static void overrideWith(CommandLine commandLine) {
instance = new Flags(commandLine);
}
}
| apache-2.0 |
lburgazzoli/spring-boot | spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/mock/mockito/DefinitionsParserTests.java | 9749 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.mock.mockito;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mockito.Answers;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.mock.mockito.example.ExampleExtraInterface;
import org.springframework.boot.test.mock.mockito.example.ExampleService;
import org.springframework.boot.test.mock.mockito.example.ExampleServiceCaller;
import org.springframework.boot.test.mock.mockito.example.RealExampleService;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link DefinitionsParser}.
*
* @author Phillip Webb
*/
public class DefinitionsParserTests {
private DefinitionsParser parser = new DefinitionsParser();
@Test
public void parseSingleMockBean() {
this.parser.parse(SingleMockBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
}
@Test
public void parseRepeatMockBean() {
this.parser.parse(RepeatMockBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMockBeanAttributes() {
this.parser.parse(MockBeanAttributes.class);
assertThat(getDefinitions()).hasSize(1);
MockDefinition definition = getMockDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToMock().resolve()).isEqualTo(ExampleService.class);
assertThat(definition.getExtraInterfaces())
.containsExactly(ExampleExtraInterface.class);
assertThat(definition.getAnswer()).isEqualTo(Answers.RETURNS_SMART_NULLS);
assertThat(definition.isSerializable()).isTrue();
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
assertThat(definition.getQualifier()).isNull();
}
@Test
public void parseMockBeanOnClassAndField() {
this.parser.parse(MockBeanOnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
MockDefinition classDefinition = getMockDefinition(0);
assertThat(classDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(classDefinition.getQualifier()).isNull();
MockDefinition fieldDefinition = getMockDefinition(1);
assertThat(fieldDefinition.getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(MockBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
}
@Test
public void parseMockBeanInferClassToMock() {
this.parser.parse(MockBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
}
@Test
public void parseMockBeanMissingClassToMock() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(MockBeanMissingClassToMock.class))
.withMessageContaining("Unable to deduce type to mock");
}
@Test
public void parseMockBeanMultipleClasses() {
this.parser.parse(MockBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getMockDefinition(0).getTypeToMock().resolve())
.isEqualTo(ExampleService.class);
assertThat(getMockDefinition(1).getTypeToMock().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseMockBeanMultipleClassesWithName() {
assertThatIllegalStateException()
.isThrownBy(
() -> this.parser.parse(MockBeanMultipleClassesWithName.class))
.withMessageContaining(
"The name attribute can only be used when mocking a single class");
}
@Test
public void parseSingleSpyBean() {
this.parser.parse(SingleSpyBean.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
}
@Test
public void parseRepeatSpyBean() {
this.parser.parse(RepeatSpyBean.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanAttributes() {
this.parser.parse(SpyBeanAttributes.class);
assertThat(getDefinitions()).hasSize(1);
SpyDefinition definition = getSpyDefinition(0);
assertThat(definition.getName()).isEqualTo("Name");
assertThat(definition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(definition.getReset()).isEqualTo(MockReset.NONE);
assertThat(definition.getQualifier()).isNull();
}
@Test
public void parseSpyBeanOnClassAndField() {
this.parser.parse(SpyBeanOnClassAndField.class);
assertThat(getDefinitions()).hasSize(2);
SpyDefinition classDefinition = getSpyDefinition(0);
assertThat(classDefinition.getQualifier()).isNull();
assertThat(classDefinition.getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
SpyDefinition fieldDefinition = getSpyDefinition(1);
QualifierDefinition qualifier = QualifierDefinition.forElement(
ReflectionUtils.findField(SpyBeanOnClassAndField.class, "caller"));
assertThat(fieldDefinition.getQualifier()).isNotNull().isEqualTo(qualifier);
assertThat(fieldDefinition.getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanInferClassToMock() {
this.parser.parse(SpyBeanInferClassToMock.class);
assertThat(getDefinitions()).hasSize(1);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
}
@Test
public void parseSpyBeanMissingClassToMock() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(SpyBeanMissingClassToMock.class))
.withMessageContaining("Unable to deduce type to spy");
}
@Test
public void parseSpyBeanMultipleClasses() {
this.parser.parse(SpyBeanMultipleClasses.class);
assertThat(getDefinitions()).hasSize(2);
assertThat(getSpyDefinition(0).getTypeToSpy().resolve())
.isEqualTo(RealExampleService.class);
assertThat(getSpyDefinition(1).getTypeToSpy().resolve())
.isEqualTo(ExampleServiceCaller.class);
}
@Test
public void parseSpyBeanMultipleClassesWithName() {
assertThatIllegalStateException()
.isThrownBy(() -> this.parser.parse(SpyBeanMultipleClassesWithName.class))
.withMessageContaining(
"The name attribute can only be used when spying a single class");
}
private MockDefinition getMockDefinition(int index) {
return (MockDefinition) getDefinitions().get(index);
}
private SpyDefinition getSpyDefinition(int index) {
return (SpyDefinition) getDefinitions().get(index);
}
private List<Definition> getDefinitions() {
return new ArrayList<>(this.parser.getDefinitions());
}
@MockBean(ExampleService.class)
static class SingleMockBean {
}
@MockBeans({ @MockBean(ExampleService.class), @MockBean(ExampleServiceCaller.class) })
static class RepeatMockBean {
}
@MockBean(name = "Name", classes = ExampleService.class,
extraInterfaces = ExampleExtraInterface.class,
answer = Answers.RETURNS_SMART_NULLS, serializable = true,
reset = MockReset.NONE)
static class MockBeanAttributes {
}
@MockBean(ExampleService.class)
static class MockBeanOnClassAndField {
@MockBean(ExampleServiceCaller.class)
@Qualifier("test")
private Object caller;
}
@MockBean({ ExampleService.class, ExampleServiceCaller.class })
static class MockBeanMultipleClasses {
}
@MockBean(name = "name",
classes = { ExampleService.class, ExampleServiceCaller.class })
static class MockBeanMultipleClassesWithName {
}
static class MockBeanInferClassToMock {
@MockBean
private ExampleService exampleService;
}
@MockBean
static class MockBeanMissingClassToMock {
}
@SpyBean(RealExampleService.class)
static class SingleSpyBean {
}
@SpyBeans({ @SpyBean(RealExampleService.class),
@SpyBean(ExampleServiceCaller.class) })
static class RepeatSpyBean {
}
@SpyBean(name = "Name", classes = RealExampleService.class, reset = MockReset.NONE)
static class SpyBeanAttributes {
}
@SpyBean(RealExampleService.class)
static class SpyBeanOnClassAndField {
@SpyBean(ExampleServiceCaller.class)
@Qualifier("test")
private Object caller;
}
@SpyBean({ RealExampleService.class, ExampleServiceCaller.class })
static class SpyBeanMultipleClasses {
}
@SpyBean(name = "name",
classes = { RealExampleService.class, ExampleServiceCaller.class })
static class SpyBeanMultipleClassesWithName {
}
static class SpyBeanInferClassToMock {
@SpyBean
private RealExampleService exampleService;
}
@SpyBean
static class SpyBeanMissingClassToMock {
}
}
| apache-2.0 |
atanasg/file-processing-application | FileProcessingApp/src/main/java/com/atanasg/fileprocessingapp/command/status/CommandSuccessful.java | 1070 | /*
* Copyright (C) 2015 Atanas Gegov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atanasg.fileprocessingapp.command.status;
/**
* {@link CommandSuccessful} objects are the return
* values for successful commands. The method
* getDetailedInformation() from
* the base class returns data (e.g. a value if
* the command reads a value) or other additional
* information.
*
* @author Atanas Gegov
*/
public final class CommandSuccessful extends CommandExecStatus {
public CommandSuccessful() {
super("Command SUCCESSFUL", true);
}
}
| apache-2.0 |
imay/palo | fe/src/main/java/org/apache/doris/analysis/FunctionCallExpr.java | 27207 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.doris.analysis;
import org.apache.doris.catalog.AggregateFunction;
import org.apache.doris.catalog.Catalog;
import org.apache.doris.catalog.Database;
import org.apache.doris.catalog.Function;
import org.apache.doris.catalog.ScalarFunction;
import org.apache.doris.catalog.Type;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.common.ErrorCode;
import org.apache.doris.common.ErrorReport;
import org.apache.doris.mysql.privilege.PrivPredicate;
import org.apache.doris.qe.ConnectContext;
import org.apache.doris.thrift.TAggregateExpr;
import org.apache.doris.thrift.TExprNode;
import org.apache.doris.thrift.TExprNodeType;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
// TODO: for aggregations, we need to unify the code paths for builtins and UDAs.
public class FunctionCallExpr extends Expr {
private static final Logger LOG = LogManager.getLogger(FunctionCallExpr.class);
private FunctionName fnName;
// private BuiltinAggregateFunction.Operator aggOp;
private FunctionParams fnParams;
// check analytic function
private boolean isAnalyticFnCall = false;
// Indicates whether this is a merge aggregation function that should use the merge
// instead of the update symbol. This flag also affects the behavior of
// resetAnalysisState() which is used during expr substitution.
private boolean isMergeAggFn;
private static final ImmutableSet<String> STDDEV_FUNCTION_SET =
new ImmutableSortedSet.Builder(String.CASE_INSENSITIVE_ORDER)
.add("stddev").add("stddev_val").add("stddev_samp")
.add("variance").add("variance_pop").add("variance_pop").add("var_samp").add("var_pop").build();
public void setIsAnalyticFnCall(boolean v) {
isAnalyticFnCall = v;
}
public Function getFn() {
return fn;
}
public FunctionName getFnName() {
return fnName;
}
// only used restore from readFields.
private FunctionCallExpr() {
super();
}
public FunctionCallExpr(String functionName, List<Expr> params) {
this(new FunctionName(functionName), new FunctionParams(false, params));
}
public FunctionCallExpr(FunctionName fnName, List<Expr> params) {
this(fnName, new FunctionParams(false, params));
}
public FunctionCallExpr(String fnName, FunctionParams params) {
this(new FunctionName(fnName), params);
}
public FunctionCallExpr(FunctionName fnName, FunctionParams params) {
this(fnName, params, false);
}
private FunctionCallExpr(
FunctionName fnName, FunctionParams params, boolean isMergeAggFn) {
super();
this.fnName = fnName;
fnParams = params;
this.isMergeAggFn = isMergeAggFn;
if (params.exprs() != null) {
children.addAll(params.exprs());
}
}
// Constructs the same agg function with new params.
public FunctionCallExpr(FunctionCallExpr e, FunctionParams params) {
Preconditions.checkState(e.isAnalyzed);
Preconditions.checkState(e.isAggregateFunction() || e.isAnalyticFnCall);
fnName = e.fnName;
// aggOp = e.aggOp;
isAnalyticFnCall = e.isAnalyticFnCall;
fnParams = params;
// Just inherit the function object from 'e'.
fn = e.fn;
this.isMergeAggFn = e.isMergeAggFn;
if (params.exprs() != null) {
children.addAll(params.exprs());
}
}
protected FunctionCallExpr(FunctionCallExpr other) {
super(other);
fnName = other.fnName;
isAnalyticFnCall = other.isAnalyticFnCall;
// aggOp = other.aggOp;
// fnParams = other.fnParams;
// Clone the params in a way that keeps the children_ and the params.exprs()
// in sync. The children have already been cloned in the super c'tor.
if (other.fnParams.isStar()) {
Preconditions.checkState(children.isEmpty());
fnParams = FunctionParams.createStarParam();
} else {
fnParams = new FunctionParams(other.fnParams.isDistinct(), children);
}
this.isMergeAggFn = other.isMergeAggFn;
fn = other.fn;
}
public boolean isMergeAggFn() {
return isMergeAggFn;
}
@Override
public Expr clone() {
return new FunctionCallExpr(this);
}
@Override
public void resetAnalysisState() {
isAnalyzed = false;
// Resolving merge agg functions after substitution may fail e.g., if the
// intermediate agg type is not the same as the output type. Preserve the original
// fn_ such that analyze() hits the special-case code for merge agg fns that
// handles this case.
if (!isMergeAggFn) {
fn = null;
}
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
FunctionCallExpr o = (FunctionCallExpr) obj;
return /*opcode == o.opcode && aggOp == o.aggOp &&*/ fnName.equals(o.fnName)
&& fnParams.isDistinct() == o.fnParams.isDistinct()
&& fnParams.isStar() == o.fnParams.isStar();
}
@Override
public String toSqlImpl() {
StringBuilder sb = new StringBuilder();
sb.append(fnName).append("(");
if (fnParams.isStar()) {
sb.append("*");
}
if (fnParams.isDistinct()) {
sb.append("DISTINCT ");
}
sb.append(Joiner.on(", ").join(childrenToSql())).append(")");
return sb.toString();
}
@Override
public String debugString() {
return Objects.toStringHelper(this)/*.add("op", aggOp)*/.add("name", fnName).add("isStar",
fnParams.isStar()).add("isDistinct", fnParams.isDistinct()).addValue(
super.debugString()).toString();
}
public FunctionParams getParams() {
return fnParams;
}
public boolean isScalarFunction() {
Preconditions.checkState(fn != null);
return fn instanceof ScalarFunction ;
}
public boolean isAggregateFunction() {
Preconditions.checkState(fn != null);
return fn instanceof AggregateFunction && !isAnalyticFnCall;
}
public boolean isBuiltin() {
Preconditions.checkState(fn != null);
return fn instanceof BuiltinAggregateFunction && !isAnalyticFnCall;
}
/**
* Returns true if this is a call to an aggregate function that returns
* non-null on an empty input (e.g. count).
*/
public boolean returnsNonNullOnEmpty() {
Preconditions.checkNotNull(fn);
return fn instanceof AggregateFunction
&& ((AggregateFunction) fn).returnsNonNullOnEmpty();
// && !isAnalyticFnCall
// && ((BuiltinAggregateFunction) fn).op().returnsNonNullOnEmpty();
}
public boolean isDistinct() {
Preconditions.checkState(isAggregateFunction());
return fnParams.isDistinct();
}
public boolean isCountStar() {
if (fnName.getFunction().equalsIgnoreCase("count")) {
if (fnParams.isStar()) {
return true;
} else if (fnParams.exprs() == null || fnParams.exprs().isEmpty()) {
return true;
} else {
for (Expr expr : fnParams.exprs()) {
if (expr.isConstant()) {
return true;
}
}
}
}
return false;
}
// public BuiltinAggregateFunction.Operator getAggOp() {
// return aggOp;
// }
@Override
protected void toThrift(TExprNode msg) {
// TODO: we never serialize this to thrift if it's an aggregate function
// except in test cases that do it explicitly.
if (isAggregate() || isAnalyticFnCall) {
msg.node_type = TExprNodeType.AGG_EXPR;
if (!isAnalyticFnCall) {
msg.setAgg_expr(new TAggregateExpr(isMergeAggFn));
}
} else {
msg.node_type = TExprNodeType.FUNCTION_CALL;
}
}
private void analyzeBuiltinAggFunction(Analyzer analyzer) throws AnalysisException {
if (fnParams.isStar() && !fnName.getFunction().equalsIgnoreCase("count")) {
throw new AnalysisException(
"'*' can only be used in conjunction with COUNT: " + this.toSql());
}
if (fnName.getFunction().equalsIgnoreCase("count")) {
// for multiple exprs count must be qualified with distinct
if (children.size() > 1 && !fnParams.isDistinct()) {
throw new AnalysisException(
"COUNT must have DISTINCT for multiple arguments: " + this.toSql());
}
for (int i = 0; i < children.size(); i++) {
if (children.get(i).type.isHllType()) {
throw new AnalysisException(
"hll only use in HLL_UNION_AGG or HLL_CARDINALITY , HLL_HASH and so on.");
}
}
return;
}
if (fnName.getFunction().equalsIgnoreCase("group_concat")) {
if (children.size() > 2 || children.isEmpty()) {
throw new AnalysisException(
"group_concat requires one or two parameters: " + this.toSql());
}
if (fnParams.isDistinct()) {
throw new AnalysisException("group_concat does not support DISTINCT");
}
Expr arg0 = getChild(0);
if (!arg0.type.isStringType() && !arg0.type.isNull()) {
throw new AnalysisException(
"group_concat requires first parameter to be of type STRING: " + this.toSql());
}
if (arg0.type.isHllType()) {
throw new AnalysisException(
"group_concat requires first parameter can't be of type HLL: " + this.toSql());
}
if (children.size() == 2) {
Expr arg1 = getChild(1);
if (!arg1.type.isStringType() && !arg1.type.isNull()) {
throw new AnalysisException(
"group_concat requires second parameter to be of type STRING: " + this.toSql());
}
if (arg0.type.isHllType()) {
throw new AnalysisException(
"group_concat requires second parameter can't be of type HLL: " + this.toSql());
}
}
return;
}
if (fnName.getFunction().equalsIgnoreCase("lag")
|| fnName.getFunction().equalsIgnoreCase("lead")) {
if (!isAnalyticFnCall) {
new AnalysisException(fnName.getFunction() + " only used in analytic function");
} else {
if (children.size() > 2) {
if (!getChild(2).isConstant()) {
throw new AnalysisException(
"The default parameter (parameter 3) of LAG must be a constant: "
+ this.toSql());
}
}
return;
}
}
if (fnName.getFunction().equalsIgnoreCase("dense_rank")
|| fnName.getFunction().equalsIgnoreCase("rank")
|| fnName.getFunction().equalsIgnoreCase("row_number")
|| fnName.getFunction().equalsIgnoreCase("first_value")
|| fnName.getFunction().equalsIgnoreCase("last_value")
|| fnName.getFunction().equalsIgnoreCase("first_value_rewrite")) {
if (!isAnalyticFnCall) {
new AnalysisException(fnName.getFunction() + " only used in analytic function");
}
}
// Function's arg can't be null for the following functions.
Expr arg = getChild(0);
if (arg == null) {
return;
}
// SUM and AVG cannot be applied to non-numeric types
if (fnName.getFunction().equalsIgnoreCase("sum")
&& ((!arg.type.isNumericType() && !arg.type.isNull()) || arg.type.isHllType())) {
throw new AnalysisException("SUM requires a numeric parameter: " + this.toSql());
}
if (fnName.getFunction().equalsIgnoreCase("sum_distinct")
&& ((!arg.type.isNumericType() && !arg.type.isNull()) || arg.type.isHllType())) {
throw new AnalysisException(
"SUM_DISTINCT requires a numeric parameter: " + this.toSql());
}
if ((fnName.getFunction().equalsIgnoreCase("min")
|| fnName.getFunction().equalsIgnoreCase("max")
|| fnName.getFunction().equalsIgnoreCase("DISTINCT_PC")
|| fnName.getFunction().equalsIgnoreCase("DISTINCT_PCSA")
|| fnName.getFunction().equalsIgnoreCase("NDV"))
&& arg.type.isHllType()) {
throw new AnalysisException(
"hll only use in HLL_UNION_AGG or HLL_CARDINALITY , HLL_HASH and so on.");
}
if ((fnName.getFunction().equalsIgnoreCase("HLL_UNION_AGG")
|| fnName.getFunction().equalsIgnoreCase("HLL_CARDINALITY")
|| fnName.getFunction().equalsIgnoreCase("HLL_RAW_AGG"))
&& !arg.type.isHllType()) {
throw new AnalysisException(
"HLL_UNION_AGG, HLL_RAW_AGG and HLL_CARDINALITY's params must be hll column");
}
if (fnName.getFunction().equalsIgnoreCase("min")
|| fnName.getFunction().equalsIgnoreCase("max")) {
fnParams.setIsDistinct(false); // DISTINCT is meaningless here
} else if (fnName.getFunction().equalsIgnoreCase("DISTINCT_PC")
|| fnName.getFunction().equalsIgnoreCase("DISTINCT_PCSA")
|| fnName.getFunction().equalsIgnoreCase("NDV")
|| fnName.getFunction().equalsIgnoreCase("HLL_UNION_AGG")) {
fnParams.setIsDistinct(false);
}
if (fnName.getFunction().equalsIgnoreCase("percentile_approx")) {
if (children.size() != 2) {
throw new AnalysisException("percentile_approx(expr, DOUBLE) requires two parameters");
}
if (!getChild(1).isConstant()) {
throw new AnalysisException("percentile_approx requires second parameter must be a constant : "
+ this.toSql());
}
}
return;
}
// Provide better error message for some aggregate builtins. These can be
// a bit more user friendly than a generic function not found.
// TODO: should we bother to do this? We could also improve the general
// error messages. For example, listing the alternatives.
protected String getFunctionNotFoundError(Type[] argTypes) {
// Some custom error message for builtins
if (fnParams.isStar()) {
return "'*' can only be used in conjunction with COUNT";
}
if (fnName.getFunction().equalsIgnoreCase("count")) {
if (!fnParams.isDistinct() && argTypes.length > 1) {
return "COUNT must have DISTINCT for multiple arguments: " + toSql();
}
}
if (fnName.getFunction().equalsIgnoreCase("sum")) {
return "SUM requires a numeric parameter: " + toSql();
}
if (fnName.getFunction().equalsIgnoreCase("avg")) {
return "AVG requires a numeric or timestamp parameter: " + toSql();
}
String[] argTypesSql = new String[argTypes.length];
for (int i = 0; i < argTypes.length; ++i) {
argTypesSql[i] = argTypes[i].toSql();
}
return String.format(
"No matching function with signature: %s(%s).",
fnName, fnParams.isStar() ? "*" : Joiner.on(", ").join(argTypesSql));
}
@Override
public void analyzeImpl(Analyzer analyzer) throws AnalysisException {
if (isMergeAggFn) {
// This is the function call expr after splitting up to a merge aggregation.
// The function has already been analyzed so just do the minimal sanity
// check here.
AggregateFunction aggFn = (AggregateFunction) fn;
Preconditions.checkNotNull(aggFn);
Type intermediateType = aggFn.getIntermediateType();
if (intermediateType == null) {
intermediateType = type;
}
// Preconditions.checkState(!type.isWildcardDecimal());
return;
}
if (fnName.getFunction().equals("count") && fnParams.isDistinct()) {
// Treat COUNT(DISTINCT ...) special because of how we do the rewrite.
// There is no version of COUNT() that takes more than 1 argument but after
// the rewrite, we only need count(*).
// TODO: fix how we rewrite count distinct.
fn = getBuiltinFunction(analyzer, fnName.getFunction(), new Type[0],
Function.CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
type = fn.getReturnType();
// Make sure BE doesn't see any TYPE_NULL exprs
for (int i = 0; i < children.size(); ++i) {
if (getChild(i).getType().isNull()) {
uncheckedCastChild(Type.BOOLEAN, i);
}
}
return;
}
Type[] argTypes = new Type[this.children.size()];
for (int i = 0; i < this.children.size(); ++i) {
this.children.get(i).analyze(analyzer);
argTypes[i] = this.children.get(i).getType();
}
analyzeBuiltinAggFunction(analyzer);
if (fnName.getFunction().equalsIgnoreCase("sum")) {
Type type = getChild(0).type.getMaxResolutionType();
fn = getBuiltinFunction(analyzer, fnName.getFunction(), new Type[]{type},
Function.CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
} else if (fnName.getFunction().equalsIgnoreCase("count_distinct")) {
Type compatibleType = this.children.get(0).getType();
for (int i = 1; i < this.children.size(); ++i) {
Type type = this.children.get(i).getType();
compatibleType = Type.getAssignmentCompatibleType(compatibleType, type, true);
if (compatibleType.isInvalid()) {
compatibleType = Type.VARCHAR;
break;
}
}
fn = getBuiltinFunction(analyzer, fnName.getFunction(), new Type[]{compatibleType},
Function.CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
} else {
// now first find function in built-in functions
if (Strings.isNullOrEmpty(fnName.getDb())) {
fn = getBuiltinFunction(analyzer, fnName.getFunction(), collectChildReturnTypes(),
Function.CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
}
// find user defined functions
if (fn == null) {
if (!analyzer.isUDFAllowed()) {
throw new AnalysisException("Does not support non-builtin functions: " + fnName);
}
String dbName = fnName.analyzeDb(analyzer);
if (!Strings.isNullOrEmpty(dbName)) {
// check operation privilege
if (!Catalog.getCurrentCatalog().getAuth().checkDbPriv(
ConnectContext.get(), dbName, PrivPredicate.SELECT)) {
ErrorReport.reportAnalysisException(ErrorCode.ERR_SPECIFIC_ACCESS_DENIED_ERROR, "SELECT");
}
Database db = Catalog.getInstance().getDb(dbName);
if (db != null) {
Function searchDesc = new Function(
fnName, collectChildReturnTypes(), Type.INVALID, false);
fn = db.getFunction(searchDesc, Function.CompareMode.IS_NONSTRICT_SUPERTYPE_OF);
}
}
}
}
if (fn == null) {
LOG.warn("fn {} not exists", fnName.getFunction());
throw new AnalysisException(getFunctionNotFoundError(collectChildReturnTypes()));
}
if (fnName.getFunction().equals("from_unixtime")) {
// if has only one child, it has default time format: yyyy-MM-dd HH:mm:ss.SSSSSS
if (children.size() > 1) {
final StringLiteral formatExpr = (StringLiteral) children.get(1);
final String dateFormat1 = "yyyy-MM-dd HH:mm:ss";
final String dateFormat2 = "yyyy-MM-dd";
if (!formatExpr.getStringValue().equals(dateFormat1)
&& !formatExpr.getStringValue().equals(dateFormat2)) {
throw new AnalysisException(new StringBuilder("format does't support, try ")
.append("'").append(dateFormat1).append("'")
.append(" or ")
.append("'").append(dateFormat2).append("'.").toString());
}
}
}
if (fn.getFunctionName().getFunction().equals("time_diff")) {
fn.getReturnType().getPrimitiveType().setTimeType();
return;
}
if (isAggregateFunction()) {
final String functionName = fnName.getFunction();
// subexprs must not contain aggregates
if (Expr.containsAggregate(children)) {
throw new AnalysisException(
"aggregate function cannot contain aggregate parameters: " + this.toSql());
}
if (STDDEV_FUNCTION_SET.contains(functionName) && argTypes[0].isDateType()) {
throw new AnalysisException("Stddev/variance function do not support Date/Datetime type");
}
if (functionName.equalsIgnoreCase("multi_distinct_sum") && argTypes[0].isDateType()) {
throw new AnalysisException("Sum in multi distinct functions do not support Date/Datetime type");
}
} else {
if (fnParams.isStar()) {
throw new AnalysisException("Cannot pass '*' to scalar function.");
}
if (fnParams.isDistinct()) {
throw new AnalysisException("Cannot pass 'DISTINCT' to scalar function.");
}
}
Type[] args = fn.getArgs();
if (args.length > 0) {
// Implicitly cast all the children to match the function if necessary
for (int i = 0; i < argTypes.length; ++i) {
// For varargs, we must compare with the last type in callArgs.argTypes.
int ix = Math.min(args.length - 1, i);
if (!argTypes[i].matchesType(args[ix]) && !(argTypes[i].isDateType() && args[ix].isDateType())) {
uncheckedCastChild(args[ix], i);
//if (argTypes[i] != args[ix]) castChild(args[ix], i);
}
}
}
this.type = fn.getReturnType();
}
@Override
public boolean isVectorized() {
return false;
}
public static FunctionCallExpr createMergeAggCall(
FunctionCallExpr agg, List<Expr> params) {
Preconditions.checkState(agg.isAnalyzed);
Preconditions.checkState(agg.isAggregateFunction());
FunctionCallExpr result = new FunctionCallExpr(
agg.fnName, new FunctionParams(false, params), true);
// Inherit the function object from 'agg'.
result.fn = agg.fn;
result.type = agg.type;
// Preconditions.checkState(!result.type.isWildcardDecimal());
return result;
}
@Override
public void write(DataOutput out) throws IOException {
fnName.write(out);
fnParams.write(out);
out.writeBoolean(isAnalyticFnCall);
out.writeBoolean(isMergeAggFn);
}
@Override
public void readFields(DataInput in) throws IOException {
fnName = FunctionName.read(in);
fnParams = FunctionParams.read(in);
if (fnParams.exprs() != null) {
children.addAll(fnParams.exprs());
}
isAnalyticFnCall = in.readBoolean();
isMergeAggFn = in.readBoolean();
}
public static FunctionCallExpr read(DataInput in) throws IOException {
FunctionCallExpr func = new FunctionCallExpr();
func.readFields(in);
return func;
}
// Used for store load
public boolean supportSerializable() {
for (Expr child : children) {
if (!child.supportSerializable()) {
return false;
}
}
return true;
}
@Override
protected boolean isConstantImpl() {
// TODO: we can't correctly determine const-ness before analyzing 'fn_'. We should
// rework logic so that we do not call this function on unanalyzed exprs.
// Aggregate functions are never constant.
if (fn instanceof AggregateFunction) return false;
final String fnName = this.fnName.getFunction();
// Non-deterministic functions are never constant.
if (isNondeterministicBuiltinFnName(fnName)) {
return false;
}
// Sleep is a special function for testing.
if (fnName.equalsIgnoreCase("sleep")) return false;
return super.isConstantImpl();
}
static boolean isNondeterministicBuiltinFnName(String fnName) {
if (fnName.equalsIgnoreCase("rand") || fnName.equalsIgnoreCase("random")
|| fnName.equalsIgnoreCase("uuid")) {
return true;
}
return false;
}
}
| apache-2.0 |
huangping40/dubbox | dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/ConsistentHashLoadBalance.java | 5977 | /*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.rpc.cluster.loadbalance;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
/**
* ConsistentHashLoadBalance
*
* @author william.liangf
*/
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
@SuppressWarnings("unchecked")
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
int identityHashCode = System.identityHashCode(invokers);
ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
if (selector == null || selector.getIdentityHashCode() != identityHashCode) {
selectors.put(key, new ConsistentHashSelector<T>(invokers, invocation.getMethodName(), identityHashCode));
selector = (ConsistentHashSelector<T>) selectors.get(key);
}
return selector.select(invocation);
}
private static final class ConsistentHashSelector<T> {
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
public ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
this.identityHashCode = System.identityHashCode(invokers);
URL url = invokers.get(0).getUrl();
this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
argumentIndex = new int[index.length];
for (int i = 0; i < index.length; i ++) {
argumentIndex[i] = Integer.parseInt(index[i]);
}
for (Invoker<T> invoker : invokers) {
for (int i = 0; i < replicaNumber / 4; i++) {
url = invoker.getUrl();
byte[] digest = md5(url.getIp()+"."+url.getPort()+"."+ i);
for (int h = 0; h < 4; h++) {
long m = hash(digest, h);
virtualInvokers.put(m, invoker);
}
}
}
}
public int getIdentityHashCode() {
return identityHashCode;
}
public Invoker<T> select(Invocation invocation) {
String key = toKey(invocation.getArguments());
byte[] digest = md5(key);
Invoker<T> invoker = sekectForKey(hash(digest, 0));
return invoker;
}
private String toKey(Object[] args) {
StringBuilder buf = new StringBuilder();
for (int i : argumentIndex) {
if (i >= 0 && i < args.length) {
buf.append(args[i].hashCode());
}
}
return buf.toString();
}
private Invoker<T> sekectForKey(long hash) {
Invoker<T> invoker;
Long key = hash;
if (!virtualInvokers.containsKey(key)) {
SortedMap<Long, Invoker<T>> tailMap = virtualInvokers.tailMap(key);
if (tailMap.isEmpty()) {
key = virtualInvokers.firstKey();
} else {
key = tailMap.firstKey();
}
}
invoker = virtualInvokers.get(key);
return invoker;
}
private long hash(byte[] digest, int number) {
return (((long) (digest[3 + number * 4] & 0xFF) << 24)
| ((long) (digest[2 + number * 4] & 0xFF) << 16)
| ((long) (digest[1 + number * 4] & 0xFF) << 8)
| (digest[0 + number * 4] & 0xFF))
& 0xFFFFFFFFL;
}
private byte[] md5(String value) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e.getMessage(), e);
}
md5.reset();
byte[] bytes = null;
try {
bytes = value.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
md5.update(bytes);
return md5.digest();
}
}
}
| apache-2.0 |
blstream/TOZ_BE | src/main/java/com/intive/patronage/toz/proposals/ProposalController.java | 5426 | package com.intive.patronage.toz.proposals;
import com.intive.patronage.toz.config.ApiUrl;
import com.intive.patronage.toz.error.exception.WrongProposalRoleException;
import com.intive.patronage.toz.error.model.ErrorResponse;
import com.intive.patronage.toz.error.model.ValidationErrorResponse;
import com.intive.patronage.toz.proposals.model.Proposal;
import com.intive.patronage.toz.proposals.model.ProposalView;
import com.intive.patronage.toz.users.model.db.Role;
import com.intive.patronage.toz.util.ModelMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import static com.intive.patronage.toz.util.ModelMapper.convertIdentifiableToView;
import static com.intive.patronage.toz.util.ModelMapper.convertToView;
@Api(tags = "Proposals", description = "Proposals management operations (CRUD).")
@RestController
@RequestMapping(value = ApiUrl.PROPOSAL_PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class ProposalController {
private final ProposalService proposalService;
@Autowired
ProposalController(ProposalService proposalService) {
this.proposalService = proposalService;
}
@ApiOperation(value = "Get all proposals", responseContainer = "List", notes =
"Required roles: SA, TOZ.")
@GetMapping
@PreAuthorize("hasAnyAuthority('SA', 'TOZ')")
public List<ProposalView> getAllProposals() {
final List<Proposal> proposals = proposalService.findAll();
return convertIdentifiableToView(proposals, ProposalView.class);
}
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "Create new proposal", response = ProposalView.class, notes =
"Required roles: SA, TOZ, ANONYMOUS.")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Bad request", response = ValidationErrorResponse.class)
})
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('SA', 'TOZ', 'ANONYMOUS')")
public ResponseEntity<ProposalView> createProposal(@Valid @RequestBody ProposalView proposalView) {
validateProposalRoles(proposalView);
final Proposal proposal = ModelMapper.convertToModel(proposalView, Proposal.class);
final ProposalView createdProposal = convertToView(proposalService.create(proposal), ProposalView.class);
final URI baseLocation = ServletUriComponentsBuilder.fromCurrentRequest()
.build().toUri();
final String proposalLocationString = String.format("%s/%s", baseLocation, createdProposal.getId());
final URI location = UriComponentsBuilder.fromUriString(proposalLocationString).build().toUri();
return ResponseEntity.created(location).body(createdProposal);
}
@ApiOperation(value = "Update proposal information", response = ProposalView.class, notes =
"Required roles: SA, TOZ.")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Proposal not found", response = ErrorResponse.class),
@ApiResponse(code = 400, message = "Bad request", response = ValidationErrorResponse.class)
})
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAnyAuthority('SA', 'TOZ')")
public ProposalView updateProposal(@PathVariable UUID id, @Valid @RequestBody ProposalView proposalView) {
final Proposal proposal = ModelMapper.convertToModel(proposalView, Proposal.class);
return ModelMapper.convertToView(proposalService.update(id, proposal), ProposalView.class);
}
@ApiOperation(value = "Delete proposal", notes =
"Required roles: SA, TOZ.")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "Proposal not found", response = ErrorResponse.class)
})
@DeleteMapping(value = "/{id}")
@PreAuthorize("hasAnyAuthority('SA', 'TOZ')")
public ResponseEntity<?> deleteProposal(@PathVariable UUID id) {
proposalService.delete(id);
return ResponseEntity.ok().build();
}
private void validateProposalRoles(ProposalView proposalView) {
for (Role role : proposalView.getRoles()) {
if (!role.equals(Role.VOLUNTEER)) {
throw new WrongProposalRoleException();
}
}
}
}
| apache-2.0 |
Talend/data-prep | dataprep-backend-service/src/main/java/org/talend/dataprep/exception/error/PreparationErrorCodes.java | 3206 | // ============================================================================
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// https://github.com/Talend/data-prep/blob/master/LICENSE
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.dataprep.exception.error;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.talend.daikon.exception.error.ErrorCode;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CONFLICT;
import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
/**
* Preparation error codes.
*/
public enum PreparationErrorCodes implements ErrorCode {
PREPARATION_DOES_NOT_EXIST(NOT_FOUND, "id"),
PREPARATION_STEP_DOES_NOT_EXIST(NOT_FOUND, "id", "stepId"),
PREPARATION_STEP_CANNOT_BE_DELETED_IN_SINGLE_MODE(FORBIDDEN, "id", "stepId"),
PREPARATION_STEP_CANNOT_BE_REORDERED(CONFLICT),
PREPARATION_ROOT_STEP_CANNOT_BE_DELETED(FORBIDDEN, "id", "stepId"),
UNABLE_TO_SERVE_PREPARATION_CONTENT(BAD_REQUEST, "id", "version"),
UNABLE_TO_READ_PREPARATION(INTERNAL_SERVER_ERROR, "id", "version"),
PREPARATION_NAME_ALREADY_USED(CONFLICT, "id", "name", "folder"),
PREPARATION_NOT_EMPTY(CONFLICT, "id"),
FORBIDDEN_PREPARATION_CREATION(FORBIDDEN),
PREPARATION_VERSION_DOES_NOT_EXIST(NOT_FOUND, "id", "stepId"),
EXPORTED_PREPARATION_VERSION_NOT_SUPPORTED(BAD_REQUEST),
UNABLE_TO_READ_PREPARATIONS_EXPORT(BAD_REQUEST, "importVersion", "dataPrepVersion"),
PREPARATION_ALREADY_EXIST(CONFLICT, "preparationName"),
INVALID_PREPARATION(BAD_REQUEST, "message");
/** The http status to use. */
private int httpStatus;
/** Expected entries to be in the context. */
private List<String> expectedContextEntries;
/**
* default constructor.
*
* @param httpStatus the http status to use.
* @param contextEntries expected context entries.
*/
PreparationErrorCodes(HttpStatus httpStatus, String... contextEntries) {
this.httpStatus = httpStatus.value();
this.expectedContextEntries = Arrays.asList(contextEntries);
}
/**
* @return the product.
*/
@Override
public String getProduct() {
return "TDP"; //$NON-NLS-1$
}
@Override
public String getGroup() {
return "PS"; //$NON-NLS-1$
}
/**
* @return the http status.
*/
@Override
public int getHttpStatus() {
return httpStatus;
}
/**
* @return the expected context entries.
*/
@Override
public Collection<String> getExpectedContextEntries() {
return expectedContextEntries;
}
@Override
public String getCode() {
return this.toString();
}
}
| apache-2.0 |
MikeWinter/twu-biblioteca-mike-winter | src/com/twu/biblioteca/CatalogueFileLoader.java | 2625 | package com.twu.biblioteca;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOError;
import java.util.Scanner;
class CatalogueFileLoader implements CatalogueLoader {
private final File booksFile;
private final File moviesFile;
private Catalogue<Book> bookCatalogue;
private Catalogue<Movie> movieCatalogue;
private CatalogueFileLoader(File books, File movies) {
booksFile = books;
moviesFile = movies;
}
static CatalogueLoader loadFrom(String path) throws FileNotFoundException {
File books = new File(path, "books");
checkExistsAndReadable(books);
File movies = new File(path, "movies");
checkExistsAndReadable(movies);
return new CatalogueFileLoader(books, movies);
}
private static void checkExistsAndReadable(File file) throws FileNotFoundException {
if (!file.exists() || !file.canRead()) {
throw new FileNotFoundException(file.getAbsolutePath());
}
}
@Override
public synchronized Catalogue<Book> getBookCatalogue() {
if (bookCatalogue == null) {
Catalogue<Book> catalogue = new Catalogue<>();
try (Scanner scanner = new Scanner(booksFile)) {
scanner.useDelimiter("[\t\n]");
while (scanner.hasNext()) {
catalogue.addItem(new Book(scanner.next(), scanner.next(), scanner.next()));
}
} catch (FileNotFoundException e) {
// This should never occur as existence/readability checks have already been performed.
throw new IOError(e);
}
bookCatalogue = catalogue;
}
return bookCatalogue;
}
@Override
public synchronized Catalogue<Movie> getMovieCatalogue() {
if (movieCatalogue == null) {
Catalogue<Movie> catalogue = new Catalogue<>();
try (Scanner scanner = new Scanner(moviesFile)) {
scanner.useDelimiter("[\t\n]");
while (scanner.hasNext()) {
catalogue.addItem(new Movie(
scanner.next(),
scanner.next(),
scanner.next(),
Rating.valueOf(scanner.next())));
}
} catch (FileNotFoundException e) {
// This should never occur as existence/readability checks have already been performed.
throw new IOError(e);
}
movieCatalogue = catalogue;
}
return movieCatalogue;
}
}
| apache-2.0 |
9elephas/alopex | src/main/java/com/ninelephas/alopex/controller/test/TestController.java | 1623 | package com.ninelephas.alopex.controller.test;
import com.ninelephas.alopex.controller.ControllerException;
import com.ninelephas.common.helper.HttpResponseHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @ClassName: TestController
* @Description: 用于测试的MVC Controller
* @author 徐泽宇
* @date 2016年12月2日 下午6:52:03
*
*/
@Log4j2
@Controller("com.ninelephas.alopex.controller.test")
@RequestMapping(value = "/test")
public class TestController {
/**
* Test500ErrorController
*
* @return
*
* @throws ControllerException
* @Auther 徐泽宇
* @Date 2016年11月10日 下午7:18:14
* @Title: Test500ErrorController
* @Description: 抛出一个500的错误
*/
@RequestMapping(value = "/500_error")
@ResponseBody
public String test500ErrorController() throws ControllerException {
throw new ControllerException("抛出一个测试的ControllerException错误");
}
/**
* test500ErrorController
*
* @return
*
* @throws ControllerException
* @Auther 徐泽宇
* @Date 2016年12月12日 下午2:59:53
* @Title: test500ErrorController
* @Description: 调用成功
*/
@RequestMapping(value = "/success", produces = "application/json;charset=utf-8")
@ResponseBody
public String success() throws ControllerException {
return HttpResponseHelper.successInfoInbox("ok");
}
}
| apache-2.0 |
slonikmak/ariADDna | desktop-gui/src/main/java/com/stnetix/ariaddna/desktopgui/views/TreeViewFactory.java | 8207 | package com.stnetix.ariaddna.desktopgui.views;
import com.stnetix.ariaddna.desktopgui.models.FileBrowserElement;
import com.stnetix.ariaddna.desktopgui.models.FileItem;
import com.stnetix.ariaddna.desktopgui.models.FilesRepository;
import com.stnetix.ariaddna.desktopgui.models.FilesRepositoryImpl;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ListChangeListener;
import javafx.css.PseudoClass;
import javafx.scene.control.Button;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import org.controlsfx.control.BreadCrumbBar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* Factory for create TreeView of file and settings items and bread crumb bar
*
* @author slonikmak
*/
@Component
public class TreeViewFactory {
private FilesRepository repository;
//Current treeView element property
private ObjectProperty<TreeView<FileBrowserElement>> currentTreeView = new SimpleObjectProperty<>();
//represent Bread Crumb Bar navigation elem
private BreadCrumbBar<FileBrowserElement> breadCrumbBar;
private TreeView<FileBrowserElement> fileBrowserTreeView;
private TreeView<FileBrowserElement> settingsTreeView;
private TreeItem<FileBrowserElement> selectedTreeItem;
/**
* constructor, init breadCrumbBar and bind it to currentTreeView
* when changed selected tree item the selected crumb bar element will changed to
*/
public TreeViewFactory() {
breadCrumbBar = new BreadCrumbBar<>();
breadCrumbBar.setCrumbFactory(treeItem -> {
FontAwesomeIconView icon = new FontAwesomeIconView(FontAwesomeIcon.ANGLE_RIGHT);
icon.setGlyphSize(20);
String name = treeItem.getValue().getName().equals("root")?"Files":treeItem.getValue().getName();
Button btn = new Button(name);
btn.setGraphic(icon);
return btn;
});
currentTreeView.addListener((observable, oldValue, newValue) -> {
TreeItem<FileBrowserElement> firstElem = newValue.getTreeItem(0);
setSelectedCrumbElem(firstElem);
});
breadCrumbBar.selectedCrumbProperty().addListener((observable, oldValue, newValue) ->
currentTreeView.getValue().getSelectionModel().select(newValue));
}
@PostConstruct
public void setupTreeView() {
repository.getCurrentFiles().addListener((ListChangeListener<FileBrowserElement>) c -> {
loadChildren(getSelectedTreeItem());
});
}
/**
* setup settings TreeView
*/
private void setupSettingsTreeView() {
settingsTreeView = new TreeView<>();
TreeItem<FileBrowserElement> root = new TreeItem<>(new FileItem("Settings"));
TreeItem<FileBrowserElement> outer;
makeBranch(new FileItem("Account"), root);
outer = makeBranch(new FileItem("Clouds"), root);
makeBranch(new FileItem("Dropbox"), outer);
makeBranch(new FileItem("Google Drive"), outer);
makeBranch(new FileItem("Sync"), root);
makeBranch(new FileItem("Encription"), root);
settingsTreeView.setRoot(root);
settingsTreeView.setPrefWidth(200);
setTreeCellFactory(settingsTreeView);
settingsTreeView.getSelectionModel().getSelectedItems().addListener(settingsTreeViewSelectedListener);
settingsTreeView.setShowRoot(false);
}
/**
* setup file browser TreeView
*/
private void setupBrowserTreeView() {
fileBrowserTreeView = new TreeView<>();
TreeItem<FileBrowserElement> root = new TreeItem<>(repository.getCurrentParent());
repository.getCurrentFiles().forEach(fileItem -> makeBranch(fileItem, root));
fileBrowserTreeView.setRoot(root);
fileBrowserTreeView.setPrefWidth(200);
setTreeCellFactory(fileBrowserTreeView);
root.setExpanded(true);
fileBrowserTreeView.getSelectionModel().getSelectedItems().addListener(browserTreeViewSelectedListener);
}
/**
* file browser TreeView selected listener
*/
private ListChangeListener<TreeItem<FileBrowserElement>> browserTreeViewSelectedListener = c -> {
c.next();
TreeItem<FileBrowserElement> selected = c.getList().get(0);
selectedTreeItem = selected;
repository.setCurrentParent(selected.getValue());
setSelectedCrumbElem(selected);
loadChildren(selected);
};
/**
* settings TreeView selected listener
*/
private ListChangeListener<TreeItem<FileBrowserElement>> settingsTreeViewSelectedListener = c -> {
c.next();
TreeItem<FileBrowserElement> selected = c.getList().get(0);
setSelectedCrumbElem(selected);
};
private void loadChildren(TreeItem<FileBrowserElement> treeItem) {
treeItem.getChildren().clear();
repository.getCurrentFiles().forEach(child -> {
if (child.isDirectory()) makeBranch(child, treeItem);
});
}
/**
* Make branch of element in root element
*
* @param element inner element
* @param root root element
* @return new branch
*/
private TreeItem<FileBrowserElement> makeBranch(FileBrowserElement element, TreeItem<FileBrowserElement> root) {
TreeItem<FileBrowserElement> newBranch = new TreeItem<>(element);
root.getChildren().add(newBranch);
return newBranch;
}
/**
* return treeView of file items
*
* @return tree view
*/
public TreeView<FileBrowserElement> getFileBrowserTreeView() {
if (fileBrowserTreeView == null) {
setupBrowserTreeView();
}
currentTreeView.setValue(fileBrowserTreeView);
return fileBrowserTreeView;
}
/**
* select element in bread crumb bar
*
* @param elem selected item
*/
private void setSelectedCrumbElem(TreeItem<FileBrowserElement> elem) {
breadCrumbBar.selectedCrumbProperty().set(elem);
}
/**
* Generate treeView of settings items
*
* @return tree view
*/
public TreeView<FileBrowserElement> getSettingsTreeView() {
if (settingsTreeView == null) {
setupSettingsTreeView();
}
currentTreeView.setValue(settingsTreeView);
return settingsTreeView;
}
/**
* Customizing treeView
*
* @param tree treeView
*/
private void setTreeCellFactory(TreeView<FileBrowserElement> tree) {
PseudoClass firstElementPseudoClass = PseudoClass.getPseudoClass("first-tree-item");
tree.setCellFactory(param -> new TreeCell<FileBrowserElement>() {
@Override
public void updateItem(FileBrowserElement item, boolean empty) {
super.updateItem(item, empty);
//setDisclosureNode(null);
if (empty) {
setText("");
setGraphic(null);
} else {
String name = item.getName();
if (name.equals("root")){
name = "Files";
pseudoClassStateChanged(firstElementPseudoClass, true);
setDisclosureNode(null);
}
setText(name);
}
}
});
tree.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
}
});
}
/**
* @return bread crumb bar
*/
public BreadCrumbBar<FileBrowserElement> getBreadCrumbBar() {
return breadCrumbBar;
}
private TreeItem<FileBrowserElement> getSelectedTreeItem() {
return selectedTreeItem;
}
@Autowired
public void setRepository(FilesRepositoryImpl repository) {
this.repository = repository;
}
}
| apache-2.0 |
petermr/norma | src/test/java/org/xmlcml/norma/demos/package-info.java | 115 | /**
* demo projects (maybe only accessible to PMR)
*/
/**
* @author pm286
*
*/
package org.xmlcml.norma.demos; | apache-2.0 |
kwon37xi/spymemcached-extra-transcoders | fst-transcoder/src/main/java/kr/pe/kwonnam/spymemcached/extratranscoders/fst/FSTTranscoder.java | 2498 | package kr.pe.kwonnam.spymemcached.extratranscoders.fst;
import net.spy.memcached.CachedData;
import net.spy.memcached.transcoders.Transcoder;
import org.nustaq.serialization.FSTConfiguration;
/**
* <a href="http://ruedigermoeller.github.io/fast-serialization/">FST(fast-serialization)</a> based spymemcached transcoder.<br>
*/
public class FSTTranscoder<T> implements Transcoder<T> {
/**
* Default FSTConfiguration.
* <br>
* It requires objects implement {@link java.io.Serializable} or {@link java.io.Externalizable}.
*/
public static final FSTConfigurationFactory DEFAULT_FSTCONFIGURATION_FACTORY = new FSTConfigurationFactory() {
@Override
public FSTConfiguration create() {
return FSTConfiguration.createDefaultConfiguration();
}
};
private final FSTConfigurationFactory fstConfigurationFactory;
private final ThreadLocal<FSTConfiguration> fstConfigurationContainer;
public FSTTranscoder() {
this(DEFAULT_FSTCONFIGURATION_FACTORY);
}
public FSTTranscoder(final FSTConfigurationFactory fstConfigurationFactory) {
this.fstConfigurationFactory = fstConfigurationFactory;
fstConfigurationContainer = new ThreadLocal<FSTConfiguration>() {
@Override
protected FSTConfiguration initialValue() {
return fstConfigurationFactory.create();
}
};
}
/**
* return {@link FSTConfigurationFactory} instance.
*
* @return FSTConfigurationFactory which used by this transcoder to create FSTConfiguration instances.
*/
public FSTConfigurationFactory getFstConfigurationFactory() {
return fstConfigurationFactory;
}
@Override
public CachedData encode(T object) {
final FSTConfiguration fstConfiguration = fstConfigurationContainer.get();
final byte[] serializedBytes = fstConfiguration.asByteArray(object);
return new CachedData(0B0000, serializedBytes, getMaxSize());
}
@Override
public T decode(CachedData cachedData) {
final FSTConfiguration fstConfiguration = fstConfigurationContainer.get();
@SuppressWarnings("unchecked")
final T deserialized = (T) fstConfiguration.asObject(cachedData.getData());
return deserialized;
}
@Override
public boolean asyncDecode(CachedData d) {
return false;
}
@Override
public int getMaxSize() {
return CachedData.MAX_SIZE;
}
} | apache-2.0 |
vespa-engine/vespa | clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/matchers/EventForNode.java | 1164 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core.matchers;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vespa.clustercontroller.core.NodeEvent;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
public class EventForNode extends BaseMatcher<NodeEvent> {
private final Node expected;
private EventForNode(Node expected) {
this.expected = expected;
}
@Override
public boolean matches(Object o) {
return ((NodeEvent)o).getNode().getNode().equals(expected);
}
@Override
public void describeTo(Description description) {
description.appendText(String.format("NodeEvent for node %s", expected));
}
@Override
public void describeMismatch(Object item, Description description) {
NodeEvent other = (NodeEvent)item;
description.appendText(String.format("got node %s", other.getNode().getNode()));
}
@Factory
public static EventForNode eventForNode(Node expected) {
return new EventForNode(expected);
}
}
| apache-2.0 |
vespa-engine/vespa | config-model/src/main/java/com/yahoo/vespa/model/container/ContainerThreadpool.java | 2792 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.handler.threadpool.ContainerThreadPool;
import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.container.handler.threadpool.DefaultContainerThreadpool;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.text.XML;
import com.yahoo.vespa.model.container.component.SimpleComponent;
import org.w3c.dom.Element;
import java.util.Optional;
/**
* Component definition for a {@link java.util.concurrent.Executor} using {@link ContainerThreadPool}.
*
* @author bjorncs
*/
public class ContainerThreadpool extends SimpleComponent implements ContainerThreadpoolConfig.Producer {
private final String name;
private final UserOptions userOptions;
public ContainerThreadpool(String name, UserOptions userOptions) {
super(new ComponentModel(
BundleInstantiationSpecification.getFromStrings(
"threadpool@" + name,
DefaultContainerThreadpool.class.getName(),
null)));
this.name = name;
this.userOptions = userOptions;
}
@Override
public void getConfig(ContainerThreadpoolConfig.Builder builder) {
builder.name(this.name);
if (userOptions != null) {
builder.maxThreads(userOptions.maxThreads);
builder.minThreads(userOptions.minThreads);
builder.queueSize(userOptions.queueSize);
}
}
protected Optional<UserOptions> userOptions() { return Optional.ofNullable(userOptions); }
protected boolean hasUserOptions() { return userOptions().isPresent(); }
public static class UserOptions {
private final int maxThreads;
private final int minThreads;
private final int queueSize;
private UserOptions(int maxThreads, int minThreads, int queueSize) {
this.maxThreads = maxThreads;
this.minThreads = minThreads;
this.queueSize = queueSize;
}
public static Optional<UserOptions> fromXml(Element xml) {
Element element = XML.getChild(xml, "threadpool");
if (element == null) return Optional.empty();
return Optional.of(new UserOptions(
intOption(element, "max-threads"),
intOption(element, "min-threads"),
intOption(element, "queue-size")));
}
private static int intOption(Element element, String name) {
return Integer.parseInt(XML.getChild(element, name).getTextContent());
}
}
}
| apache-2.0 |
SumoLogic/epigraph | java/http-server/common/src/main/java/ws/epigraph/server/http/HtmlCapableInvocationError.java | 912 | /*
* Copyright 2017 Sumo Logic
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.epigraph.server.http;
import org.jetbrains.annotations.NotNull;
import ws.epigraph.invocation.InvocationError;
/**
* @author <a href="mailto:konstantin.sobolev@gmail.com">Konstantin Sobolev</a>
*/
public interface HtmlCapableInvocationError extends InvocationError {
@NotNull String htmlMessage();
}
| apache-2.0 |
nwnpallewela/developer-studio | esb/plugins/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/AbstractEndPoint.java | 27365 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.wso2.developerstudio.eclipse.gmf.esb;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Abstract End Point</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isReliableMessagingEnabled <em>Reliable Messaging Enabled</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isSecurityEnabled <em>Security Enabled</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isAddressingEnabled <em>Addressing Enabled</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getAddressingVersion <em>Addressing Version</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isAddressingSeparateListener <em>Addressing Separate Listener</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getTimeOutDuration <em>Time Out Duration</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getTimeOutAction <em>Time Out Action</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryErrorCodes <em>Retry Error Codes</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryCount <em>Retry Count</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryDelay <em>Retry Delay</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendErrorCodes <em>Suspend Error Codes</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendInitialDuration <em>Suspend Initial Duration</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendMaximumDuration <em>Suspend Maximum Duration</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendProgressionFactor <em>Suspend Progression Factor</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getReliableMessagingPolicy <em>Reliable Messaging Policy</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSecurityPolicy <em>Security Policy</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getFormat <em>Format</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getOptimize <em>Optimize</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getTemplateParameters <em>Template Parameters</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isStatisticsEnabled <em>Statistics Enabled</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isTraceEnabled <em>Trace Enabled</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getInboundPolicy <em>Inbound Policy</em>}</li>
* <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getOutboundPolicy <em>Outbound Policy</em>}</li>
* </ul>
* </p>
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint()
* @model abstract="true"
* @generated
*/
public interface AbstractEndPoint extends EndPoint {
/**
* Returns the value of the '<em><b>Reliable Messaging Enabled</b></em>' attribute.
* The default value is <code>"false"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Reliable Messaging Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Reliable Messaging Enabled</em>' attribute.
* @see #setReliableMessagingEnabled(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_ReliableMessagingEnabled()
* @model default="false"
* @generated
*/
boolean isReliableMessagingEnabled();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isReliableMessagingEnabled <em>Reliable Messaging Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Reliable Messaging Enabled</em>' attribute.
* @see #isReliableMessagingEnabled()
* @generated
*/
void setReliableMessagingEnabled(boolean value);
/**
* Returns the value of the '<em><b>Security Enabled</b></em>' attribute.
* The default value is <code>"false"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Security Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Security Enabled</em>' attribute.
* @see #setSecurityEnabled(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SecurityEnabled()
* @model default="false"
* @generated
*/
boolean isSecurityEnabled();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isSecurityEnabled <em>Security Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Security Enabled</em>' attribute.
* @see #isSecurityEnabled()
* @generated
*/
void setSecurityEnabled(boolean value);
/**
* Returns the value of the '<em><b>Addressing Enabled</b></em>' attribute.
* The default value is <code>"false"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Addressing Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Addressing Enabled</em>' attribute.
* @see #setAddressingEnabled(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_AddressingEnabled()
* @model default="false"
* @generated
*/
boolean isAddressingEnabled();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isAddressingEnabled <em>Addressing Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Addressing Enabled</em>' attribute.
* @see #isAddressingEnabled()
* @generated
*/
void setAddressingEnabled(boolean value);
/**
* Returns the value of the '<em><b>Addressing Version</b></em>' attribute.
* The default value is <code>"final"</code>.
* The literals are from the enumeration {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointAddressingVersion}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Addressing Version</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Addressing Version</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointAddressingVersion
* @see #setAddressingVersion(EndPointAddressingVersion)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_AddressingVersion()
* @model default="final"
* @generated
*/
EndPointAddressingVersion getAddressingVersion();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getAddressingVersion <em>Addressing Version</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Addressing Version</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointAddressingVersion
* @see #getAddressingVersion()
* @generated
*/
void setAddressingVersion(EndPointAddressingVersion value);
/**
* Returns the value of the '<em><b>Addressing Separate Listener</b></em>' attribute.
* The default value is <code>"false"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Addressing Separate Listener</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Addressing Separate Listener</em>' attribute.
* @see #setAddressingSeparateListener(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_AddressingSeparateListener()
* @model default="false"
* @generated
*/
boolean isAddressingSeparateListener();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isAddressingSeparateListener <em>Addressing Separate Listener</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Addressing Separate Listener</em>' attribute.
* @see #isAddressingSeparateListener()
* @generated
*/
void setAddressingSeparateListener(boolean value);
/**
* Returns the value of the '<em><b>Time Out Duration</b></em>' attribute.
* The default value is <code>"0"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Time Out Duration</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Time Out Duration</em>' attribute.
* @see #setTimeOutDuration(long)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_TimeOutDuration()
* @model default="0"
* @generated
*/
long getTimeOutDuration();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getTimeOutDuration <em>Time Out Duration</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Time Out Duration</em>' attribute.
* @see #getTimeOutDuration()
* @generated
*/
void setTimeOutDuration(long value);
/**
* Returns the value of the '<em><b>Time Out Action</b></em>' attribute.
* The default value is <code>"never"</code>.
* The literals are from the enumeration {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointTimeOutAction}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Time Out Action</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Time Out Action</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointTimeOutAction
* @see #setTimeOutAction(EndPointTimeOutAction)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_TimeOutAction()
* @model default="never"
* @generated
*/
EndPointTimeOutAction getTimeOutAction();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getTimeOutAction <em>Time Out Action</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Time Out Action</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointTimeOutAction
* @see #getTimeOutAction()
* @generated
*/
void setTimeOutAction(EndPointTimeOutAction value);
/**
* Returns the value of the '<em><b>Retry Error Codes</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Retry Error Codes</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Retry Error Codes</em>' attribute.
* @see #setRetryErrorCodes(String)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_RetryErrorCodes()
* @model
* @generated
*/
String getRetryErrorCodes();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryErrorCodes <em>Retry Error Codes</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Retry Error Codes</em>' attribute.
* @see #getRetryErrorCodes()
* @generated
*/
void setRetryErrorCodes(String value);
/**
* Returns the value of the '<em><b>Retry Count</b></em>' attribute.
* The default value is <code>"0"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Retry Count</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Retry Count</em>' attribute.
* @see #setRetryCount(int)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_RetryCount()
* @model default="0"
* @generated
*/
int getRetryCount();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryCount <em>Retry Count</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Retry Count</em>' attribute.
* @see #getRetryCount()
* @generated
*/
void setRetryCount(int value);
/**
* Returns the value of the '<em><b>Retry Delay</b></em>' attribute.
* The default value is <code>"0"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Retry Delay</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Retry Delay</em>' attribute.
* @see #setRetryDelay(long)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_RetryDelay()
* @model default="0"
* @generated
*/
long getRetryDelay();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getRetryDelay <em>Retry Delay</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Retry Delay</em>' attribute.
* @see #getRetryDelay()
* @generated
*/
void setRetryDelay(long value);
/**
* Returns the value of the '<em><b>Suspend Error Codes</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Suspend Error Codes</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Suspend Error Codes</em>' attribute.
* @see #setSuspendErrorCodes(String)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SuspendErrorCodes()
* @model
* @generated
*/
String getSuspendErrorCodes();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendErrorCodes <em>Suspend Error Codes</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Suspend Error Codes</em>' attribute.
* @see #getSuspendErrorCodes()
* @generated
*/
void setSuspendErrorCodes(String value);
/**
* Returns the value of the '<em><b>Suspend Initial Duration</b></em>' attribute.
* The default value is <code>"-1"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Suspend Initial Duration</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Suspend Initial Duration</em>' attribute.
* @see #setSuspendInitialDuration(long)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SuspendInitialDuration()
* @model default="-1"
* @generated
*/
long getSuspendInitialDuration();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendInitialDuration <em>Suspend Initial Duration</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Suspend Initial Duration</em>' attribute.
* @see #getSuspendInitialDuration()
* @generated
*/
void setSuspendInitialDuration(long value);
/**
* Returns the value of the '<em><b>Suspend Maximum Duration</b></em>' attribute.
* The default value is <code>"0"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Suspend Maximum Duration</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Suspend Maximum Duration</em>' attribute.
* @see #setSuspendMaximumDuration(long)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SuspendMaximumDuration()
* @model default="0"
* @generated
*/
long getSuspendMaximumDuration();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendMaximumDuration <em>Suspend Maximum Duration</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Suspend Maximum Duration</em>' attribute.
* @see #getSuspendMaximumDuration()
* @generated
*/
void setSuspendMaximumDuration(long value);
/**
* Returns the value of the '<em><b>Suspend Progression Factor</b></em>' attribute.
* The default value is <code>"-1"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Suspend Progression Factor</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Suspend Progression Factor</em>' attribute.
* @see #setSuspendProgressionFactor(float)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SuspendProgressionFactor()
* @model default="-1"
* @generated
*/
float getSuspendProgressionFactor();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSuspendProgressionFactor <em>Suspend Progression Factor</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Suspend Progression Factor</em>' attribute.
* @see #getSuspendProgressionFactor()
* @generated
*/
void setSuspendProgressionFactor(float value);
/**
* Returns the value of the '<em><b>Reliable Messaging Policy</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Reliable Messaging Policy</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Reliable Messaging Policy</em>' containment reference.
* @see #setReliableMessagingPolicy(RegistryKeyProperty)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_ReliableMessagingPolicy()
* @model containment="true"
* @generated
*/
RegistryKeyProperty getReliableMessagingPolicy();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getReliableMessagingPolicy <em>Reliable Messaging Policy</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Reliable Messaging Policy</em>' containment reference.
* @see #getReliableMessagingPolicy()
* @generated
*/
void setReliableMessagingPolicy(RegistryKeyProperty value);
/**
* Returns the value of the '<em><b>Security Policy</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Security Policy</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Security Policy</em>' containment reference.
* @see #setSecurityPolicy(RegistryKeyProperty)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_SecurityPolicy()
* @model containment="true"
* @generated
*/
RegistryKeyProperty getSecurityPolicy();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getSecurityPolicy <em>Security Policy</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Security Policy</em>' containment reference.
* @see #getSecurityPolicy()
* @generated
*/
void setSecurityPolicy(RegistryKeyProperty value);
/**
* Returns the value of the '<em><b>Format</b></em>' attribute.
* The literals are from the enumeration {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointMessageFormat}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Format</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Format</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointMessageFormat
* @see #setFormat(EndPointMessageFormat)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_Format()
* @model
* @generated
*/
EndPointMessageFormat getFormat();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getFormat <em>Format</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Format</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointMessageFormat
* @see #getFormat()
* @generated
*/
void setFormat(EndPointMessageFormat value);
/**
* Returns the value of the '<em><b>Optimize</b></em>' attribute.
* The literals are from the enumeration {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointAttachmentOptimization}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Optimize</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Optimize</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointAttachmentOptimization
* @see #setOptimize(EndPointAttachmentOptimization)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_Optimize()
* @model
* @generated
*/
EndPointAttachmentOptimization getOptimize();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getOptimize <em>Optimize</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Optimize</em>' attribute.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EndPointAttachmentOptimization
* @see #getOptimize()
* @generated
*/
void setOptimize(EndPointAttachmentOptimization value);
/**
* Returns the value of the '<em><b>Template Parameters</b></em>' containment reference list.
* The list contents are of type {@link org.wso2.developerstudio.eclipse.gmf.esb.TemplateParameter}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Template Parameters</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Template Parameters</em>' containment reference list.
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_TemplateParameters()
* @model containment="true"
* @generated
*/
EList<TemplateParameter> getTemplateParameters();
/**
* Returns the value of the '<em><b>Statistics Enabled</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Statistics Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Statistics Enabled</em>' attribute.
* @see #setStatisticsEnabled(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_StatisticsEnabled()
* @model
* @generated
*/
boolean isStatisticsEnabled();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isStatisticsEnabled <em>Statistics Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Statistics Enabled</em>' attribute.
* @see #isStatisticsEnabled()
* @generated
*/
void setStatisticsEnabled(boolean value);
/**
* Returns the value of the '<em><b>Trace Enabled</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Trace Enabled</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Trace Enabled</em>' attribute.
* @see #setTraceEnabled(boolean)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_TraceEnabled()
* @model
* @generated
*/
boolean isTraceEnabled();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#isTraceEnabled <em>Trace Enabled</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Trace Enabled</em>' attribute.
* @see #isTraceEnabled()
* @generated
*/
void setTraceEnabled(boolean value);
/**
* Returns the value of the '<em><b>Inbound Policy</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Inbound Policy</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Inbound Policy</em>' containment reference.
* @see #setInboundPolicy(RegistryKeyProperty)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_InboundPolicy()
* @model containment="true"
* @generated
*/
RegistryKeyProperty getInboundPolicy();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getInboundPolicy <em>Inbound Policy</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Inbound Policy</em>' containment reference.
* @see #getInboundPolicy()
* @generated
*/
void setInboundPolicy(RegistryKeyProperty value);
/**
* Returns the value of the '<em><b>Outbound Policy</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Outbound Policy</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Outbound Policy</em>' containment reference.
* @see #setOutboundPolicy(RegistryKeyProperty)
* @see org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage#getAbstractEndPoint_OutboundPolicy()
* @model containment="true"
* @generated
*/
RegistryKeyProperty getOutboundPolicy();
/**
* Sets the value of the '{@link org.wso2.developerstudio.eclipse.gmf.esb.AbstractEndPoint#getOutboundPolicy <em>Outbound Policy</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Outbound Policy</em>' containment reference.
* @see #getOutboundPolicy()
* @generated
*/
void setOutboundPolicy(RegistryKeyProperty value);
} // AbstractEndPoint
| apache-2.0 |
yahoo/athenz | libs/java/auth_core/src/test/java/com/yahoo/athenz/auth/token/AccessTokenTest.java | 25438 | /*
* Copyright 2019 Oath Holdings Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.auth.token;
import com.yahoo.athenz.auth.token.jwts.JwtsSigningKeyResolver;
import com.yahoo.athenz.auth.token.jwts.MockJwtsSigningKeyResolver;
import com.yahoo.athenz.auth.util.Crypto;
import com.yahoo.athenz.auth.util.CryptoException;
import io.jsonwebtoken.*;
import org.mockito.Mockito;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.*;
import static org.testng.Assert.*;
public class AccessTokenTest {
private final File ecPrivateKey = new File("./src/test/resources/unit_test_ec_private.key");
private final File ecPublicKey = new File("./src/test/resources/ec_public.key");
private final String JWT_KEYS = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"0\",\"alg\":\"RS256\","
+ "\"use\":\"sig\",\"n\":\"AMV3cnZXxYJL-A0TYY8Fy245HKSOBCYt9atNAUQVtbEwx9QaZGj8moYIe4nXgx"
+ "72Ktwg0Gruh8sS7GQLBizCXg7fCk62sDV_MZINnwON9gsKbxxgn9mLFeYSaatUzk-VRphDoHNIBC-qeDtYnZhs"
+ "HYcV9Jp0GPkLNquhN1TXA7gT\",\"e\":\"AQAB\"},{\"kty\":\"EC\",\"kid\":\"eckey1\",\"alg\":"
+ "\"ES256\",\"use\":\"sig\",\"crv\":\"prime256v1\",\"x\":\"AI0x6wEUk5T0hslaT83DNVy5r98Xn"
+ "G7HAjQynjCrcdCe\",\"y\":\"ATdV2ebpefqBli_SXZwvL3-7OiD3MTryGbR-zRSFZ_s=\"},"
+ "{\"kty\":\"ATHENZ\",\"alg\":\"ES256\"}]}";
AccessToken createAccessToken(long now) {
AccessToken accessToken = new AccessToken();
accessToken.setAuthTime(now);
accessToken.setScope(Collections.singletonList("readers"));
accessToken.setSubject("subject");
accessToken.setUserId("userid");
accessToken.setExpiryTime(now + 3600);
accessToken.setIssueTime(now);
accessToken.setClientId("mtls");
accessToken.setAudience("coretech");
accessToken.setVersion(1);
accessToken.setIssuer("athenz");
accessToken.setProxyPrincipal("proxy.user");
accessToken.setConfirmEntry("x5t#uri", "spiffe://athenz/sa/api");
accessToken.setAuthorizationDetails("[{\"type\":\"message_access\",\"data\":\"resource\"}]");
try {
Path path = Paths.get("src/test/resources/mtls_token_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
accessToken.setConfirmX509CertHash(cert);
} catch (IOException ignored) {
fail();
}
return accessToken;
}
void validateAccessToken(AccessToken accessToken, long now) {
assertEquals(now, accessToken.getAuthTime());
assertEquals(1, accessToken.getScope().size());
assertTrue(accessToken.getScope().contains("readers"));
assertEquals("subject", accessToken.getSubject());
assertEquals("userid", accessToken.getUserId());
assertEquals(now + 3600, accessToken.getExpiryTime());
assertEquals(now, accessToken.getIssueTime());
assertEquals("mtls", accessToken.getClientId());
assertEquals("coretech", accessToken.getAudience());
assertEquals(1, accessToken.getVersion());
assertEquals("athenz", accessToken.getIssuer());
assertEquals("proxy.user", accessToken.getProxyPrincipal());
LinkedHashMap<String, Object> confirm = accessToken.getConfirm();
assertNotNull(confirm);
assertEquals("A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0", confirm.get("x5t#S256"));
assertEquals("A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0", accessToken.getConfirmEntry("x5t#S256"));
assertEquals("spiffe://athenz/sa/api", confirm.get("x5t#uri"));
assertEquals("spiffe://athenz/sa/api", accessToken.getConfirmEntry("x5t#uri"));
assertNull(accessToken.getConfirmEntry("unknown"));
assertEquals("[{\"type\":\"message_access\",\"data\":\"resource\"}]", accessToken.getAuthorizationDetails());
try {
Path path = Paths.get("src/test/resources/mtls_token_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
final String cnfHash = (String) accessToken.getConfirmEntry(AccessToken.CLAIM_CONFIRM_X509_HASH);
assertTrue(accessToken.confirmX509CertHash(cert, cnfHash));
} catch (IOException ignored) {
fail();
}
}
private void resetConfProperty(final String oldConf) {
if (oldConf == null) {
System.clearProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF);
} else {
System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF, oldConf);
}
}
@Test
public void testAccessToken() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// verify the getters
validateAccessToken(accessToken, now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
PublicKey publicKey = Crypto.loadPublicKey(ecPublicKey);
Jws<Claims> claims = Jwts.parserBuilder().setSigningKey(publicKey).build().parseClaimsJws(accessJws);
assertNotNull(claims);
assertEquals("subject", claims.getBody().getSubject());
assertEquals("coretech", claims.getBody().getAudience());
assertEquals("athenz", claims.getBody().getIssuer());
List<String> scopes = (List<String>) claims.getBody().get("scp");
assertNotNull(scopes);
assertEquals(1, scopes.size());
assertEquals("readers", scopes.get(0));
}
@Test
public void testAccessTokenWithX509Cert() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
resolver.addPublicKey("eckey1", Crypto.loadPublicKey(ecPublicKey));
Path path = Paths.get("src/test/resources/mtls_token_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
AccessToken checkToken = new AccessToken(accessJws, resolver, cert);
validateAccessToken(checkToken, now);
}
@Test
public void testAccessTokenWithMismatchX509Cert() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
resolver.addPublicKey("eckey1", Crypto.loadPublicKey(ecPublicKey));
// use a different cert than one used for signing
Path path = Paths.get("src/test/resources/rsa_public_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
try {
new AccessToken(accessJws, resolver, cert);
fail();
} catch (CryptoException ex) {
assertTrue(ex.getMessage().contains("X.509 Certificate Confirmation failure"));
}
}
@Test
public void testAccessTokenSignedToken() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
resolver.addPublicKey("eckey1", Crypto.loadPublicKey(ecPublicKey));
AccessToken checkToken = new AccessToken(accessJws, resolver);
validateAccessToken(checkToken, now);
}
@Test
public void testAccessTokenWithoutSignedToken() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
resolver.addPublicKey("eckey1", Crypto.loadPublicKey(ecPublicKey));
// remove the signature part from the token
int idx = accessJws.lastIndexOf('.');
final String unsignedJws = accessJws.substring(0, idx + 1);
try {
new AccessToken(unsignedJws, resolver);
fail();
} catch (Exception ex) {
assertTrue(ex instanceof UnsupportedJwtException);
}
}
@Test
public void testAccessTokenSignedTokenPublicKey() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
AccessToken checkToken = new AccessToken(accessJws, Crypto.loadPublicKey(ecPublicKey));
validateAccessToken(checkToken, now);
}
@Test
public void testAccessTokenSignedTokenConfigFile() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
final String oldConf = System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF,
"src/test/resources/athenz.conf");
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
AccessToken checkToken = new AccessToken(accessJws, resolver);
validateAccessToken(checkToken, now);
resetConfProperty(oldConf);
}
@Test
public void testAccessTokenSignedTokenConfigFileUnknownKey() {
testAccessTokenSignedTokenConfigFileNoKeys("src/test/resources/athenz.conf");
testAccessTokenSignedTokenConfigFileNoKeys("src/test/resources/athenz-no-keys.conf");
testAccessTokenSignedTokenConfigFileNoKeys("src/test/resources/athenz-no-valid-keys.conf");
testAccessTokenSignedTokenConfigFileNoKeys("");
// passing invalid file that will generate parse exception
testAccessTokenSignedTokenConfigFileNoKeys("arg_file");
}
void testAccessTokenSignedTokenConfigFileNoKeys(final String confPath) {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey99", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
final String oldConf = System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF,
confPath);
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
try {
new AccessToken(accessJws, resolver);
fail();
} catch (Exception ex) {
}
resetConfProperty(oldConf);
}
@Test
public void testAccessTokenSignedTokenServerKeys() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
final String oldConf = System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF,
"src/test/resources/athenz-no-keys.conf");
MockJwtsSigningKeyResolver.setResponseBody(JWT_KEYS);
MockJwtsSigningKeyResolver resolver = new MockJwtsSigningKeyResolver("https://localhost:4443", null);
AccessToken checkToken = new AccessToken(accessJws, resolver);
validateAccessToken(checkToken, now);
resetConfProperty(oldConf);
}
@Test
public void testAccessTokenSignedTokenServerKeysFailure() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
final String oldConf = System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF,
"src/test/resources/athenz-no-keys.conf");
MockJwtsSigningKeyResolver.setResponseBody("");
SSLContext sslContext = Mockito.mock(SSLContext.class);
MockJwtsSigningKeyResolver resolver = new MockJwtsSigningKeyResolver("https://localhost:4443", sslContext);
try {
new AccessToken(accessJws, resolver);
fail();
} catch (Exception ex) {
assertTrue(ex instanceof IllegalArgumentException, ex.getMessage());
}
resetConfProperty(oldConf);
}
@Test
public void testAccessTokenExpired() {
long now = System.currentTimeMillis() / 1000;
// we allow clock skew of 60 seconds so we'll go
// back 3600 + 61 to make our token expired
AccessToken accessToken = createAccessToken(now - 3661);
// now get the signed token
PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
String accessJws = accessToken.getSignedToken(privateKey, "eckey1", SignatureAlgorithm.ES256);
assertNotNull(accessJws);
// now verify our signed token
final String oldConf = System.setProperty(JwtsSigningKeyResolver.ZTS_PROP_ATHENZ_CONF,
"src/test/resources/athenz.conf");
JwtsSigningKeyResolver resolver = new JwtsSigningKeyResolver(null, null);
try {
new AccessToken(accessJws, resolver);
fail();
} catch (Exception ex) {
assertTrue(ex.getMessage().contains("expired"));
}
resetConfProperty(oldConf);
}
@Test
public void testAccessTokenNullConfirm() {
AccessToken accessToken = new AccessToken();
assertNull(accessToken.getConfirm());
assertNull(accessToken.getConfirmEntry("key"));
}
@Test
public void testGetX509CertificateHash() throws CertificateEncodingException {
X509Certificate mockCert = Mockito.mock(X509Certificate.class);
Mockito.when(mockCert.getEncoded()).thenThrow(new CryptoException());
AccessToken accessToken = new AccessToken();
assertNull(accessToken.getX509CertificateHash(mockCert));
}
@Test
public void testConfirmX509CertHashFailure() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
try {
Path path = Paths.get("src/test/resources/valid_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
final String cnfHash = (String) accessToken.getConfirmEntry(AccessToken.CLAIM_CONFIRM_X509_HASH);
assertFalse(accessToken.confirmX509CertHash(cert, cnfHash));
} catch (IOException ignored) {
fail();
}
}
@Test
public void testConfirmMTLSBoundTokenNullX509Cert() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
assertFalse(accessToken.confirmMTLSBoundToken(null, "cnf-hash"));
}
@Test
public void testConfirmMTLSBoundTokenNoHash() {
AccessToken accessToken = new AccessToken();
accessToken.setVersion(1);
accessToken.setIssuer("athenz");
accessToken.setConfirmEntry("x5t#uri", "spiffe://athenz/sa/api");
try {
Path path = Paths.get("src/test/resources/valid_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmMTLSBoundToken(cert, "cnf-hash"));
} catch (IOException ignored) {
fail();
}
}
@Test
public void testConfirmMTLSBoundTokenWithProxyNotAllowed() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
Path path = Paths.get("src/test/resources/valid_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
AccessToken.setAccessTokenProxyPrincipals(new HashSet<>());
assertFalse(accessToken.confirmMTLSBoundToken(cert, "A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0"));
AccessToken.setAccessTokenProxyPrincipals(null);
}
@Test
public void testConfirmMTLSBoundTokenWithProxyAllowed() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
Path path = Paths.get("src/test/resources/valid_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
AccessToken.setAccessTokenProxyPrincipals(new HashSet<>(Arrays.asList("athenz.syncer")));
assertTrue(accessToken.confirmMTLSBoundToken(cert, "A4DtL2JmUMhAsvJj5tKyn64SqzmuXbMrJa0n761y5v0"));
AccessToken.setAccessTokenProxyPrincipals(null);
}
@Test
public void testConfirmMTLSBoundTokenCertPrincipalAllowed() throws IOException {
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 - 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 - 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertTrue(accessToken.confirmMTLSBoundToken(cert, null));
}
@Test
public void testConfirmMTLSBoundTokenNoCN() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
Path path = Paths.get("src/test/resources/no_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmMTLSBoundToken(cert, "cnf-hash"));
}
@Test
public void testConfirmX509CertPrincipalNullCert() {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
assertFalse(accessToken.confirmX509CertPrincipal(null, "athenz.proxy"));
}
@Test
public void testConfirmX509CertPrincipalCertNoCN() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
Path path = Paths.get("src/test/resources/no_cn_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmX509CertPrincipal(cert, "athenz.proxy"));
}
@Test
public void testConfirmX509CertPrincipalCertCNMismatch() throws IOException {
long now = System.currentTimeMillis() / 1000;
AccessToken accessToken = createAccessToken(now);
Path path = Paths.get("src/test/resources/rsa_public_x509.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmX509CertPrincipal(cert, "athenz.proxy"));
}
@Test
public void testConfirmX509CertPrincipalCertStartTime() throws IOException {
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 + 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 + 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmX509CertPrincipal(cert, "mtls"));
}
@Test
public void testConfirmX509CertPrincipalCertStartTimeCheckDisabled() throws IOException {
AccessToken.setAccessTokenCertOffset(-1);
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 + 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 + 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertTrue(accessToken.confirmX509CertPrincipal(cert, "mtls"));
AccessToken.setAccessTokenCertOffset(3600);
}
@Test
public void testConfirmX509CertPrincipalCertStartTimePassOffset() throws IOException {
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 - ACCESS_TOKEN_CERT_OFFSET - 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 - 3600 - 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmX509CertPrincipal(cert, "mtls"));
}
@Test
public void testConfirmX509CertPrincipal() throws IOException {
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 - 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 - 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertTrue(accessToken.confirmX509CertPrincipal(cert, "mtls"));
}
@Test
public void testConfirmX509CertPrincipalDisable() throws IOException {
AccessToken.setAccessTokenCertOffset(0);
// our cert issue time is 1565245568
// so we're going to set token issue time to cert time + 3600 - 100
AccessToken accessToken = createAccessToken(1565245568 + 3600 - 100);
Path path = Paths.get("src/test/resources/mtls_token2_spec.cert");
String certStr = new String(Files.readAllBytes(path));
X509Certificate cert = Crypto.loadX509Certificate(certStr);
assertFalse(accessToken.confirmX509CertPrincipal(cert, "mtls"));
AccessToken.setAccessTokenCertOffset(3600);
}
}
| apache-2.0 |
nilbody/h2o-3 | h2o-core/src/main/java/water/rapids/ASTColSlice.java | 19176 | package water.rapids;
import jsr166y.CountedCompleter;
import water.*;
import water.fvec.*;
import water.parser.BufferedString;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
/** Column slice; allows R-like syntax.
* Numbers past the largest column are an error.
* Negative numbers and number lists are allowed, and represent an *exclusion* list */
class ASTColSlice extends ASTPrim {
@Override public String[] args() { return new String[]{"ary", "cols"}; }
@Override int nargs() { return 1+2; } // (cols src [col_list])
@Override public String str() { return "cols" ; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val v = stk.track(asts[1].exec(env));
if( v instanceof ValRow ) {
ValRow vv = (ValRow)v;
return vv.slice(asts[2].columns(vv._names));
}
Frame src = v.getFrame();
int[] cols = col_select(src.names(),asts[2]);
Frame dst = new Frame();
Vec[] vecs = src.vecs();
for( int col : cols ) dst.add(src._names[col],vecs[col]);
return new ValFrame(dst);
}
// Complex column selector; by list of names or list of numbers or single
// name or number. Numbers can be ranges or negative.
static int[] col_select( String[] names, AST col_selector ) {
int[] cols = col_selector.columns(names);
if( cols.length==0 ) return cols; // Empty inclusion list?
if( cols[0] >= 0 ) { // Positive (inclusion) list
if( cols[cols.length-1] >= names.length )
throw new IllegalArgumentException("Column must be an integer from 0 to "+(names.length-1));
return cols;
}
// Negative (exclusion) list; convert to positive inclusion list
int[] pos = new int[names.length];
for( int col : cols ) // more or less a radix sort, filtering down to cols to ignore
if( 0 <= -col-1 && -col-1 < names.length )
pos[-col-1] = -1;
int j=0;
for( int i=0; i<names.length; i++ ) if( pos[i] == 0 ) pos[j++] = i;
return Arrays.copyOfRange(pos,0,j);
}
}
/** Column slice; allows python-like syntax.
* Numbers past last column are allowed and ignored in NumLists, but throw an
* error for single numbers. Negative numbers have the number of columns
* added to them, before being checked for range.
*/
class ASTColPySlice extends ASTPrim {
@Override public String[] args() { return new String[]{"ary", "cols"}; }
@Override int nargs() { return 1+2; } // (cols_py src [col_list])
@Override public String str() { return "cols_py" ; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val v = stk.track(asts[1].exec(env));
if( v instanceof ValRow ) {
ValRow vv = (ValRow)v;
return vv.slice(asts[2].columns(vv._names));
}
Frame fr = v.getFrame();
int[] cols = asts[2].columns(fr.names());
Frame fr2 = new Frame();
if( cols.length==0 ) // Empty inclusion list?
return new ValFrame(fr2);
if( cols[0] < 0 ) // Negative cols have number of cols added
for( int i=0; i<cols.length; i++ )
cols[i] += fr.numCols();
if( asts[2] instanceof ASTNum && // Singletons must be in-range
(cols[0] < 0 || cols[0] >= fr.numCols()) )
throw new IllegalArgumentException("Column must be an integer from 0 to "+(fr.numCols()-1));
for( int col : cols ) // For all included columns
if( col >= 0 && col < fr.numCols() ) // Ignoring out-of-range ones
fr2.add(fr.names()[col],fr.vecs()[col]);
return new ValFrame(fr2);
}
}
/** Row Slice */
class ASTRowSlice extends ASTPrim {
@Override public String[] args() { return new String[]{"ary", "rows"}; }
@Override int nargs() { return 1+2; } // (rows src [row_list])
@Override public String str() { return "rows" ; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
Frame returningFrame;
long nrows = fr.numRows();
if( asts[2] instanceof ASTNumList ) {
final ASTNumList nums = (ASTNumList)asts[2];
if( !nums._isSort && !nums.isEmpty() && nums._bases[0] >= 0)
throw new IllegalArgumentException("H2O does not currently reorder rows, please sort your row selection first");
long[] rows = (nums._isList || nums.min()<0) ? nums.expand8Sort() : null;
if( rows!=null ) {
if (rows.length == 0) { // Empty inclusion list?
} else if (rows[0] >= 0) { // Positive (inclusion) list
if (rows[rows.length - 1] > nrows)
throw new IllegalArgumentException("Row must be an integer from 0 to " + (nrows - 1));
} else { // Negative (exclusion) list
if (rows[rows.length - 1] >= 0)
throw new IllegalArgumentException("Cannot mix negative and postive row selection");
// Invert the list to make a positive list, ignoring out-of-bounds values
BitSet bs = new BitSet((int) nrows);
for (int i = 0; i < rows.length; i++) {
int idx = (int) (-rows[i] - 1); // The positive index
if (idx >= 0 && idx < nrows)
bs.set(idx); // Set column to EXCLUDE
}
rows = new long[(int) nrows - bs.cardinality()];
for (int i = bs.nextClearBit(0), j = 0; i < nrows; i = bs.nextClearBit(i + 1))
rows[j++] = i;
}
}
final long[] ls = rows;
returningFrame = new MRTask(){
@Override public void map(Chunk[] cs, NewChunk[] ncs) {
if( nums.cnt()==0 ) return;
if( ls != null && ls.length == 0 ) return;
long start = cs[0].start();
long end = start + cs[0]._len;
long min = ls==null?(long)nums.min():ls[0], max = ls==null?(long)nums.max()-1:ls[ls.length-1]; // exclusive max to inclusive max when stride == 1
// [ start, ..., end ] the chunk
//1 [] nums out left: nums.max() < start
//2 [] nums out rite: nums.min() > end
//3 [ nums ] nums run left: nums.min() < start && nums.max() <= end
//4 [ nums ] nums run in : start <= nums.min() && nums.max() <= end
//5 [ nums ] nums run rite: start <= nums.min() && end < nums.max()
if( !(max<start || min>end) ) { // not situation 1 or 2 above
long startOffset = (min > start ? min : start); // situation 4 and 5 => min > start;
for( int i=(int)(startOffset-start); i<cs[0]._len; ++i) {
if( (ls==null && nums.has(start+i)) || (ls!=null && Arrays.binarySearch(ls,start+i) >= 0 )) {
for(int c=0;c<cs.length;++c) {
if( cs[c] instanceof CStrChunk ) ncs[c].addStr(cs[c], i);
else if( cs[c] instanceof C16Chunk ) ncs[c].addUUID(cs[c],i);
else if( cs[c].isNA(i) ) ncs[c].addNA();
else ncs[c].addNum(cs[c].atd(i));
}
}
}
}
}
}.doAll(fr.types(), fr).outputFrame(fr.names(),fr.domains());
} else if( (asts[2] instanceof ASTNum) ) {
long[] rows = new long[]{(long)(((ASTNum)asts[2])._v.getNum())};
returningFrame = fr.deepSlice(rows,null);
} else if( (asts[2] instanceof ASTExec) || (asts[2] instanceof ASTId) ) {
Frame predVec = stk.track(asts[2].exec(env)).getFrame();
if( predVec.numCols() != 1 ) throw new IllegalArgumentException("Conditional Row Slicing Expression evaluated to " + predVec.numCols() + " columns. Must be a boolean Vec.");
returningFrame = fr.deepSlice(predVec,null);
} else
throw new IllegalArgumentException("Row slicing requires a number-list as the last argument, but found a "+asts[2].getClass());
return new ValFrame(returningFrame);
}
}
class ASTFlatten extends ASTPrim {
@Override public String[] args() { return new String[]{"ary"}; }
@Override int nargs() { return 1+1; } // (flatten fr)
@Override public String str() { return "flatten"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
if( fr.numCols()!=1 || fr.numRows()!=1 ) return new ValFrame(fr); // did not flatten
Vec vec = fr.anyVec();
if( vec.isNumeric() || vec.isBad() ) return new ValNum(vec.at(0));
return new ValStr( vec.isString() ? vec.atStr(new BufferedString(),0).toString() : vec.factor(vec.at8(0)));
}
}
class ASTFilterNACols extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "fraction"}; }
@Override int nargs() { return 1+2; } // (filterNACols frame frac)
@Override
public String str() { return "filterNACols"; }
@Override ValNums apply( Env env, Env.StackHelp stk, AST asts[] ) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
double frac = asts[2].exec(env).getNum();
double nrow = fr.numRows()*frac;
Vec vecs[] = fr.vecs();
ArrayList<Double> idxs = new ArrayList<>();
for( double i=0; i<fr.numCols(); i++ )
if( vecs[(int)i].naCnt() < nrow )
idxs.add(i);
double[] include_cols = new double[idxs.size()];
int i=0;
for(double d: idxs)
include_cols[i++] = d;
return new ValNums(include_cols);
}
}
/** cbind: bind columns together into a new frame */
class ASTCBind extends ASTPrim {
@Override
public String[] args() { return new String[]{"..."}; }
@Override int nargs() { return -1; } // variable number of args
@Override
public String str() { return "cbind" ; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
// Compute the variable args. Find the common row count
Val vals[] = new Val[asts.length];
Vec vec = null;
for( int i=1; i<asts.length; i++ ) {
vals[i] = stk.track(asts[i].exec(env));
if( vals[i].isFrame() ) {
Vec anyvec = vals[i].getFrame().anyVec();
if( anyvec == null ) continue; // Ignore the empty frame
if( vec == null ) vec = anyvec;
else if( vec.length() != anyvec.length() )
throw new IllegalArgumentException("cbind frames must have all the same rows, found "+vec.length()+" and "+anyvec.length()+" rows.");
}
}
boolean clean = false;
if( vec == null ) { vec = Vec.makeZero(1); clean = true; } // Default to length 1
// Populate the new Frame
Frame fr = new Frame();
for( int i=1; i<asts.length; i++ ) {
switch( vals[i].type() ) {
case Val.FRM:
fr.add(vals[i].getFrame().names(),fr.makeCompatible(vals[i].getFrame()));
break;
case Val.FUN: throw H2O.unimpl();
case Val.STR: throw H2O.unimpl();
case Val.NUM:
// Auto-expand scalars to fill every row
double d = vals[i].getNum();
fr.add(Double.toString(d),vec.makeCon(d));
break;
default: throw H2O.unimpl();
}
}
if( clean ) vec.remove();
return new ValFrame(fr);
}
}
/** rbind: bind rows together into a new frame */
class ASTRBind extends ASTPrim {
@Override
public String[] args() { return new String[]{"..."}; }
@Override int nargs() { return -1; } // variable number of args
@Override
public String str() { return "rbind" ; }
@Override ValFrame apply( Env env, Env.StackHelp stk, AST asts[] ) {
// Execute all args. Find a canonical frame; all Frames must look like this one.
// Each argument turns into either a Frame (whose rows are entirely
// inlined) or a scalar (which is replicated across as a single row).
Frame fr = null; // Canonical Frame; all frames have the same column count, types and names
int nchks=0; // Total chunks
Val vals[] = new Val[asts.length]; // Computed AST results
for( int i=1; i<asts.length; i++ ) {
vals[i] = stk.track(asts[i].exec(env));
if( vals[i].isFrame() ) {
fr = vals[i].getFrame();
nchks += fr.anyVec().nChunks(); // Total chunks
} else nchks++; // One chunk per scalar
}
// No Frame, just a pile-o-scalars?
Vec zz = null; // The zero-length vec for the zero-frame frame
if( fr==null ) { // Zero-length, 1-column, default name
fr = new Frame(new String[]{Frame.defaultColName(0)}, new Vec[]{zz=Vec.makeZero(0)});
if( asts.length == 1 ) return new ValFrame(fr);
}
// Verify all Frames are the same columns, names, and types. Domains can vary, and will be the union
final Frame frs[] = new Frame[asts.length]; // Input frame
final byte[] types = fr.types(); // Column types
final long[] espc = new long[nchks+1]; // Compute a new layout!
int coffset = 0;
Frame[] tmp_frs = new Frame[asts.length];
for( int i=1; i<asts.length; i++ ) {
Val val = vals[i]; // Save values computed for pass 2
Frame fr0 = val.isFrame() ? val.getFrame()
// Scalar: auto-expand into a 1-row frame
: (tmp_frs[i] = new Frame(fr._names,Vec.makeCons(val.getNum(),1L,fr.numCols())));
// Check that all frames are compatible
if( fr.numCols() != fr0.numCols() )
throw new IllegalArgumentException("rbind frames must have all the same columns, found "+fr.numCols()+" and "+fr0.numCols()+" columns.");
if( !Arrays.deepEquals(fr._names,fr0._names) )
throw new IllegalArgumentException("rbind frames must have all the same column names, found "+Arrays.toString(fr._names)+" and "+Arrays.toString(fr0._names));
if( !Arrays.equals(types,fr0.types()) )
throw new IllegalArgumentException("rbind frames must have all the same column types, found "+Arrays.toString(types)+" and "+Arrays.toString(fr0.types()));
frs[i] = fr0; // Save frame
// Roll up the ESPC row counts
long roffset = espc[coffset];
long[] espc2 = fr0.anyVec().espc();
for( int j=1; j < espc2.length; j++ ) // Roll up the row counts
espc[coffset + j] = (roffset+espc2[j]);
coffset += espc2.length-1; // Chunk offset
}
if( zz != null ) zz.remove();
// build up the new domains for each vec
HashMap<String, Integer>[] dmap = new HashMap[types.length];
String[][] domains = new String[types.length][];
int[][][] cmaps = new int[types.length][][];
for(int k=0;k<types.length;++k) {
dmap[k] = new HashMap<>();
int c = 0;
byte t = types[k];
if( t == Vec.T_CAT ) {
int[][] maps = new int[frs.length][];
for(int i=1; i < frs.length; i++) {
maps[i] = new int[frs[i].vec(k).domain().length];
for(int j=0; j < maps[i].length; j++ ) {
String s = frs[i].vec(k).domain()[j];
if( !dmap[k].containsKey(s)) dmap[k].put(s, maps[i][j]=c++);
else maps[i][j] = dmap[k].get(s);
}
}
cmaps[k] = maps;
} else {
cmaps[k] = new int[frs.length][];
}
domains[k] = c==0?null:new String[c];
for( Map.Entry<String, Integer> e : dmap[k].entrySet())
domains[k][e.getValue()] = e.getKey();
}
// Now make Keys for the new Vecs
Key<Vec>[] keys = fr.anyVec().group().addVecs(fr.numCols());
Vec[] vecs = new Vec[fr.numCols()];
int rowLayout = Vec.ESPC.rowLayout(keys[0],espc);
for( int i=0; i<vecs.length; i++ )
vecs[i] = new Vec( keys[i], rowLayout, domains[i], types[i]);
// Do the row-binds column-by-column.
// Switch to F/J thread for continuations
ParallelRbinds t;
H2O.submitTask(t =new ParallelRbinds(frs,espc,vecs,cmaps)).join();
for( Frame tfr : tmp_frs ) if( tfr != null ) tfr.delete();
return new ValFrame(new Frame(fr.names(), t._vecs));
}
// Helper class to allow parallel column binds, up to MAXP in parallel at any
// point in time. TODO: Not sure why this is here, should just spam F/J with
// all columns, even up to 100,000's should be fine.
private static class ParallelRbinds extends H2O.H2OCountedCompleter{
private final AtomicInteger _ctr; // Concurrency control
private static int MAXP = 100; // Max number of concurrent columns
private Frame[] _frs; // All frame args
private int[][][] _cmaps; // Individual cmaps per each set of vecs to rbind
private long[] _espc; // Rolled-up final ESPC
private Vec[] _vecs; // Output
ParallelRbinds( Frame[] frs, long[] espc, Vec[] vecs, int[][][] cmaps) { _frs = frs; _espc = espc; _vecs = vecs; _cmaps=cmaps;_ctr = new AtomicInteger(MAXP-1); }
@Override protected void compute2() {
final int ncols = _frs[1].numCols();
addToPendingCount(ncols-1);
for (int i=0; i < Math.min(MAXP, ncols); ++i) forkVecTask(i);
}
// An RBindTask for each column
private void forkVecTask(final int colnum) {
Vec[] vecs = new Vec[_frs.length]; // Source Vecs
for( int i = 1; i < _frs.length; i++ )
vecs[i] = _frs[i].vec(colnum);
new RbindTask(new Callback(), vecs, _vecs[colnum], _espc, _cmaps[colnum]).fork();
}
private class Callback extends H2O.H2OCallback {
public Callback(){super(ParallelRbinds.this);}
@Override public void callback(H2O.H2OCountedCompleter h2OCountedCompleter) {
int i = _ctr.incrementAndGet();
if(i < _vecs.length)
forkVecTask(i);
}
}
}
// RBind a single column across all vals
private static class RbindTask extends H2O.H2OCountedCompleter<RbindTask> {
final Vec[] _vecs; // Input vecs to be row-bound
final Vec _v; // Result vec
final long[] _espc; // Result layout
int[][] _cmaps; // categorical mapping array
RbindTask(H2O.H2OCountedCompleter cc, Vec[] vecs, Vec v, long[] espc, int[][] cmaps) { super(cc); _vecs = vecs; _v = v; _espc = espc; _cmaps=cmaps; }
@Override protected void compute2() {
addToPendingCount(_vecs.length-1-1);
int offset=0;
for( int i=1; i<_vecs.length; i++ ) {
new RbindMRTask(this, _cmaps[i], _v, offset).asyncExec(_vecs[i]);
offset += _vecs[i].nChunks();
}
}
@Override public void onCompletion(CountedCompleter cc) {
DKV.put(_v);
}
}
private static class RbindMRTask extends MRTask<RbindMRTask> {
private final int[] _cmap;
private final int _chunkOffset;
private final Vec _v;
RbindMRTask(H2O.H2OCountedCompleter hc, int[] cmap, Vec v, int offset) { super(hc); _cmap = cmap; _v = v; _chunkOffset = offset;}
@Override public void map(Chunk cs) {
int idx = _chunkOffset+cs.cidx();
Key ckey = Vec.chunkKey(_v._key, idx);
if (_cmap != null) {
assert !cs.hasFloat(): "Input chunk ("+cs.getClass()+") has float, but is expected to be categorical";
NewChunk nc = new NewChunk(_v, idx);
// loop over rows and update ints for new domain mapping according to vecs[c].domain()
for (int r=0;r < cs._len;++r) {
if (cs.isNA(r)) nc.addNA();
else nc.addNum(_cmap[(int)cs.at8(r)], 0);
}
nc.close(_fs);
} else {
DKV.put(ckey, cs.deepCopy(), _fs, true);
}
}
}
}
| apache-2.0 |