repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
SaenkoDmitry/atom | lecture02/src/main/java/ru/atom/geometry/Geometry.java | 861 | package ru.atom.geometry;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* ^ Y
* |
* |
* |
* | X
* .---------->
*/
public final class Geometry {
private Geometry() {
}
/**
* Bar is a rectangle, which borders are parallel to coordinate axis
* Like selection bar in desktop, this bar is defined by two opposite corners
* Bar is not oriented
* (It is not relevant, which opposite corners you choose to define bar)
* @return new Bar
*/
public static Collider createBar(int firstPointX, int firstCornerY, int secondCornerX, int secondCornerY) {
throw new NotImplementedException();
}
/**
* 2D point
* @return new Point
*/
public static Collider createPoint(int x, int y) {
throw new NotImplementedException();
}
}
| mit |
HenryHarper/Acquire-Reboot | gradle/src/maven/org/gradle/api/plugins/MavenPlugin.java | 10203 | /*
* Copyright 2009 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.gradle.api.plugins;
import org.apache.maven.project.MavenProject;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.artifacts.maven.Conf2ScopeMappingContainer;
import org.gradle.api.artifacts.maven.MavenPom;
import org.gradle.api.artifacts.maven.MavenResolver;
import org.gradle.api.internal.artifacts.DefaultModuleVersionIdentifier;
import org.gradle.api.internal.artifacts.ModuleInternal;
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal;
import org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.DefaultProjectPublication;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectPublicationRegistry;
import org.gradle.api.internal.artifacts.mvnsettings.LocalMavenRepositoryLocator;
import org.gradle.api.internal.artifacts.mvnsettings.MavenSettingsProvider;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.plugins.DslObject;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.publication.maven.internal.DefaultDeployerFactory;
import org.gradle.api.publication.maven.internal.DefaultMavenRepositoryHandlerConvention;
import org.gradle.api.publication.maven.internal.MavenFactory;
import org.gradle.api.tasks.Upload;
import org.gradle.configuration.project.ProjectConfigurationActionContainer;
import org.gradle.internal.Factory;
import org.gradle.logging.LoggingManagerInternal;
import javax.inject.Inject;
/**
* <p>A {@link org.gradle.api.Plugin} which allows project artifacts to be deployed to a Maven repository, or installed
* to the local Maven cache.</p>
*/
public class MavenPlugin implements Plugin<ProjectInternal> {
public static final int COMPILE_PRIORITY = 300;
public static final int RUNTIME_PRIORITY = 200;
public static final int TEST_COMPILE_PRIORITY = 150;
public static final int TEST_RUNTIME_PRIORITY = 100;
public static final int PROVIDED_COMPILE_PRIORITY = COMPILE_PRIORITY + 100;
public static final int PROVIDED_RUNTIME_PRIORITY = COMPILE_PRIORITY + 150;
public static final String INSTALL_TASK_NAME = "install";
private final Factory<LoggingManagerInternal> loggingManagerFactory;
private final FileResolver fileResolver;
private final ProjectPublicationRegistry publicationRegistry;
private final ProjectConfigurationActionContainer configurationActionContainer;
private final MavenSettingsProvider mavenSettingsProvider;
private final LocalMavenRepositoryLocator mavenRepositoryLocator;
private Project project;
@Inject
public MavenPlugin(Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver,
ProjectPublicationRegistry publicationRegistry, ProjectConfigurationActionContainer configurationActionContainer,
MavenSettingsProvider mavenSettingsProvider, LocalMavenRepositoryLocator mavenRepositoryLocator) {
this.loggingManagerFactory = loggingManagerFactory;
this.fileResolver = fileResolver;
this.publicationRegistry = publicationRegistry;
this.configurationActionContainer = configurationActionContainer;
this.mavenSettingsProvider = mavenSettingsProvider;
this.mavenRepositoryLocator = mavenRepositoryLocator;
}
public void apply(final ProjectInternal project) {
this.project = project;
project.getPluginManager().apply(BasePlugin.class);
MavenFactory mavenFactory = project.getServices().get(MavenFactory.class);
final MavenPluginConvention pluginConvention = addConventionObject(project, mavenFactory);
final DefaultDeployerFactory deployerFactory = new DefaultDeployerFactory(
mavenFactory,
loggingManagerFactory,
fileResolver,
pluginConvention,
project.getConfigurations(),
pluginConvention.getConf2ScopeMappings(),
mavenSettingsProvider,
mavenRepositoryLocator);
configureUploadTasks(deployerFactory);
configureUploadArchivesTask();
PluginContainer plugins = project.getPlugins();
plugins.withType(JavaPlugin.class, new Action<JavaPlugin>() {
public void execute(JavaPlugin javaPlugin) {
configureJavaScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
configureInstall(project);
}
});
plugins.withType(WarPlugin.class, new Action<WarPlugin>() {
public void execute(WarPlugin warPlugin) {
configureWarScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
}
});
}
private void configureUploadTasks(final DefaultDeployerFactory deployerFactory) {
project.getTasks().withType(Upload.class, new Action<Upload>() {
public void execute(Upload upload) {
RepositoryHandler repositories = upload.getRepositories();
DefaultRepositoryHandler handler = (DefaultRepositoryHandler) repositories;
DefaultMavenRepositoryHandlerConvention repositoryConvention = new DefaultMavenRepositoryHandlerConvention(handler, deployerFactory);
new DslObject(repositories).getConvention().getPlugins().put("maven", repositoryConvention);
}
});
}
private void configureUploadArchivesTask() {
configurationActionContainer.add(new Action<Project>() {
public void execute(Project project) {
Upload uploadArchives = project.getTasks().withType(Upload.class).findByName(BasePlugin.UPLOAD_ARCHIVES_TASK_NAME);
if (uploadArchives == null) {
return;
}
ConfigurationInternal configuration = (ConfigurationInternal) uploadArchives.getConfiguration();
ModuleInternal module = configuration.getModule();
for (MavenResolver resolver : uploadArchives.getRepositories().withType(MavenResolver.class)) {
MavenPom pom = resolver.getPom();
ModuleVersionIdentifier publicationId = new DefaultModuleVersionIdentifier(
pom.getGroupId().equals(MavenProject.EMPTY_PROJECT_GROUP_ID) ? module.getGroup() : pom.getGroupId(),
pom.getArtifactId().equals(MavenProject.EMPTY_PROJECT_ARTIFACT_ID) ? module.getName() : pom.getArtifactId(),
pom.getVersion().equals(MavenProject.EMPTY_PROJECT_VERSION) ? module.getVersion() : pom.getVersion()
);
publicationRegistry.registerPublication(project.getPath(), new DefaultProjectPublication(publicationId));
}
}
});
}
private MavenPluginConvention addConventionObject(ProjectInternal project, MavenFactory mavenFactory) {
MavenPluginConvention mavenConvention = new MavenPluginConvention(project, mavenFactory);
Convention convention = project.getConvention();
convention.getPlugins().put("maven", mavenConvention);
return mavenConvention;
}
private void configureJavaScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
mavenScopeMappings.addMapping(COMPILE_PRIORITY, configurations.getByName(JavaPlugin.COMPILE_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.COMPILE);
mavenScopeMappings.addMapping(RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.RUNTIME_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.RUNTIME);
mavenScopeMappings.addMapping(TEST_COMPILE_PRIORITY, configurations.getByName(JavaPlugin.TEST_COMPILE_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.TEST);
mavenScopeMappings.addMapping(TEST_RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.TEST_RUNTIME_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.TEST);
}
private void configureWarScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
mavenScopeMappings.addMapping(PROVIDED_COMPILE_PRIORITY, configurations.getByName(WarPlugin.PROVIDED_COMPILE_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.PROVIDED);
mavenScopeMappings.addMapping(PROVIDED_RUNTIME_PRIORITY, configurations.getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME),
Conf2ScopeMappingContainer.PROVIDED);
}
private void configureInstall(Project project) {
Upload installUpload = project.getTasks().create(INSTALL_TASK_NAME, Upload.class);
Configuration configuration = project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION);
installUpload.setConfiguration(configuration);
MavenRepositoryHandlerConvention repositories = new DslObject(installUpload.getRepositories()).getConvention().getPlugin(MavenRepositoryHandlerConvention.class);
repositories.mavenInstaller();
installUpload.setDescription("Installs the 'archives' artifacts into the local Maven repository.");
}
}
| mit |
leancloud/Java-WebSocket | src/main/java/org/java_websocket/framing/PingFrame.java | 1398 | /*
* Copyright (c) 2010-2017 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket.framing;
/**
* Class to represent a ping frame
*/
public class PingFrame extends ControlFrame {
/**
* constructor which sets the opcode of this frame to ping
*/
public PingFrame() {
super(Opcode.PING);
}
}
| mit |
AllTheMods/CraftTweaker | CraftTweaker2-API/src/main/java/crafttweaker/api/data/DataByte.java | 3795 | package crafttweaker.api.data;
import java.util.*;
/**
* Contains a byte value (-128 .. 127)
*
* @author Stan Hebben
*/
public class DataByte implements IData {
private final byte value;
public DataByte(byte value) {
this.value = value;
}
@Override
public boolean asBool() {
throw new IllegalDataException("Cannot cast a byte to a bool");
}
@Override
public byte asByte() {
return value;
}
@Override
public short asShort() {
return value;
}
@Override
public int asInt() {
return value;
}
@Override
public long asLong() {
return value;
}
@Override
public float asFloat() {
return value;
}
@Override
public double asDouble() {
return value;
}
@Override
public String asString() {
return Byte.toString(value);
}
@Override
public List<IData> asList() {
return null;
}
@Override
public Map<String, IData> asMap() {
return null;
}
@Override
public byte[] asByteArray() {
return null;
}
@Override
public int[] asIntArray() {
return null;
}
@Override
public IData getAt(int i) {
throw new UnsupportedOperationException("A byte is not indexable");
}
@Override
public void setAt(int i, IData value) {
throw new UnsupportedOperationException("A byte is not indexable");
}
@Override
public IData memberGet(String name) {
throw new UnsupportedOperationException("A byte is not indexable");
}
@Override
public void memberSet(String name, IData data) {
throw new UnsupportedOperationException("A byte is not indexable");
}
@Override
public int length() {
return 0;
}
@Override
public boolean contains(IData data) {
return data.asByte() == value;
}
@Override
public boolean equals(IData data) {
return value == data.asByte();
}
@Override
public int compareTo(IData data) {
return Byte.compare(value, data.asByte());
}
@Override
public IData immutable() {
return this;
}
@Override
public IData update(IData data) {
return data;
}
@Override
public <T> T convert(IDataConverter<T> converter) {
return converter.fromByte(value);
}
@Override
public IData add(IData other) {
return new DataByte((byte) (value + other.asByte()));
}
@Override
public IData sub(IData other) {
return new DataByte((byte) (value - other.asByte()));
}
@Override
public IData mul(IData other) {
return new DataByte((byte) (value * other.asByte()));
}
@Override
public IData div(IData other) {
return new DataByte((byte) (value / other.asByte()));
}
@Override
public IData mod(IData other) {
return new DataByte((byte) (value % other.asByte()));
}
@Override
public IData and(IData other) {
return new DataByte((byte) (value & other.asByte()));
}
@Override
public IData or(IData other) {
return new DataByte((byte) (value | other.asByte()));
}
@Override
public IData xor(IData other) {
return new DataByte((byte) (value ^ other.asByte()));
}
@Override
public IData neg() {
return new DataByte((byte) (-value));
}
@Override
public IData not() {
return new DataByte((byte) (~value));
}
@Override
public String toString() {
return asString() + " as byte";
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/MarketOperations/impl/MarketOperationsFactoryImpl.java | 20399 | /**
*/
package gluemodel.CIM.IEC61970.Informative.MarketOperations.impl;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class MarketOperationsFactoryImpl extends EFactoryImpl implements MarketOperationsFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static MarketOperationsFactory init() {
try {
MarketOperationsFactory theMarketOperationsFactory = (MarketOperationsFactory)EPackage.Registry.INSTANCE.getEFactory(MarketOperationsPackage.eNS_URI);
if (theMarketOperationsFactory != null) {
return theMarketOperationsFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new MarketOperationsFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketOperationsFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case MarketOperationsPackage.NOTIFICATION_TIME_CURVE: return createNotificationTimeCurve();
case MarketOperationsPackage.ENERGY_PRICE_CURVE: return createEnergyPriceCurve();
case MarketOperationsPackage.METER: return createMeter();
case MarketOperationsPackage.MARKET_STATEMENT: return createMarketStatement();
case MarketOperationsPackage.CONTINGENCY_CONSTRAINT_LIMIT: return createContingencyConstraintLimit();
case MarketOperationsPackage.REGISTERED_GENERATOR: return createRegisteredGenerator();
case MarketOperationsPackage.TRANSACTION_BID: return createTransactionBid();
case MarketOperationsPackage.SECURITY_CONSTRAINTS: return createSecurityConstraints();
case MarketOperationsPackage.VIOLATION_LIMIT: return createViolationLimit();
case MarketOperationsPackage.START_UP_COST_CURVE: return createStartUpCostCurve();
case MarketOperationsPackage.DEFAULT_CONSTRAINT_LIMIT: return createDefaultConstraintLimit();
case MarketOperationsPackage.BILL_DETERMINANT: return createBillDeterminant();
case MarketOperationsPackage.LOAD_REDUCTION_PRICE_CURVE: return createLoadReductionPriceCurve();
case MarketOperationsPackage.CHARGE_PROFILE: return createChargeProfile();
case MarketOperationsPackage.SETTLEMENT: return createSettlement();
case MarketOperationsPackage.MARKET: return createMarket();
case MarketOperationsPackage.RESERVE_REQ: return createReserveReq();
case MarketOperationsPackage.REGISTERED_RESOURCE: return createRegisteredResource();
case MarketOperationsPackage.MARKET_PRODUCT: return createMarketProduct();
case MarketOperationsPackage.GENERATING_BID: return createGeneratingBid();
case MarketOperationsPackage.TERMINAL_CONSTRAINT_TERM: return createTerminalConstraintTerm();
case MarketOperationsPackage.RTO: return createRTO();
case MarketOperationsPackage.CONSTRAINT_TERM: return createConstraintTerm();
case MarketOperationsPackage.PASS_THROUGH_BILL: return createPassThroughBill();
case MarketOperationsPackage.PNODE: return createPnode();
case MarketOperationsPackage.PNODE_CLEARING: return createPnodeClearing();
case MarketOperationsPackage.START_UP_TIME_CURVE: return createStartUpTimeCurve();
case MarketOperationsPackage.SECURITY_CONSTRAINT_SUM: return createSecurityConstraintSum();
case MarketOperationsPackage.BASE_CASE_CONSTRAINT_LIMIT: return createBaseCaseConstraintLimit();
case MarketOperationsPackage.PRODUCT_BID: return createProductBid();
case MarketOperationsPackage.MW_LIMIT_SCHEDULE: return createMWLimitSchedule();
case MarketOperationsPackage.MARKET_STATEMENT_LINE_ITEM: return createMarketStatementLineItem();
case MarketOperationsPackage.ANCILLARY_SERVICE_CLEARING: return createAncillaryServiceClearing();
case MarketOperationsPackage.BID_SET: return createBidSet();
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING: return createSecurityConstraintsClearing();
case MarketOperationsPackage.PRODUCT_BID_CLEARING: return createProductBidClearing();
case MarketOperationsPackage.RESOURCE_BID: return createResourceBid();
case MarketOperationsPackage.CAPACITY_BENEFIT_MARGIN: return createCapacityBenefitMargin();
case MarketOperationsPackage.SCHEDULING_COORDINATOR: return createSchedulingCoordinator();
case MarketOperationsPackage.RAMP_RATE_CURVE: return createRampRateCurve();
case MarketOperationsPackage.BID_CLEARING: return createBidClearing();
case MarketOperationsPackage.LOAD_BID: return createLoadBid();
case MarketOperationsPackage.BID: return createBid();
case MarketOperationsPackage.FLOWGATE: return createFlowgate();
case MarketOperationsPackage.MARKET_FACTORS: return createMarketFactors();
case MarketOperationsPackage.FTR: return createFTR();
case MarketOperationsPackage.LOSS_PENALTY_FACTOR: return createLossPenaltyFactor();
case MarketOperationsPackage.RESOURCE_GROUP: return createResourceGroup();
case MarketOperationsPackage.UNIT_INITIAL_CONDITIONS: return createUnitInitialConditions();
case MarketOperationsPackage.REGISTERED_LOAD: return createRegisteredLoad();
case MarketOperationsPackage.RESERVE_REQ_CURVE: return createReserveReqCurve();
case MarketOperationsPackage.BILATERAL_TRANSACTION: return createBilateralTransaction();
case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE: return createSensitivityPriceCurve();
case MarketOperationsPackage.TRANSMISSION_RELIABILITY_MARGIN: return createTransmissionReliabilityMargin();
case MarketOperationsPackage.BID_PRICE_CURVE: return createBidPriceCurve();
case MarketOperationsPackage.RESOURCE_GROUP_REQ: return createResourceGroupReq();
case MarketOperationsPackage.CHARGE_PROFILE_DATA: return createChargeProfileData();
case MarketOperationsPackage.MARKET_CASE_CLEARING: return createMarketCaseClearing();
case MarketOperationsPackage.NODE_CONSTRAINT_TERM: return createNodeConstraintTerm();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationTimeCurve createNotificationTimeCurve() {
NotificationTimeCurveImpl notificationTimeCurve = new NotificationTimeCurveImpl();
return notificationTimeCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EnergyPriceCurve createEnergyPriceCurve() {
EnergyPriceCurveImpl energyPriceCurve = new EnergyPriceCurveImpl();
return energyPriceCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Meter createMeter() {
MeterImpl meter = new MeterImpl();
return meter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketStatement createMarketStatement() {
MarketStatementImpl marketStatement = new MarketStatementImpl();
return marketStatement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ContingencyConstraintLimit createContingencyConstraintLimit() {
ContingencyConstraintLimitImpl contingencyConstraintLimit = new ContingencyConstraintLimitImpl();
return contingencyConstraintLimit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RegisteredGenerator createRegisteredGenerator() {
RegisteredGeneratorImpl registeredGenerator = new RegisteredGeneratorImpl();
return registeredGenerator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TransactionBid createTransactionBid() {
TransactionBidImpl transactionBid = new TransactionBidImpl();
return transactionBid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SecurityConstraints createSecurityConstraints() {
SecurityConstraintsImpl securityConstraints = new SecurityConstraintsImpl();
return securityConstraints;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ViolationLimit createViolationLimit() {
ViolationLimitImpl violationLimit = new ViolationLimitImpl();
return violationLimit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StartUpCostCurve createStartUpCostCurve() {
StartUpCostCurveImpl startUpCostCurve = new StartUpCostCurveImpl();
return startUpCostCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DefaultConstraintLimit createDefaultConstraintLimit() {
DefaultConstraintLimitImpl defaultConstraintLimit = new DefaultConstraintLimitImpl();
return defaultConstraintLimit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BillDeterminant createBillDeterminant() {
BillDeterminantImpl billDeterminant = new BillDeterminantImpl();
return billDeterminant;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LoadReductionPriceCurve createLoadReductionPriceCurve() {
LoadReductionPriceCurveImpl loadReductionPriceCurve = new LoadReductionPriceCurveImpl();
return loadReductionPriceCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ChargeProfile createChargeProfile() {
ChargeProfileImpl chargeProfile = new ChargeProfileImpl();
return chargeProfile;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Settlement createSettlement() {
SettlementImpl settlement = new SettlementImpl();
return settlement;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Market createMarket() {
MarketImpl market = new MarketImpl();
return market;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReserveReq createReserveReq() {
ReserveReqImpl reserveReq = new ReserveReqImpl();
return reserveReq;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RegisteredResource createRegisteredResource() {
RegisteredResourceImpl registeredResource = new RegisteredResourceImpl();
return registeredResource;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketProduct createMarketProduct() {
MarketProductImpl marketProduct = new MarketProductImpl();
return marketProduct;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public GeneratingBid createGeneratingBid() {
GeneratingBidImpl generatingBid = new GeneratingBidImpl();
return generatingBid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TerminalConstraintTerm createTerminalConstraintTerm() {
TerminalConstraintTermImpl terminalConstraintTerm = new TerminalConstraintTermImpl();
return terminalConstraintTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RTO createRTO() {
RTOImpl rto = new RTOImpl();
return rto;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ConstraintTerm createConstraintTerm() {
ConstraintTermImpl constraintTerm = new ConstraintTermImpl();
return constraintTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PassThroughBill createPassThroughBill() {
PassThroughBillImpl passThroughBill = new PassThroughBillImpl();
return passThroughBill;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Pnode createPnode() {
PnodeImpl pnode = new PnodeImpl();
return pnode;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PnodeClearing createPnodeClearing() {
PnodeClearingImpl pnodeClearing = new PnodeClearingImpl();
return pnodeClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StartUpTimeCurve createStartUpTimeCurve() {
StartUpTimeCurveImpl startUpTimeCurve = new StartUpTimeCurveImpl();
return startUpTimeCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SecurityConstraintSum createSecurityConstraintSum() {
SecurityConstraintSumImpl securityConstraintSum = new SecurityConstraintSumImpl();
return securityConstraintSum;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BaseCaseConstraintLimit createBaseCaseConstraintLimit() {
BaseCaseConstraintLimitImpl baseCaseConstraintLimit = new BaseCaseConstraintLimitImpl();
return baseCaseConstraintLimit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProductBid createProductBid() {
ProductBidImpl productBid = new ProductBidImpl();
return productBid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MWLimitSchedule createMWLimitSchedule() {
MWLimitScheduleImpl mwLimitSchedule = new MWLimitScheduleImpl();
return mwLimitSchedule;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketStatementLineItem createMarketStatementLineItem() {
MarketStatementLineItemImpl marketStatementLineItem = new MarketStatementLineItemImpl();
return marketStatementLineItem;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AncillaryServiceClearing createAncillaryServiceClearing() {
AncillaryServiceClearingImpl ancillaryServiceClearing = new AncillaryServiceClearingImpl();
return ancillaryServiceClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BidSet createBidSet() {
BidSetImpl bidSet = new BidSetImpl();
return bidSet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SecurityConstraintsClearing createSecurityConstraintsClearing() {
SecurityConstraintsClearingImpl securityConstraintsClearing = new SecurityConstraintsClearingImpl();
return securityConstraintsClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProductBidClearing createProductBidClearing() {
ProductBidClearingImpl productBidClearing = new ProductBidClearingImpl();
return productBidClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceBid createResourceBid() {
ResourceBidImpl resourceBid = new ResourceBidImpl();
return resourceBid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CapacityBenefitMargin createCapacityBenefitMargin() {
CapacityBenefitMarginImpl capacityBenefitMargin = new CapacityBenefitMarginImpl();
return capacityBenefitMargin;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SchedulingCoordinator createSchedulingCoordinator() {
SchedulingCoordinatorImpl schedulingCoordinator = new SchedulingCoordinatorImpl();
return schedulingCoordinator;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RampRateCurve createRampRateCurve() {
RampRateCurveImpl rampRateCurve = new RampRateCurveImpl();
return rampRateCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BidClearing createBidClearing() {
BidClearingImpl bidClearing = new BidClearingImpl();
return bidClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LoadBid createLoadBid() {
LoadBidImpl loadBid = new LoadBidImpl();
return loadBid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Bid createBid() {
BidImpl bid = new BidImpl();
return bid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Flowgate createFlowgate() {
FlowgateImpl flowgate = new FlowgateImpl();
return flowgate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketFactors createMarketFactors() {
MarketFactorsImpl marketFactors = new MarketFactorsImpl();
return marketFactors;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FTR createFTR() {
FTRImpl ftr = new FTRImpl();
return ftr;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public LossPenaltyFactor createLossPenaltyFactor() {
LossPenaltyFactorImpl lossPenaltyFactor = new LossPenaltyFactorImpl();
return lossPenaltyFactor;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceGroup createResourceGroup() {
ResourceGroupImpl resourceGroup = new ResourceGroupImpl();
return resourceGroup;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public UnitInitialConditions createUnitInitialConditions() {
UnitInitialConditionsImpl unitInitialConditions = new UnitInitialConditionsImpl();
return unitInitialConditions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RegisteredLoad createRegisteredLoad() {
RegisteredLoadImpl registeredLoad = new RegisteredLoadImpl();
return registeredLoad;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReserveReqCurve createReserveReqCurve() {
ReserveReqCurveImpl reserveReqCurve = new ReserveReqCurveImpl();
return reserveReqCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BilateralTransaction createBilateralTransaction() {
BilateralTransactionImpl bilateralTransaction = new BilateralTransactionImpl();
return bilateralTransaction;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SensitivityPriceCurve createSensitivityPriceCurve() {
SensitivityPriceCurveImpl sensitivityPriceCurve = new SensitivityPriceCurveImpl();
return sensitivityPriceCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TransmissionReliabilityMargin createTransmissionReliabilityMargin() {
TransmissionReliabilityMarginImpl transmissionReliabilityMargin = new TransmissionReliabilityMarginImpl();
return transmissionReliabilityMargin;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BidPriceCurve createBidPriceCurve() {
BidPriceCurveImpl bidPriceCurve = new BidPriceCurveImpl();
return bidPriceCurve;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ResourceGroupReq createResourceGroupReq() {
ResourceGroupReqImpl resourceGroupReq = new ResourceGroupReqImpl();
return resourceGroupReq;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ChargeProfileData createChargeProfileData() {
ChargeProfileDataImpl chargeProfileData = new ChargeProfileDataImpl();
return chargeProfileData;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketCaseClearing createMarketCaseClearing() {
MarketCaseClearingImpl marketCaseClearing = new MarketCaseClearingImpl();
return marketCaseClearing;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NodeConstraintTerm createNodeConstraintTerm() {
NodeConstraintTermImpl nodeConstraintTerm = new NodeConstraintTermImpl();
return nodeConstraintTerm;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MarketOperationsPackage getMarketOperationsPackage() {
return (MarketOperationsPackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static MarketOperationsPackage getPackage() {
return MarketOperationsPackage.eINSTANCE;
}
} //MarketOperationsFactoryImpl
| mit |
gvaish/objectify-appengine | src/com/googlecode/objectify/impl/ref/ProxyRef.java | 1507 | package com.googlecode.objectify.impl.ref;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.Result;
/**
* <p>An implementation of Ref that works like a proxy. We can't create dynamic proxies on abstract classes
* and we don't want to suck in a bytecode manipulator dependency so we have to create this by hand. No big deal.</p>
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
abstract public class ProxyRef<T> extends Ref<T>
{
private static final long serialVersionUID = 1L;
/** */
Ref<T> cached;
/** Implement this to provide the real, non-proxied Ref */
abstract protected Ref<T> ref();
/* (non-Javadoc)
* @see com.googlecode.objectify.Ref#key()
*/
@Override
final public Key<T> key() {
return getRef().key();
}
/* (non-Javadoc)
* @see com.googlecode.objectify.Ref#get()
*/
@Override
final public T get() {
return getRef().get();
}
/* (non-Javadoc)
* @see com.googlecode.objectify.Ref#getValue()
*/
@Override
public T getValue() {
return getRef().getValue();
}
/* (non-Javadoc)
* @see com.googlecode.objectify.Ref#set(com.googlecode.objectify.Result)
*/
@Override
final public void set(Result<T> value) {
getRef().set(value);
}
/** Checks for the cached instance, if not there get it from ref() */
private final Ref<T> getRef() {
if (this.cached == null)
this.cached = ref();
return this.cached;
}
} | mit |
mainini/stiam-sender | src/main/java/ch/bfh/ti/ictm/iam/stiam/aa/directory/DirectoryFactory.java | 1942 | /*
* Copyright 2014 Pascal Mainini, Marc Kunz
* Licensed under MIT license, see included file LICENSE or
* http://opensource.org/licenses/MIT
*/
package ch.bfh.ti.ictm.iam.stiam.aa.directory;
import ch.bfh.ti.ictm.iam.stiam.aa.directory.ldap.DirectoryImpl;
import ch.bfh.ti.ictm.iam.stiam.aa.directory.property.PropertyDirectory;
import ch.bfh.ti.ictm.iam.stiam.aa.util.StiamConfiguration;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
* A factory creating Directory-instances based on configuration. This is a
* singleton.
*
* @author Pascal Mainini
* @author Marc Kunz
*/
public class DirectoryFactory {
//////////////////////////////////////// Fields
private static final Logger logger = getLogger(StiamConfiguration.class);
private static final DirectoryFactory instance = new DirectoryFactory();
private static Directory directoryInstance;
//////////////////////////////////////// Constructors
/**
* Private constructor, initializes the configured directory.
*/
private DirectoryFactory() {
String directoryType = StiamConfiguration.getInstance().getDirectory();
if (directoryType.equalsIgnoreCase("ldap")) {
directoryInstance = new DirectoryImpl();
} else if (directoryType.equalsIgnoreCase("property")) {
directoryInstance = new PropertyDirectory();
} else {
logger.error("Unknown directory type found in configuration: {}", directoryType);
directoryInstance = null;
}
}
//////////////////////////////////////// Methods
/**
* @return The one and only instance of this factory. (Singleton)
*/
public static DirectoryFactory getInstance() {
return instance;
}
/**
* @return An instance of Directory, depending on the configuration.
*/
public Directory createDirectory() {
return directoryInstance;
}
}
| mit |
damorton/dropwizardheroku-webgateway | src/test/java/com/bitbosh/lovat/webgateway/resources/WebGatewayResourceUnitTest.java | 2782 | package com.bitbosh.lovat.webgateway.resources;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;
import com.bitbosh.lovat.webgateway.api.ApiResponse;
import com.bitbosh.lovat.webgateway.api.NashornController;
import com.bitbosh.lovat.webgateway.core.User;
import com.bitbosh.lovat.webgateway.repository.WebGatewayDao;
import io.dropwizard.auth.Auth;
import mockit.Expectations;
import mockit.Mocked;
public class WebGatewayResourceUnitTest {
@Test
public void EventResource_constructsSuccessfully_IfEventDaoNotNull(@Mocked DBI jdbi, @Mocked WebGatewayDao eventDao,
@Mocked Client client, @Mocked NashornController react) {
new Expectations() {
{
jdbi.onDemand(withAny(WebGatewayDao.class));
result = eventDao; // return valid EventDao
}
};
WebGatewayResource eventResource = new WebGatewayResource(jdbi, client, react);
}
@Test
public void getEvents_returnsCorrectApiResponce_IfEventsListRequested(@Mocked DBI jdbi, @Mocked Client client,
@Mocked WebTarget webTarget, @Mocked Invocation.Builder invocationBuilder, @Mocked Response response,
@Mocked ApiResponse apiResponse, @Mocked NashornController react, @Auth User user) {
new Expectations() {
{
client.target(WebGatewayResource.kEventServiceApiEndpointEvents);
result = webTarget;
webTarget.request(MediaType.APPLICATION_JSON);
result = invocationBuilder;
invocationBuilder.get();
result = response;
response.readEntity(withAny(ApiResponse.class));
result = apiResponse;
}
};
WebGatewayResource webGatewayResource = new WebGatewayResource(jdbi, client, react);
ApiResponse actualResponse = webGatewayResource.getEvents();
assertEquals(apiResponse, actualResponse);
}
@Test
public void successfulPostToEventsService(@Mocked DBI jdbi, @Mocked Client client,
@Mocked WebTarget webTarget, @Mocked Invocation.Builder invocationBuilder, @Mocked Response response,
@Mocked ApiResponse apiResponse, @Mocked NashornController react, @Auth User user) {
new Expectations() {
{
client.target(WebGatewayResource.kEventServiceApiEndpointEvents);
result = webTarget;
webTarget.request(MediaType.APPLICATION_JSON);
result = invocationBuilder;
invocationBuilder.get();
result = response;
response.readEntity(withAny(ApiResponse.class));
result = apiResponse;
}
};
WebGatewayResource webGatewayResource = new WebGatewayResource(jdbi, client, react);
ApiResponse actualResponse = webGatewayResource.getEvents();
assertEquals(apiResponse, actualResponse);
}
}
| mit |
rterp/LimitUpTrading | commons/sumzero-commons-api/src/main/java/com/sumzerotrading/time/ITimeProvider.java | 1767 | /**
* MIT License
Copyright (c) 2015 Rob Terpilowski
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.sumzerotrading.time;
/**
*
* @author RobTerpilowski
*/
public interface ITimeProvider {
/**
* Starts the specified time provider
*/
public void start();
/**
* Stops the specified time provider
*/
public void stop();
/**
* Adds the specified time update listener
*
* @param listener The listener to add.
*/
public void addTimeUpdatedListener( TimeUpdatedListener listener );
/**
* Removes the specified time update listener
*
* @param listener The listener to remove.
*/
public void removeTimeUpdatedListener( TimeUpdatedListener listener );
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2018_12_01/src/main/java/com/microsoft/azure/management/network/v2018_12_01/implementation/AzureFirewallFqdnTagImpl.java | 1938 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_12_01.implementation;
import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl;
import com.microsoft.azure.management.network.v2018_12_01.AzureFirewallFqdnTag;
import rx.Observable;
class AzureFirewallFqdnTagImpl extends GroupableResourceCoreImpl<AzureFirewallFqdnTag, AzureFirewallFqdnTagInner, AzureFirewallFqdnTagImpl, NetworkManager> implements AzureFirewallFqdnTag {
AzureFirewallFqdnTagImpl(String name, AzureFirewallFqdnTagInner inner, NetworkManager manager) {
super(name, inner, manager);
}
@Override
public Observable<AzureFirewallFqdnTag> createResourceAsync() {
AzureFirewallFqdnTagsInner client = this.manager().inner().azureFirewallFqdnTags();
return null; // NOP createResourceAsync implementation as create is not supported
}
@Override
public Observable<AzureFirewallFqdnTag> updateResourceAsync() {
AzureFirewallFqdnTagsInner client = this.manager().inner().azureFirewallFqdnTags();
return null; // NOP updateResourceAsync implementation as update is not supported
}
@Override
protected Observable<AzureFirewallFqdnTagInner> getInnerAsync() {
AzureFirewallFqdnTagsInner client = this.manager().inner().azureFirewallFqdnTags();
return null; // NOP getInnerAsync implementation as get is not supported
}
@Override
public String etag() {
return this.inner().etag();
}
@Override
public String fqdnTagName() {
return this.inner().fqdnTagName();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
}
| mit |
andreasronge/lucene | examples/you_might_know/YouMightKnow.java | 2005 | class YouMightKnow
{
List<List<Node>> result = new ArrayList<List<Node>>();
int maxDistance;
String[] features;
Object[] values;
Set<Node> buddies = new HashSet<Node>();
YouMightKnow( Node node, String[] features, int maxDistance )
{
this.features = features;
this.maxDistance = maxDistance;
values = new Object[features.length];
List<Integer> matches = new ArrayList<Integer>();
for ( int i = 0; i < features.length; i++ )
{
values[i] = node.getProperty( features[i] );
matches.add( i );
}
for ( Relationship rel : node.getRelationships( RelationshipTypes.KNOWS ) )
{
buddies.add( rel.getOtherNode( node ) );
}
findFriends( Arrays.asList( new Node[] { node } ), matches, 1 );
}
void findFriends( List<Node> path, List<Integer> matches, int depth )
{
Node prevNode = path.get( path.size() - 1 );
for ( Relationship rel : prevNode.getRelationships( RelationshipTypes.KNOWS ) )
{
Node node = rel.getOtherNode( prevNode );
if ( (depth > 1 && buddies.contains( node )) || path.contains( node ) )
{
continue;
}
List<Integer> newMatches = new ArrayList<Integer>();
for ( int match : matches )
{
if ( node.getProperty( features[match] ).equals( values[match] ) )
{
newMatches.add( match );
}
}
if ( newMatches.size() > 0 )
{
List<Node> newPath = new ArrayList<Node>( path );
newPath.add( node );
if ( depth > 1 )
{
result.add( newPath );
}
if ( depth != maxDistance )
{
findFriends( newPath, newMatches, depth + 1 );
}
}
}
}
} | mit |
drdaemos/LifeLiveWP | rajawali/src/main/java/rajawali/primitives/Plane.java | 8912 | /**
* Copyright 2013 Dennis Ippel
*
* 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 rajawali.primitives;
import rajawali.Object3D;
import rajawali.math.vector.Vector3.Axis;
/**
* A plane primitive. The constructor takes two boolean arguments that indicate whether certain buffers should be
* created or not. Not creating these buffers can reduce memory footprint.
* <p>
* When creating solid color plane both <code>createTextureCoordinates</code> and <code>createVertexColorBuffer</code>
* can be set to <code>false</code>.
* <p>
* When creating a textured plane <code>createTextureCoordinates</code> should be set to <code>true</code> and
* <code>createVertexColorBuffer</code> should be set to <code>false</code>.
* <p>
* When creating a plane without a texture but with different colors per texture <code>createTextureCoordinates</code>
* should be set to <code>false</code> and <code>createVertexColorBuffer</code> should be set to <code>true</code>.
*
* @author dennis.ippel
*
*/
public class Plane extends Object3D {
protected float mWidth;
protected float mHeight;
protected int mSegmentsW;
protected int mSegmentsH;
protected int mNumTextureTiles;
private boolean mCreateTextureCoords;
private boolean mCreateVertexColorBuffer;
private Axis mUpAxis;
/**
* Create a plane primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
* The plane will be facing the camera ({@link Axis.Z}) by default.
*/
public Plane() {
this(1f, 1f, 1, 1, Axis.Z, true, false, 1);
}
/**
* Create a plane primitive. Calling this constructor will create a plane facing the specified axis.
* @param upAxis
*/
public Plane(Axis upAxis)
{
this(1f, 1f, 1, 1, upAxis, true, false, 1);
}
/**
* Create a plane primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
* The plane will be facing the camera ({@link Axis.Z}) by default.
*
* @param width
* The plane width
* @param height
* The plane height
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
*/
public Plane(float width, float height, int segmentsW, int segmentsH)
{
this(width, height, segmentsW, segmentsH, Axis.Z, true, false, 1);
}
/**
* Create a plane primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
* The plane will be facing the camera ({@link Axis.Z}) by default.
*
* @param width
* The plane width
* @param height
* The plane height
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
* @param numTextureTiles
* The number of texture tiles. If more than 1 the texture will be repeat by n times.
*/
public Plane(float width, float height, int segmentsW, int segmentsH, int numTextureTiles)
{
this(width, height, segmentsW, segmentsH, Axis.Z, true, false, numTextureTiles);
}
/**
* Create a plane primitive. Calling this constructor will create texture coordinates but no vertex color buffer.
*
* @param width
* The plane width
* @param height
* The plane height
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
* @param upAxis
* The up axis. Choose Axis.Y for a ground plane and Axis.Z for a camera facing plane.
*/
public Plane(float width, float height, int segmentsW, int segmentsH, Axis upAxis)
{
this(width, height, segmentsW, segmentsH, upAxis, true, false, 1);
}
/**
* Creates a plane primitive.
*
* @param width
* The plane width
* @param height
* The plane height
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
* @param upAxis
* The up axis. Choose Axis.Y for a ground plane and Axis.Z for a camera facing plane.
* @param createTextureCoordinates
* A boolean that indicates whether the texture coordinates should be calculated or not.
* @param createVertexColorBuffer
* A boolean that indicates whether a vertex color buffer should be created or not.
*/
public Plane(float width, float height, int segmentsW, int segmentsH, Axis upAxis, boolean createTextureCoordinates,
boolean createVertexColorBuffer) {
this(width, height, segmentsW, segmentsH, upAxis, createTextureCoordinates, createVertexColorBuffer, 1);
}
/**
* Creates a plane primitive.
*
* @param width
* The plane width
* @param height
* The plane height
* @param segmentsW
* The number of vertical segments
* @param segmentsH
* The number of horizontal segments
* @param upAxis
* The up axis. Choose Axis.Y for a ground plane and Axis.Z for a camera facing plane.
* @param createTextureCoordinates
* A boolean that indicates whether the texture coordinates should be calculated or not.
* @param createVertexColorBuffer
* A boolean that indicates whether a vertex color buffer should be created or not.
* @param numTextureTiles
* The number of texture tiles. If more than 1 the texture will be repeat by n times.
*/
public Plane(float width, float height, int segmentsW, int segmentsH, Axis upAxis, boolean createTextureCoordinates,
boolean createVertexColorBuffer, int numTextureTiles) {
super();
mWidth = width;
mHeight = height;
mSegmentsW = segmentsW;
mSegmentsH = segmentsH;
mUpAxis = upAxis;
mCreateTextureCoords = createTextureCoordinates;
mCreateVertexColorBuffer = createVertexColorBuffer;
mNumTextureTiles = numTextureTiles;
init();
}
private void init() {
int i, j;
int numVertices = (mSegmentsW + 1) * (mSegmentsH + 1);
float[] vertices = new float[numVertices * 3];
float[] textureCoords = null;
if (mCreateTextureCoords)
textureCoords = new float[numVertices * 2];
float[] normals = new float[numVertices * 3];
float[] colors = null;
if (mCreateVertexColorBuffer)
colors = new float[numVertices * 4];
int[] indices = new int[mSegmentsW * mSegmentsH * 6];
int vertexCount = 0;
int texCoordCount = 0;
for (i = 0; i <= mSegmentsW; i++) {
for (j = 0; j <= mSegmentsH; j++) {
float v1 = ((float) i / (float) mSegmentsW - 0.5f) * mWidth;
float v2 = ((float) j / (float) mSegmentsH - 0.5f) * mHeight;
if(mUpAxis == Axis.X)
{
vertices[vertexCount] = 0;
vertices[vertexCount + 1] = v1;
vertices[vertexCount + 2] = v2;
}
else if(mUpAxis == Axis.Y)
{
vertices[vertexCount] = v1;
vertices[vertexCount + 1] = 0;
vertices[vertexCount + 2] = v2;
}
else if(mUpAxis == Axis.Z)
{
vertices[vertexCount] = v1;
vertices[vertexCount + 1] = v2;
vertices[vertexCount + 2] = 0;
}
if (mCreateTextureCoords) {
float u = (float) i / (float) mSegmentsW;
textureCoords[texCoordCount++] = (1.0f - u) * mNumTextureTiles;
float v = (float) j / (float) mSegmentsH;
textureCoords[texCoordCount++] = (1.0f - v) * mNumTextureTiles;
}
normals[vertexCount] = mUpAxis == Axis.X ? 1 : 0;
normals[vertexCount + 1] = mUpAxis == Axis.Y ? 1 : 0;
normals[vertexCount + 2] = mUpAxis == Axis.Z ? 1 : 0;
vertexCount += 3;
}
}
int colspan = mSegmentsH + 1;
int indexCount = 0;
for (int col = 0; col < mSegmentsW; col++) {
for (int row = 0; row < mSegmentsH; row++) {
int ul = col * colspan + row;
int ll = ul + 1;
int ur = (col + 1) * colspan + row;
int lr = ur + 1;
indices[indexCount++] = (int) ur;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) lr;
indices[indexCount++] = (int) ul;
indices[indexCount++] = (int) ll;
}
}
if (mCreateVertexColorBuffer)
{
int numColors = numVertices * 4;
for (j = 0; j < numColors; j += 4)
{
colors[j] = 1.0f;
colors[j + 1] = 1.0f;
colors[j + 2] = 1.0f;
colors[j + 3] = 1.0f;
}
}
setData(vertices, normals, textureCoords, colors, indices);
vertices = null;
normals = null;
textureCoords = null;
colors = null;
indices = null;
}
} | mit |
RyanTech/Skittles | skittles/src/main/java/snow/skittles/SkittleBuilder.java | 8463 | package snow.skittles;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
/**
* Utility class for managing the addition of skittles and click events
*/
@SuppressWarnings("ALL")
public class SkittleBuilder {
private static SkittleLayout mSkittleLayout;
private TextSkittle textSkittle;
private Context context;
private int skittleCount = 1;
private int color;
private SkittleClickListener mListener;
/**
* Interface for click events
*/
public interface SkittleClickListener {
void onSkittleClick(Skittle skittle);
void onTextSkittleClick(TextSkittle textSkittle);
}
private SkittleBuilder(Builder builder) {
setUp(builder.mContext, builder.mSkittleLayout, builder.animatable, builder.miniSkittleColor);
mSkittleLayout.setMainSkittleColor(builder.mainSkittleColor);
}
private void setUp(@NonNull Context context, @NonNull SkittleLayout mSkittleLayout, boolean animatable
, @Nullable Integer color) {
this.mSkittleLayout = mSkittleLayout;
this.context = context;
this.color = color;
mSkittleLayout.setMainSkittleAnimatable(animatable);
}
/**
* Call this to change the icon of the main skitlle ie the normal sized FloatingActionButton
*
* @param icon
*/
public void setMainSkittleIcon(@NonNull Drawable icon) {
FloatingActionButton mSkittle = (FloatingActionButton) mSkittleLayout.findViewById(R.id.skittle_main);
if (icon != null)
mSkittle.setImageDrawable(icon);
}
/**
* Call this to change the color of the main skittle,use this method only if you want to
* change the color of the main skittle dynamically, else use the constructor @see #SkittleBuilder(@NonNull Context
* , @NonNull SkittleLayout, boolean animatable, @Nullable Integer, int)
*
* @param color you can pass either a reference or a generated color,you can pass either
* a reference or a generated color
*/
public void setMainSkittleColor(int color) {
mSkittleLayout.setMainSkittleColor(color);
}
/**
* Call this to add a simple skittle
*
* @param icon
*/
public void addSkittle(@NonNull int icon) {
mSkittleLayout.addFab(setUpMiniSkittle(icon));
}
public void addSkittle(@NonNull int icon, int color) {
Skittle skittle = setUpMiniSkittle(icon);
skittle.setBackgroundTintList(Utils.getColorStateList(color, context));
mSkittleLayout.addFab(skittle);
}
private Skittle setUpMiniSkittle(int icon) {
Skittle skittle = (Skittle) LayoutInflater.from(context)
.inflate(R.layout.action_skittle, mSkittleLayout.getSkittleContainer(), false);
skittle.setImageDrawable(context.getResources().getDrawable(icon));
skittle.setAlpha(0f);
skittle.setClickability(false);
skittle.setBackgroundTintList(Utils.getColorStateList(color, context));
skittle.setOnClickListener(mSkittleClickListener);
skittle.setPosition(skittleCount++);
return skittle;
}
public TextSkittleBuilder makeTextSkittle(String text, @DrawableRes int icon) {
return new TextSkittleBuilder(text, icon);
}
private void addTextSkittle(TextSkittle textSkittle) {
textSkittle.setAlpha(0f);
textSkittle.setPosition(skittleCount++);
mSkittleLayout.addFab(textSkittle);
textSkittle.getSkittle().setOnClickListener(mTextSkittleClickListener);
}
View.OnClickListener mSkittleClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Skittles", "Skittle Click");
Skittle skittle = (Skittle) v;
if (v.isClickable() && getmListener() != null)
getmListener().onSkittleClick((Skittle) v);
}
};
View.OnClickListener mTextSkittleClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Skittles", "Text Skittle Click");
Skittle skittle = (Skittle) v;
if (v.isClickable() && getmListener() != null)
getmListener().onTextSkittleClick((TextSkittle) v.getParent());
}
};
public SkittleClickListener getmListener() {
return mListener;
}
/**
* Call this method for setting the click listener for the skittles
*
* @param mListener
*/
public void setSkittleListener(@NonNull SkittleClickListener mListener) {
this.mListener = mListener;
}
/**
* Call this method to manually toggle the skittle menu
*/
public void toggleSkittleMenu() {
mSkittleLayout.animateMiniSkittles();
}
/**
* Convenient builder pattern for instantiating the SkittleBuilder
*/
public static class Builder {
private final SkittleLayout mSkittleLayout;
private final Context mContext;
private boolean animatable;
private int mainSkittleColor, miniSkittleColor;
private Drawable mainSkittleIcon;
public Builder(Context mContext, SkittleLayout mSkittleLayout) {
this.mContext = mContext;
this.mSkittleLayout = mSkittleLayout;
}
public Builder animatable(boolean animatable) {
this.animatable = animatable;
return this;
}
public Builder mainSkittleColor(int color) {
this.mainSkittleColor = color;
return this;
}
public Builder miniSkittleColor(int color) {
this.miniSkittleColor = color;
return this;
}
public Builder mainSkittleIcon(@DrawableRes int iconRes) {
this.mainSkittleIcon = mContext.getResources().getDrawable(iconRes);
return this;
}
public SkittleBuilder build() {
return new SkittleBuilder(this);
}
}
/**
* Convenient builder pattern for creating @link snow.skittles.TextSkittle
*/
public class TextSkittleBuilder {
private final TextView textView;
private final FloatingActionButton miniSkittle;
private final TextSkittle textSkittle;
public TextSkittleBuilder(String text, @DrawableRes int icon) {
textSkittle = (TextSkittle) LayoutInflater.from(context)
.inflate(R.layout.text_action_skittle, mSkittleLayout.getSkittleContainer(), false);
textView = textSkittle.getTextView();
textView.setText(text);
miniSkittle = textSkittle.getSkittle();
miniSkittle.setImageDrawable(context.getResources().getDrawable(icon));
}
public TextSkittleBuilder setTextColor(@ColorRes int textColor) {
textView.setTextColor(context.getResources().getColor(textColor));
return this;
}
public TextSkittleBuilder setTextSize(@DimenRes int size) {
textView.setTextSize(context.getResources().getDimensionPixelSize(size));
return this;
}
public TextSkittleBuilder setTextBackgroundColor(@ColorRes int backgroundColor) {
textView.setBackgroundColor(context.getResources().getColor(backgroundColor));
return this;
}
public TextSkittleBuilder setTextBackground(@DrawableRes int drawable) {
textView.setBackground(context.getResources().getDrawable(drawable));
return this;
}
public TextSkittleBuilder setSkittleColor(int color) {
miniSkittle.setBackgroundTintList(Utils.getColorStateList(color, context));
return this;
}
public TextSkittleBuilder setSkittleIcon(@DrawableRes int drawable) {
miniSkittle.setImageDrawable(context.getResources().getDrawable(drawable));
return this;
}
public void add() {
addTextSkittle(textSkittle);
}
}
}
| mit |
liufeiit/tulip | stats/core/src/main/java/analytics/core/dao/DAOException.java | 485 | package analytics.core.dao;
/**
*
* @author 刘飞 E-mail:liufei_it@126.com
* @version 1.0
* @since 2014年8月19日 下午2:46:38
*/
public class DAOException extends Exception {
private static final long serialVersionUID = 1L;
public DAOException() {
super();
}
public DAOException(String message, Throwable cause) {
super(message, cause);
}
public DAOException(String message) {
super(message);
}
public DAOException(Throwable cause) {
super(cause);
}
} | mit |
tsauerwein/mapfish-print | core/src/main/java/org/mapfish/print/wrapper/PAbstractObject.java | 5973 | /*
* Copyright (C) 2014 Camptocamp
*
* This file is part of MapFish Print
*
* MapFish Print 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.
*
* MapFish Print 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 MapFish Print. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mapfish.print.wrapper;
/**
* Abstract class for PObject implementation.
*
* @author Stéphane Brunner on 11/04/14.
*/
public abstract class PAbstractObject extends PElement implements PObject {
/**
* Constructor.
*
* @param parent the parent element
* @param contextName the field name of this element in the parent.
*/
public PAbstractObject(final PElement parent, final String contextName) {
super(parent, contextName);
}
/**
* Get a property as a string or throw an exception.
* @param key the property name
*/
@Override
public final String getString(final String key) {
String result = optString(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a string or defaultValue.
* @param key the property name
* @param defaultValue the default value
*/
@Override
public final String optString(final String key, final String defaultValue) {
String result = optString(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as an int or throw an exception.
* @param key the property name
*/
@Override
public final int getInt(final String key) {
Integer result = optInt(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as an int or default value.
* @param key the property name
* @param defaultValue the default value
*/
@Override
public final Integer optInt(final String key, final Integer defaultValue) {
Integer result = optInt(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as a double or throw an exception.
* @param key the property name
*/
@Override
public final double getDouble(final String key) {
Double result = optDouble(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a double or defaultValue.
* @param key the property name
* @param defaultValue the default value
*/
@Override
public final Double optDouble(final String key, final Double defaultValue) {
Double result = optDouble(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as a float or throw an exception.
* @param key the property name
*/
@Override
public final float getFloat(final String key) {
Float result = optFloat(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a float or Default value.
* @param key the property name
* @param defaultValue default value
*/
@Override
public final Float optFloat(final String key, final Float defaultValue) {
Float result = optFloat(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as a boolean or throw exception.
* @param key the property name
*/
@Override
public final boolean getBool(final String key) {
Boolean result = optBool(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a boolean or default value.
* @param key the property name
* @param defaultValue the default
*/
@Override
public final Boolean optBool(final String key, final Boolean defaultValue) {
Boolean result = optBool(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as a object or throw exception.
* @param key the property name
*/
@Override
public final PObject getObject(final String key) {
PObject result = optObject(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a array or default.
* @param key the property name
* @param defaultValue default
*/
@Override
public final PObject optObject(final String key, final PObject defaultValue) {
PObject result = optObject(key);
return result == null ? defaultValue : result;
}
/**
* Get a property as a array or throw exception.
* @param key the property name
*/
@Override
public final PArray getArray(final String key) {
PArray result = optArray(key);
if (result == null) {
throw new ObjectMissingException(this, key);
}
return result;
}
/**
* Get a property as a array or default.
* @param key the property name
* @param defaultValue default
*/
@Override
public final PArray optArray(final String key, final PArray defaultValue) {
PArray result = optArray(key);
return result == null ? defaultValue : result;
}
}
| mit |
safris-src/org | lib4j/xml/datatype/src/main/java/org/lib4j/xml/datatype/YearMonth.java | 4055 | /* Copyright (c) 2006 lib4j
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.lib4j.xml.datatype;
import java.io.Serializable;
import java.util.TimeZone;
/**
* http://www.w3.org/TR/xmlschema11-2/#gYearMonth
*/
public class YearMonth extends TemporalType implements Serializable {
private static final long serialVersionUID = -5629415172932276877L;
public static String print(final YearMonth yearMonth) {
return yearMonth == null ? null : yearMonth.toString();
}
public static YearMonth parse(String string) {
if (string == null)
return null;
string = string.trim();
if (string.length() < YEAR_MONTH_FRAG_MIN_LENGTH)
throw new IllegalArgumentException("year-month == " + string);
final int year = Year.parseYearFrag(string);
int index = string.indexOf("-", Year.YEAR_FRAG_MIN_LENGTH);
final int month = Month.parseMonthFrag(string.substring(index + 1));
index = string.indexOf("Z", YEAR_MONTH_FRAG_MIN_LENGTH);
if (index == -1)
index = string.indexOf("-", YEAR_MONTH_FRAG_MIN_LENGTH);
if (index == -1)
index = string.indexOf("+", YEAR_MONTH_FRAG_MIN_LENGTH);
final TimeZone timeZone = index == -1 ? null : Time.parseTimeZoneFrag(string.substring(index));
return new YearMonth(year, month, timeZone);
}
protected static final int YEAR_MONTH_FRAG_MIN_LENGTH = Year.YEAR_FRAG_MIN_LENGTH + 1 + Month.MONTH_FRAG_MIN_LENGTH;
private final Year year;
private final Month month;
private final long epochTime;
@SuppressWarnings("deprecation")
protected YearMonth(final Year year, final Month month, final TimeZone timeZone) {
super(timeZone);
this.year = year;
this.month = month;
epochTime = java.util.Date.UTC(year.getYear() - 1900, month.getMonth() - 1, 1, 0, 0, 0) - getTimeZone().getRawOffset() - getTimeZone().getDSTSavings();
}
public YearMonth(final int year, final int month, final TimeZone timeZone) {
this(new Year(year, timeZone), new Month(month, timeZone), timeZone);
}
public YearMonth(final int year, final int month) {
this(year, month, null);
}
public YearMonth(final long time, final TimeZone timeZone) {
this(new Year(time, timeZone), new Month(time), timeZone);
}
public YearMonth(final long time) {
this(new Year(time), new Month(time), null);
}
public YearMonth() {
this(System.currentTimeMillis());
}
public int getYear() {
return year.getYear();
}
public int getMonth() {
return month.getMonth();
}
public long getTime() {
return epochTime;
}
@Override
protected String toEmbededString() {
final StringBuilder builder = new StringBuilder();
builder.append(year.toEmbededString()).append('-');
if (getMonth() < 10)
builder.append('0');
builder.append(getMonth());
return builder.toString();
}
@Override
public boolean equals(final Object obj) {
if (obj == this)
return true;
if (!(obj instanceof YearMonth))
return false;
final YearMonth that = (YearMonth)obj;
return super.equals(obj) && (year != null ? year.equals(that.year) : that.year == null) && (month != null ? month.equals(that.month) : that.month == null);
}
@Override
public int hashCode() {
return super.hashCode() + (year != null ? year.hashCode() : -1) + (month != null ? month.hashCode() : -1);
}
} | mit |
bhewett/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/contracts/productadmin/ProductCategory.java | 883 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.productadmin;
import org.joda.time.DateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
/**
* The site category to which a product belongs.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ProductCategory implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
/**
* Unique identifier for the storefront container used to organize products.
*/
protected Integer categoryId;
public Integer getCategoryId() {
return this.categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
}
| mit |
sixlettervariables/sierra-ecg-tools | jsierraecg/src/org/sierraecg/schema/jaxb/_1_03/Medication.java | 3887 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.15 at 08:44:37 PM EDT
//
package org.sierraecg.schema.jaxb._1_03;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="code" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
* <attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
* <attribute name="value" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "medication")
public class Medication {
@XmlValue
protected String value;
@XmlAttribute(name = "code")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String code;
@XmlAttribute(name = "id", required = true)
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "NMTOKEN")
protected String id;
@XmlAttribute(name = "value")
protected String valueAttribute;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the code property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the valueAttribute property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValueAttribute() {
return valueAttribute;
}
/**
* Sets the value of the valueAttribute property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValueAttribute(String value) {
this.valueAttribute = value;
}
}
| mit |
otrimegistro/aerospikez | src/main/java/com/aerospike/client/lua/LuaJavaBlob.java | 956 | /*
* Copyright 2012-2014 Aerospike, Inc.
*
* Portions may be licensed to Aerospike, Inc. under one or more contributor
* license agreements.
*
* 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.aerospike.client.lua;
import org.luaj.vm2.LuaUserdata;
public final class LuaJavaBlob extends LuaUserdata implements LuaData {
public LuaJavaBlob(Object object) {
super(object);
}
public Object luaToObject() {
return m_instance;
}
}
| mit |
gregwym/joos-compiler-java | testcases/a1/J1_forAllwaysInit.java | 320 | // PARSER_WEEDER
public class J1_forAllwaysInit {
public J1_forAllwaysInit () {}
public int foo() {
return 123;
}
public int bar() {
int i = 0;
for (i=foo(); i>123; i=i+1) {}
return i;
}
public static int test() {
J1_forAllwaysInit j = new J1_forAllwaysInit();
return j.bar();
}
}
| mit |
darshanhs90/Java-InterviewPrep | src/LeetcodeTemplate/_0986IntervalListIntersections.java | 1070 | package LeetcodeTemplate;
public class _0986IntervalListIntersections {
public static void main(String[] args) {
System.out.println(intervalIntersection(
new int[][] { new int[] { 0, 2 }, new int[] { 5, 10 }, new int[] { 13, 23 }, new int[] { 24, 25 } },
new int[][] { new int[] { 1, 5 }, new int[] { 8, 12 }, new int[] { 15, 24 }, new int[] { 25, 26 } }));
System.out
.println(intervalIntersection(new int[][] { new int[] { 1, 3 }, new int[] { 5, 9 } }, new int[][] {}));
System.out.println(
intervalIntersection(new int[][] {}, new int[][] { new int[] { 4, 8 }, new int[] { 10, 12 } }));
System.out
.println(intervalIntersection(new int[][] { new int[] { 1, 7 } }, new int[][] { new int[] { 3, 10 } }));
System.out.println(intervalIntersection(new int[][] { new int[] { 3, 5 }, new int[] { 9, 20 } },
new int[][] { new int[] { 4, 5 }, new int[] { 7, 10 }, new int[] { 11, 12 }, new int[] { 14, 15 },
new int[] { 16, 20 } }));
}
public static int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
}
}
| mit |
csmith/DMDirc-Plugins | debug/src/main/java/com/dmdirc/addons/debug/DebugPlugin.java | 1983 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dmdirc.addons.debug;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.plugins.implementations.BaseCommandPlugin;
import dagger.ObjectGraph;
/**
* Debug plugin providing commands to aid in debugging the client.
*/
public class DebugPlugin extends BaseCommandPlugin {
/** The manager in use. */
private DebugManager manager;
@Override
public void load(final PluginInfo pluginInfo, final ObjectGraph graph) {
super.load(pluginInfo, graph);
setObjectGraph(graph.plus(new DebugModule(pluginInfo)));
manager = getObjectGraph().get(DebugManager.class);
registerCommand(Debug.class, Debug.INFO);
}
@Override
public void onLoad() {
super.onLoad();
manager.load();
}
@Override
public void onUnload() {
super.onUnload();
manager.unload();
}
}
| mit |
aghalarp/StarMapper | test/test/pages/EditSurferPage.java | 2095 | package test.pages;
import java.util.ArrayList;
import java.util.List;
import org.fluentlenium.core.FluentPage;
import org.openqa.selenium.WebDriver;
// Although Eclipse marks the following two methods as deprecated,
// the no-arg versions of the methods used here are not deprecated. (as of May, 2013).
import static org.fluentlenium.core.filter.FilterConstructor.withText;
import static org.fluentlenium.core.filter.FilterConstructor.withId;
import static org.fest.assertions.Assertions.assertThat;
/**
* Illustration of the Page Object Pattern in Fluentlenium.
*
* @author Philip Johnson
* @author Kevin
*/
@SuppressWarnings("unused")
public class EditSurferPage extends BasePage {
/**
* Create the LoginPage.
*
* @param webDriver The driver.
* @param port The port.
*/
public EditSurferPage(WebDriver webDriver, int port, String slug) {
super(webDriver, "http://localhost", port, "/surfer/" + slug + "/edit");
}
@Override
public void isAt() {
assertThat(title()).isEqualTo("Surferpedia - EditSurfer");
}
public void fillSurferForm(String name, String home, String awards, String carouselImgUrl, String bioImgUrl,
String biography, String surferType, String footstyleType, String country) {
fill("#name").with(name);
fill("#home").with(home);
fill("#awards").with(awards);
fill("#carouselImgUrl").with(carouselImgUrl);
fill("#bioImgUrl").with(bioImgUrl);
fill("#biography").with(biography);
find("select", withId("surferType")).find("option", withText().equalTo(surferType)).click();
find("div", withId("footstyleTypes")).findFirst("input", withId(footstyleType)).click();
fill("#country").with(country);
submit("#submitSurfer");
}
public void login(String email, String pass) {
// Fill the input field with id "email" with the passed name string.
fill("#email").with(email);
// Fill the input field with id "password" with the passed pass string.
fill("#password").with(pass);
// Submit the form whose id is "submit"
findFirst("form").submit();
}
}
| mit |
virtix/mut4j | lib/slf4j-1.6.0/slf4j-api/src/main/java/org/slf4j/MDC.java | 7485 | /*
* Copyright (c) 2004-2007 QOS.ch
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.slf4j;
import java.util.Map;
import org.slf4j.helpers.BasicMDCAdapter;
import org.slf4j.helpers.NOPMDCAdapter;
import org.slf4j.helpers.Util;
import org.slf4j.impl.StaticMDCBinder;
import org.slf4j.spi.MDCAdapter;
/**
* This class hides and serves as a substitute for the underlying logging
* system's MDC implementation.
*
* <p>
* If the underlying logging system offers MDC functionality, then SLF4J's MDC,
* i.e. this class, will delegate to the underlying system's MDC. Note that at
* this time, only two logging systems, namely log4j and logback, offer MDC
* functionality. If the underlying system does not support MDC, e.g.
* java.util.logging, then SLF4J will use a {@link BasicMDCAdapter}.
*
* <p>
* Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j
* logback, or java.util.logging, but without forcing these systems as
* dependencies upon your users.
*
* <p>
* For more information on MDC please see the <a
* href="http://logback.qos.ch/manual/mdc.html">chapter on MDC</a> in the
* logback manual.
*
* <p>
* Please note that all methods in this class are static.
*
* @author Ceki Gülcü
* @since 1.4.1
*/
public class MDC {
static final String NULL_MDCA_URL = "http://www.slf4j.org/codes.html#null_MDCA";
static final String NO_STATIC_MDC_BINDER_URL = "http://www.slf4j.org/codes.html#no_static_mdc_binder";
static MDCAdapter mdcAdapter;
private MDC() {
}
static {
try {
mdcAdapter = StaticMDCBinder.SINGLETON.getMDCA();
} catch (NoClassDefFoundError ncde) {
mdcAdapter = new NOPMDCAdapter();
String msg = ncde.getMessage();
if (msg != null && msg.indexOf("org/slf4j/impl/StaticMDCBinder") != -1) {
Util.report("Failed to load class \"org.slf4j.impl.StaticMDCBinder\".");
Util.report("Defaulting to no-operation MDCAdapter implementation.");
Util
.report("See " + NO_STATIC_MDC_BINDER_URL + " for further details.");
} else {
throw ncde;
}
} catch (Exception e) {
// we should never get here
Util.report("MDC binding unsuccessful.", e);
}
}
/**
* Put a context value (the <code>val</code> parameter) as identified with the
* <code>key</code> parameter into the current thread's context map. The
* <code>key</code> parameter cannot be null. The <code>val</code> parameter
* can be null only if the underlying implementation supports it.
*
* <p>
* This method delegates all work to the MDC of the underlying logging system.
*
* @throws IllegalArgumentException
* in case the "key" parameter is null
*/
public static void put(String key, String val)
throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.put(key, val);
}
/**
* Get the context identified by the <code>key</code> parameter. The
* <code>key</code> parameter cannot be null.
*
* <p>
* This method delegates all work to the MDC of the underlying logging system.
*
* @return the string value identified by the <code>key</code> parameter.
* @throws IllegalArgumentException
* in case the "key" parameter is null
*/
public static String get(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
return mdcAdapter.get(key);
}
/**
* Remove the the context identified by the <code>key</code> parameter using
* the underlying system's MDC implementation. The <code>key</code> parameter
* cannot be null. This method does nothing if there is no previous value
* associated with <code>key</code>.
*
* @throws IllegalArgumentException
* in case the "key" parameter is null
*/
public static void remove(String key) throws IllegalArgumentException {
if (key == null) {
throw new IllegalArgumentException("key parameter cannot be null");
}
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.remove(key);
}
/**
* Clear all entries in the MDC of the underlying implementation.
*/
public static void clear() {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.clear();
}
/**
* Return a copy of the current thread's context map, with keys and values of
* type String. Returned value may be null.
*
* @return A copy of the current thread's context map. May be null.
* @since 1.5.1
*/
public static Map getCopyOfContextMap() {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
return mdcAdapter.getCopyOfContextMap();
}
/**
* Set the current thread's context map by first clearing any existing map and
* then copying the map passed as parameter. The context map passed as
* parameter must only contain keys and values of type String.
*
* @param contextMap
* must contain only keys and values of type String
* @since 1.5.1
*/
public static void setContextMap(Map contextMap) {
if (mdcAdapter == null) {
throw new IllegalStateException("MDCAdapter cannot be null. See also "
+ NULL_MDCA_URL);
}
mdcAdapter.setContextMap(contextMap);
}
/**
* Returns the MDCAdapter instance currently in use.
*
* @return the MDcAdapter instance currently in use.
* @since 1.4.2
*/
public static MDCAdapter getMDCAdapter() {
return mdcAdapter;
}
} | mit |
AreaFiftyLAN/toornament-client | src/main/java/ch/wisv/toornament/model/enums/MatchStatus.java | 253 | package ch.wisv.toornament.model.enums;
import com.fasterxml.jackson.annotation.JsonProperty;
public enum MatchStatus {
@JsonProperty("pending")
PENDING,
@JsonProperty("running")
RUNNING,
@JsonProperty("completed")
COMPLETED
}
| mit |
danthemellowman/Processing-Android-Eclipse-Demos | processing-android/src/processing/mode/android/BadSDKException.java | 186 | package processing.mode.android;
@SuppressWarnings("serial")
public class BadSDKException extends Exception {
public BadSDKException(final String message) {
super(message);
}
}
| mit |
recena/github-api | src/main/java/org/kohsuke/github/GHBlobBuilder.java | 1339 | package org.kohsuke.github;
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;
/**
* Builder pattern for creating a new blob.
* Based on https://developer.github.com/v3/git/blobs/#create-a-blob
*/
public class GHBlobBuilder {
private final GHRepository repo;
private final Requester req;
GHBlobBuilder(GHRepository repo) {
this.repo = repo;
req = new Requester(repo.root);
}
/**
* Configures a blob with the specified text {@code content}.
*/
public GHBlobBuilder textContent(String content) {
req.with("content", content);
req.with("encoding", "utf-8");
return this;
}
/**
* Configures a blob with the specified binary {@code content}.
*/
public GHBlobBuilder binaryContent(byte[] content) {
String base64Content = Base64.encodeBase64String(content);
req.with("content", base64Content);
req.with("encoding", "base64");
return this;
}
private String getApiTail() {
return String.format("/repos/%s/%s/git/blobs", repo.getOwnerName(), repo.getName());
}
/**
* Creates a blob based on the parameters specified thus far.
*/
public GHBlob create() throws IOException {
return req.method("POST").to(getApiTail(), GHBlob.class);
}
}
| mit |
uwol/cobol85parser | src/main/java/io/proleap/cobol/asg/metamodel/procedure/divide/impl/GivingImpl.java | 1206 | /*
* Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.cobol.asg.metamodel.procedure.divide.impl;
import io.proleap.cobol.CobolParser.DivideGivingContext;
import io.proleap.cobol.asg.metamodel.ProgramUnit;
import io.proleap.cobol.asg.metamodel.call.Call;
import io.proleap.cobol.asg.metamodel.impl.CobolDivisionElementImpl;
import io.proleap.cobol.asg.metamodel.procedure.divide.Giving;
public class GivingImpl extends CobolDivisionElementImpl implements Giving {
protected DivideGivingContext ctx;
protected Call givingCall;
protected boolean rounded;
public GivingImpl(final ProgramUnit programUnit, final DivideGivingContext ctx) {
super(programUnit, ctx);
this.ctx = ctx;
}
@Override
public Call getGivingCall() {
return givingCall;
}
@Override
public boolean isRounded() {
return rounded;
}
@Override
public void setGivingCall(final Call givingCall) {
this.givingCall = givingCall;
}
@Override
public void setRounded(final boolean rounded) {
this.rounded = rounded;
}
}
| mit |
mattparks/Flounder-Engine | src/flounder/particles/ParticleSystem.java | 6694 | package flounder.particles;
import flounder.framework.*;
import flounder.maths.*;
import flounder.maths.matrices.*;
import flounder.maths.vectors.*;
import flounder.noise.*;
import flounder.particles.spawns.*;
import java.util.*;
/**
* A system of particles that are to be spawned.
*/
public class ParticleSystem {
private List<ParticleType> types;
private IParticleSpawn spawn;
private float pps;
private float averageSpeed;
private float gravityEffect;
private boolean randomRotation;
private Vector3f systemCentre;
private Vector3f velocityCentre;
private PerlinNoise noise;
private Vector3f direction;
private float directionDeviation;
private float speedError;
private float lifeError;
private float scaleError;
private boolean paused;
/**
* Creates a new particle system.
*
* @param types The types of particles to spawn.
* @param spawn The particle spawn types.
* @param pps Particles per second.
* @param speed The particle speed.
* @param gravityEffect How much gravity will effect the particle.
*/
public ParticleSystem(List<ParticleType> types, IParticleSpawn spawn, float pps, float speed, float gravityEffect) {
this.types = types;
this.spawn = spawn;
this.pps = pps;
this.averageSpeed = speed;
this.gravityEffect = gravityEffect;
this.randomRotation = false;
this.systemCentre = new Vector3f();
this.velocityCentre = new Vector3f();
this.noise = new PerlinNoise(21);
this.paused = false;
FlounderParticles.get().addSystem(this);
}
public void generateParticles() {
if (paused || spawn == null) {
return;
}
float delta = Framework.get().getDelta();
float particlesToCreate = this.pps * delta;
int count = (int) Math.floor(particlesToCreate);
float partialParticle = particlesToCreate % 1.0f;
for (int i = 0; i < count; i++) {
emitParticle();
}
// TODO: Make it so that the random method is not the only one creating particles.
float random = noise.noise(Framework.get().getTimeMs()) * 10.0f * this.pps;
if (random < partialParticle) {
emitParticle();
}
}
private void emitParticle() {
Vector3f velocity;
if (this.direction != null) {
velocity = generateRandomUnitVectorWithinCone(direction, directionDeviation);
} else {
velocity = generateRandomUnitVector();
}
if (types.isEmpty()) {
return;
}
ParticleType emitType = types.get((int) Math.floor(Maths.randomInRange(0, types.size())));
velocity.normalize();
velocity.scale(generateValue(averageSpeed, averageSpeed * speedError));
Vector3f.add(velocity, velocityCentre, velocity);
float scale = generateValue(emitType.getScale(), emitType.getScale() * scaleError);
float lifeLength = generateValue(emitType.getLifeLength(), emitType.getLifeLength() * lifeError);
Vector3f spawnPos = Vector3f.add(systemCentre, spawn.getBaseSpawnPosition(), null);
FlounderParticles.get().addParticle(emitType, spawnPos, velocity, lifeLength, generateRotation(), scale, gravityEffect);
}
private float generateValue(float average, float errorMargin) {
float offset = (Maths.RANDOM.nextFloat() - 0.5f) * 2.0f * errorMargin;
return average + offset;
}
private float generateRotation() {
if (this.randomRotation) {
return Maths.RANDOM.nextFloat() * 360.0f;
}
return 0.0f;
}
private static Vector3f generateRandomUnitVectorWithinCone(Vector3f coneDirection, float angle) {
float cosAngle = (float) Math.cos(angle);
Random random = new Random();
float theta = (float) (random.nextFloat() * 2.0f * Math.PI);
float z = cosAngle + random.nextFloat() * (1.0f - cosAngle);
float rootOneMinusZSquared = (float) Math.sqrt(1.0f - z * z);
float x = (float) (rootOneMinusZSquared * Math.cos(theta));
float y = (float) (rootOneMinusZSquared * Math.sin(theta));
Vector4f direction = new Vector4f(x, y, z, 1.0f);
if ((coneDirection.x != 0.0f) || (coneDirection.y != 0.0f) || ((coneDirection.z != 1.0f) && (coneDirection.z != -1.0f))) {
Vector3f rotateAxis = Vector3f.cross(coneDirection, new Vector3f(0.0f, 0.0f, 1.0f), null);
rotateAxis.normalize();
float rotateAngle = (float) Math.acos(Vector3f.dot(coneDirection, new Vector3f(0.0f, 0.0f, 1.0f)));
Matrix4f rotationMatrix = new Matrix4f();
Matrix4f.rotate(rotationMatrix, rotateAxis, -rotateAngle, rotationMatrix);
Matrix4f.transform(rotationMatrix, direction, direction);
} else if (coneDirection.z == -1.0f) {
direction.z *= -1.0f;
}
return new Vector3f(direction);
}
private Vector3f generateRandomUnitVector() {
float theta = (float) (Maths.RANDOM.nextFloat() * 2.0f * Math.PI);
float z = Maths.RANDOM.nextFloat() * 2.0f - 1.0f;
float rootOneMinusZSquared = (float) Math.sqrt(1.0f - z * z);
float x = (float) (rootOneMinusZSquared * Math.cos(theta));
float y = (float) (rootOneMinusZSquared * Math.sin(theta));
return new Vector3f(x, y, z);
}
public List<ParticleType> getTypes() {
return types;
}
public void addParticleType(ParticleType particleType) {
types.add(particleType);
}
public void removeParticleType(ParticleType particleType) {
types.remove(particleType);
}
public IParticleSpawn getSpawn() {
return spawn;
}
public void setSpawn(IParticleSpawn spawn) {
this.spawn = spawn;
}
public float getPPS() {
return pps;
}
public void setPps(float pps) {
this.pps = pps;
}
public float getAverageSpeed() {
return averageSpeed;
}
public void setAverageSpeed(float averageSpeed) {
this.averageSpeed = averageSpeed;
}
public float getGravityEffect() {
return gravityEffect;
}
public void setGravityEffect(float gravityEffect) {
this.gravityEffect = gravityEffect;
}
public void randomizeRotation() {
this.randomRotation = true;
}
public Vector3f getSystemCentre() {
return systemCentre;
}
public void setSystemCentre(Vector3f systemCentre) {
this.systemCentre.set(systemCentre);
}
public Vector3f getVelocityCentre() {
return velocityCentre;
}
public void setVelocityCentre(Vector3f velocityCentre) {
this.velocityCentre.set(velocityCentre);
}
public void setDirection(Vector3f direction, float deviation) {
this.direction = new Vector3f(direction);
this.directionDeviation = ((float) (deviation * Math.PI));
}
public void setSpeedError(float error) {
this.speedError = error;
}
public void setLifeError(float error) {
this.lifeError = error;
}
public void setScaleError(float error) {
this.scaleError = error;
}
public boolean isPaused() {
return paused;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
/**
* Removes this system from the systems list.
*/
public void delete() {
FlounderParticles.get().removeSystem(this);
}
}
| mit |
Juanlu991/Play-US | Play-US/Play_US/src/play_us/shared/domain/Song.java | 2532 |
package play_us.shared.domain;
import java.io.Serializable;
import javax.annotation.Generated;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@Generated("org.jsonschema2pojo")
@JsonIgnoreProperties(ignoreUnknown=true)
public class Song implements Serializable{
private static final long serialVersionUID = 289772839985793415L;
private Integer SongID;
private String SongName;
private Integer ArtistID;
private String ArtistName;
private Integer AlbumID;
private String AlbumName;
private String CoverArtFilename;
private Integer Popularity;
private Boolean IsLowBitrateAvailable;
private Boolean IsVerified;
private Integer Flags;
public Integer getSongID() {
return SongID;
}
public void setSongID(Integer songID) {
this.SongID = songID;
}
public String getSongName() {
return SongName;
}
public void setSongName(String songName) {
this.SongName = songName;
}
public Integer getArtistID() {
return ArtistID;
}
public void setArtistID(Integer artistID) {
this.ArtistID = artistID;
}
public String getArtistName() {
return ArtistName;
}
public void setArtistName(String artistName) {
this.ArtistName = artistName;
}
public Integer getAlbumID() {
return AlbumID;
}
public void setAlbumID(Integer albumID) {
this.AlbumID = albumID;
}
public String getAlbumName() {
return AlbumName;
}
public void setAlbumName(String albumName) {
this.AlbumName = albumName;
}
public String getCoverArtFilename() {
return CoverArtFilename;
}
public void setCoverArtFilename(String coverArtFilename) {
this.CoverArtFilename = coverArtFilename;
}
public Integer getPopularity() {
return Popularity;
}
public void setPopularity(Integer popularity) {
this.Popularity = popularity;
}
public Boolean getIsLowBitrateAvailable() {
return IsLowBitrateAvailable;
}
public void setIsLowBitrateAvailable(Boolean isLowBitrateAvailable) {
this.IsLowBitrateAvailable = isLowBitrateAvailable;
}
public Boolean getIsVerified() {
return IsVerified;
}
public void setIsVerified(Boolean isVerified) {
this.IsVerified = isVerified;
}
public Integer getFlags() {
return Flags;
}
public void setFlags(Integer flags) {
this.Flags = flags;
}
}
| mit |
java8compiler/OpenTeleporter | src/main/java/li/cil/oc/api/nanomachines/Behavior.java | 1753 | package li.cil.oc.api.nanomachines;
/**
* Implemented by single behaviors.
* <p/>
* If you need a reference to the player this behavior applies to (which you'll
* probably usually want to have), pass it along from {@link BehaviorProvider#createBehaviors}.
*/
public interface Behavior {
/**
* A short name / description of this behavior.
* <p/>
* You can <em>not</em> use commas (<tt>,</tt>) or double quotes (<tt>"</tt>)
* in the returned string. If you do, they'll automatically be replaced with
* underscores.
* <p/>
* This is entirely optional and may even return <tt>null</tt>. It is made
* accessible via the controller's wireless protocol, to allow better
* automating reconfigurations / determining input mappings. In some cases
* you may not wish to make this possible, in those cases return <tt>null</tt>
* or a random string.
* <p/>
* Again, you can return whatever you like here, it's not used in mod internal
* logic, but only provided to ingame devices as a hint to make configuring
* nanomachines a little easier.
*
* @return the name to provide for this behavior, if any.
*/
String getNameHint();
/**
* Called when this behavior becomes active because all its required inputs
* are now satisfied.
* <p/>
* Use this to initialize permanent effects.
*/
void onEnable();
/**
* Called when this behavior becomes inactive.
* <p/>
* Use this to remove permanent effects.
*
* @param reason the reason the behavior is being disabled.
*/
void onDisable(DisableReason reason);
/**
* Called each tick while this behavior is active.
*/
void update();
}
| mit |
DASPA/DASCA | com.logicalhacking.dasca.dataflow/src/main/java/com/logicalhacking/dasca/dataflow/util/SuperGraphUtil.java | 41251 | /*
* Copyright (c) 2010-2015 SAP SE.
* 2016-2018 The University of Sheffield.
*
* All rights reserved. This program and the accompanying materials
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*/
package com.logicalhacking.dasca.dataflow.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import com.ibm.wala.dataflow.IFDS.ICFGSupergraph;
import com.ibm.wala.ipa.cfg.BasicBlockInContext;
import com.ibm.wala.ssa.IR;
import com.ibm.wala.ssa.SSABinaryOpInstruction;
import com.ibm.wala.ssa.SSAConditionalBranchInstruction;
import com.ibm.wala.ssa.SSAGotoInstruction;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.ssa.SSAInvokeInstruction;
import com.ibm.wala.ssa.SymbolTable;
import com.ibm.wala.ssa.analysis.IExplodedBasicBlock;
import com.ibm.wala.types.MethodReference;
import cvc3.Expr;
import cvc3.SatResult;
import cvc3.ValidityChecker;
/**
* static class for SG helper methods
*
*/
public class SuperGraphUtil {
private static final Logger log = AnalysisUtil.getLogger(SuperGraphUtil.class);
/**
* Adds every nodes ID to iDs, iff it is on a path between the entry and exit point. Uses recursive DFS
* @param iDs
* @param sg
* @param sgNodes
* @param sgNodesReverse
* @param currentId
* @param endId
*/
private static void relevantPathSearch(
HashSet<Integer> iDs,
ICFGSupergraph sg,
HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>> sgNodes,
HashMap<BasicBlockInContext<IExplodedBasicBlock>, Integer> sgNodesReverse,
ArrayList<MethodReference> acceptedMethods,
int currentId,
int endId) {
if(iDs.contains(currentId)) {
return;
}
iDs.add(currentId);
if(currentId == endId) {
return;
}
BasicBlockInContext<IExplodedBasicBlock> bbic = sgNodes.get(currentId);
boolean isInvoke = bbic.getLastInstruction() instanceof SSAInvokeInstruction;
boolean isStringConcat = isInvoke && bbic.getLastInstruction().toString().contains("StringBuilder") && (bbic.getLastInstruction().toString().contains("append") | bbic.getLastInstruction().toString().contains("toString"));
Iterator<BasicBlockInContext<IExplodedBasicBlock>> sucIt = sg.getSuccNodes(bbic);
while(sucIt.hasNext()) {
BasicBlockInContext<IExplodedBasicBlock> nextChild = sucIt.next();
if(isStringConcat) {
if(!sucIt.hasNext()) { // last association of a String concatenation is java intern
continue;
}
}
MethodReference method = nextChild.getMethod().getReference();
if(isInvoke) {
if(!acceptedMethods.contains(method)) {
acceptedMethods.add(method);
}
} else {
if(!acceptedMethods.contains(method)) {
log.debug("supergraph cut at '" + bbic.getNumber() + " -> " + nextChild.getNumber() + " ("
+ nextChild.toString() + ")'");
continue;
}
}
IExplodedBasicBlock del = nextChild.getDelegate();
if(del.isEntryBlock() && del.toString().contains("init")) {
log.debug("supergraph cut at '" + bbic.getNumber() + " -> " + nextChild.getNumber() + " (" + nextChild.toString() + ")'");
continue;
}
relevantPathSearch(iDs, sg, sgNodes, sgNodesReverse, acceptedMethods, sgNodesReverse.get(nextChild), endId);
}
}
/**
* Analyzes the supergraph and saves the relevant part as a dot file to the location <graphs folder>/<entryClass/
* @return
*/
public static int analyzeAndSaveSuperGraph(ICFGSupergraph sg, String entryClass, String entryMethod) {
int weaknessCount = 0;
if (sg == null) {
throw new IllegalArgumentException("sg was null for entry Class \""+entryClass+"\" and entry method \""+entryMethod+"\"");
}
log.info("--- start analyzing " + entryClass + "." + entryMethod + " ---");
ValidityChecker vc = ValidityChecker.create();
vc.push();
Iterator<BasicBlockInContext<IExplodedBasicBlock>> completeIterator = sg.iterator();
int analysisLevel = AnalysisUtil.getPropertyInteger(AnalysisUtil.CONFIG_ANALYSIS_DEPTH);
HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>> sgNodes = new HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>>();
HashMap<BasicBlockInContext<IExplodedBasicBlock>, Integer> sgNodesReversed = new HashMap<BasicBlockInContext<IExplodedBasicBlock>, Integer>();
HashMap<SSAInstructionKey, Integer> sgNodesInstId = new HashMap<SSAInstructionKey, Integer>();
ArrayList<MethodReference> acceptedMethods = new ArrayList<MethodReference>();
// Add all blocks into a Map with a unique identifier in both directions and find entry/exit node
int i = 0;
int mainEntryId = 0;
int mainExitId = 0;
while (completeIterator.hasNext()) {
BasicBlockInContext<IExplodedBasicBlock> current = completeIterator.next();
sgNodes.put(i, current);
log.debug("sgNodes: insert node "+i+" ==> "+current);
sgNodesReversed.put(current, i);
Iterator<SSAInstruction> instIt = current.iterator();
while (instIt.hasNext()) {
SSAInstruction inst = instIt.next();
sgNodesInstId.put(new SSAInstructionKey(inst), i);
log.debug(" sgNodesInstId: insert node "+i+" ==> "+inst);
/* add to include other required methods into CFG
if(inst instanceof AstJavaInvokeInstruction){
AstJavaInvokeInstruction in = (AstJavaInvokeInstruction) inst;
MethodReference meth = in.getDeclaredTarget();
if(meth.toString().contains("calledMethod")){ // check for required method
acceptedMethods.add(meth);
}
}
//*/
}
String signature = current.getMethod().getSignature();
// find entry and exit nodes
if(signature.contains(entryClass) && signature.contains(entryMethod) && current.isEntryBlock()) { // FIXME: entry/exit nodes definition via name is too weak
mainEntryId = i;
log.error("Found Entry Block "+i+"("+entryClass+" / "+entryMethod+":");
log.error(" "+signature);
} else if(signature.contains(entryClass) && signature.contains(entryMethod) && current.isExitBlock()) {
mainExitId = i;
log.error("Found Exit Block "+i+"("+entryClass+" / "+entryMethod+":");
log.error(" "+signature);
}
i++;
}
if(mainEntryId == 0 && mainExitId == 0) {
log.error(" "+entryClass + "." + entryMethod +
": empty entry method, ensure invocation in main method " +
"(mainEntryId = " +mainEntryId + " / mainExitId = " + mainExitId + ")");
return -1;
}
HashSet<Integer> relevantIDs = new HashSet<Integer>();
BasicBlockInContext<IExplodedBasicBlock> bbic = sgNodes.get(mainEntryId);
acceptedMethods.add(bbic.getMethod().getReference());
log.error(" "+entryClass + "." + entryMethod +
"start recursive graph building");
relevantPathSearch(relevantIDs, sg, sgNodes, sgNodesReversed, acceptedMethods, mainEntryId, mainExitId);
// remove irrelevant nodes (not on at least one path between entry and exit node)
log.debug("remove irrelevant nodes");
for (int j = 0; j < i; j++) {
BasicBlockInContext<IExplodedBasicBlock> tmp = sgNodes.get(j);
if(!relevantIDs.contains(j)) {
sgNodesReversed.remove(tmp);
sgNodes.remove(j);
log.debug(" removing node: "+j);
}
}
// build separate adjacency list
log.debug(" "+entryClass + "." + entryMethod +
"build seperate adjacency list");
HashMap<Integer, ArrayList<Integer>> adjList = new HashMap<Integer, ArrayList<Integer>>();
HashMap<Integer, ArrayList<Integer>> adjListReverse = new HashMap<Integer, ArrayList<Integer>>();
boolean removeEmptyNodes = AnalysisUtil.getPropertyBoolean(AnalysisUtil.CONFIG_DOT_REMOVE_EMPTY_NODES);
ArrayList<Integer> emptyNodes = new ArrayList<Integer>();
buildAdjacencyLists(sg, sgNodes, sgNodesReversed, adjList, adjListReverse, emptyNodes, relevantIDs);
// <<< print original adjacency list to log
log.debug("adjacency list before removing empty nodes:");
AnalysisUtil.printAdjList(adjList, log);
//
if(removeEmptyNodes) {
removeEmptyNodes(emptyNodes, adjList, adjListReverse, sgNodes, sgNodesReversed);
// <<< print adjacency list to log
log.debug("adjacency after removing empty nodes:");
AnalysisUtil.printAdjList(adjList, log);
//
}
log.debug(" "+entryClass + "." + entryMethod +
"add conditions to graph nodes");
ArrayList<Integer> visited = new ArrayList<Integer>();
ArrayList<Integer> currentConditions = new ArrayList<Integer>();
HashMap<Integer, Integer> currentConditionsEndId = new HashMap<Integer, Integer>();
HashMap<Integer, ArrayList<Integer>> finalConditions = new HashMap<Integer, ArrayList<Integer>>();
HashMap<Integer, Integer> loops = new HashMap<Integer, Integer>();
addConditionsToGraph(sgNodes, adjList, mainEntryId, visited, mainExitId, currentConditions, currentConditionsEndId, finalConditions, loops);
// remove goto statements for later analysis steps
for (int loopId : loops.keySet()) {
int gotoId = loops.get(loopId);
int gotoTargetId = adjList.get(gotoId).get(0); // goto has exact one child
int afterLoopId = 0;
for(int id : adjList.get(loopId)) {
afterLoopId = Math.max(afterLoopId, id);
}
ArrayList<Integer> newList = new ArrayList<Integer>();
newList.add(afterLoopId);
adjList.put(gotoId, newList);
adjListReverse.get(afterLoopId).add(gotoId);
ArrayList<Integer> gotoTargetReverseList = adjListReverse.get(gotoTargetId);
ArrayList<Integer> newGotoTargetReverseList = new ArrayList<Integer>();
for (int child : gotoTargetReverseList) {
if(child != gotoId) {
newGotoTargetReverseList.add(child);
}
}
adjListReverse.put(gotoTargetId, newGotoTargetReverseList);
}
/* <<< print required conditions for each node
for (Integer key : finalConditions.keySet()) {
StringBuffer sb = new StringBuffer();
for(int condition : finalConditions.get(key)){
sb.append(", " + condition);
}sb.append(" ");
log.debug(key + ": " + sb.substring(2));
}
//*/
/* <<< print changed adjacency list to log
log.debug("adjacency list after removing empty nodes:");
AnalysisUtil.printAdjList(adjList, log);
//*/
//* <<< get definition instruction for each SSA value
HashMap<Integer, SSAInstruction> definitions = AnalysisUtil.getDefs(sgNodes);
//*/
//* <<< get source code line number for each instruction
HashMap<SSAInstructionKey, Integer> lineNumbers = AnalysisUtil.getLineNumbers(sgNodes);
//*/
//* <<< get the corresponding instruction for each condition inside the callgraph
ArrayList<SSAInstruction> conditionsList = AnalysisUtil.getConditions(sgNodes);
ArrayList<Integer> conditionsIdList = new ArrayList<Integer>();
for (SSAInstruction cond : conditionsList) {
conditionsIdList.add(sgNodesInstId.get(new SSAInstructionKey(cond)));
}
//*/
//* <<< get the corresponding source code line number for each condition (node id) inside the callgraph
HashMap<Integer, Integer> conditionLineNumber = new HashMap<Integer, Integer>();
for (SSAInstruction instCondition : conditionsList) {
int nodeId = sgNodesInstId.get(new SSAInstructionKey(instCondition));
int lineNumber = lineNumbers.get(new SSAInstructionKey(instCondition));
conditionLineNumber.put(nodeId, lineNumber);
}
//*/
//* <<< build CVC3 expressions from conditional instruction
log.debug("** get CVC3 expressions for each conditional branch instruction");
HashMap<Integer, Expr> expressions = new HashMap<Integer, Expr>();
IR entryIR = sgNodes.values().iterator().next().getNode().getIR();
vc.pop();
vc.push();
for (SSAInstruction instCondition : conditionsList) {
int condId = sgNodesInstId.get(new SSAInstructionKey(instCondition));
if(loops.keySet().contains(condId)) {
Expr expr = SMTChecker.getExprForLoop(vc , instCondition, entryIR);
expressions.put(sgNodesInstId.get(new SSAInstructionKey(instCondition)), expr);
} else {
Expr expr = SMTChecker.getExprForConditionalBranchInstruction(vc , instCondition, entryIR);
expressions.put(sgNodesInstId.get(new SSAInstructionKey(instCondition)), expr);
}
vc.pop();
vc.push();
}
vc.pop();
vc.push();
//*/
ArrayList<SSAInstruction> sqlExecutes = AnalysisUtil.getSQLExecutes(sgNodes);
log.debug("** get source/sink pairs for each SQL instruction");
String sanitizerMethods = AnalysisUtil.getPropertyString(AnalysisUtil.CONFIG_SANITIZER); // good sources are specified as sanitizer
String[] methods = sanitizerMethods.split(",");
HashSet<String> sanitizer = new HashSet<String>();
for (int k = 0; k < methods.length; k++) {
String sanitizerMethod = methods[k].trim();
sanitizer.add(sanitizerMethod);
}
String badSourceMethods = AnalysisUtil.getPropertyString(AnalysisUtil.CONFIG_BAD_SRC);
methods = badSourceMethods.split(",");
HashSet<String> badMethods = new HashSet<String>();
for (int k = 0; k < methods.length; k++) {
String badMethod = methods[k].trim() + "()";
badMethods.add(badMethod);
}
//* <<< get possible vulnerabilities for each SQL execute
HashMap<SSAInstructionKey, ArrayList<SSAInstruction>> sinkSources = new HashMap<SSAInstructionKey, ArrayList<SSAInstruction>>();
for (SSAInstruction ssaInstruction : sqlExecutes) {
boolean isPreparedStmt = ssaInstruction.toString().contains("Prepared");
sinkSources.put(new SSAInstructionKey(ssaInstruction), AnalysisUtil.analyzeStatementExecute(ssaInstruction, definitions, isPreparedStmt, badMethods));
}
boolean containsVulnerability = false;
for (SSAInstruction sink : sqlExecutes) {
if(!sinkSources.containsKey(new SSAInstructionKey(sink))) { // no vulnerability possible
continue;
}
ArrayList<SSAInstruction> badSources = sinkSources.get(new SSAInstructionKey(sink));
if(badSources != null) {
for (SSAInstruction source : badSources) {
boolean isNotMutuallyExclusive = true;
if(analysisLevel >= AnalysisUtil.ANALYSIS_DEPTH_EXCLUSIVE) {
isNotMutuallyExclusive = isNotMutuallyExclusive(sink, source, sgNodesInstId, finalConditions, expressions, vc);
}
if(isNotMutuallyExclusive) {
boolean isNotSanitized = true;
if(analysisLevel >= AnalysisUtil.ANALYSIS_DEPTH_SANITIZING) {
log.debug("Calling isNotSanitized:");
log.debug(" Source (" + sgNodesInstId.get(new SSAInstructionKey(source)) + "): " + source);
log.debug(" Sink (" + sgNodesInstId.get(new SSAInstructionKey(sink)) + "): " + sink);
isNotSanitized = isNotSanitized(sgNodesInstId.get(new SSAInstructionKey(source)), sgNodesInstId.get(new SSAInstructionKey(sink)), adjList, finalConditions, expressions, vc, conditionsIdList, sanitizer, sgNodes);
}
if(isNotSanitized) {
weaknessCount++;
containsVulnerability = true;
log.warn("SQL execute [" + lineNumbers.get(new SSAInstructionKey(sink)) + "] with bad source readLine [" + lineNumbers.get(new SSAInstructionKey(source)) + "] (" + entryClass + "." + entryMethod + ")");
}
}
}
}
}
if(!containsVulnerability) {
log.info("(" + entryClass + "." + entryMethod + ") is save");
}
//*/
String filePath = String.format("%s_SG.dot", entryMethod);
generateDotFile(sgNodes, adjList, entryClass, filePath, finalConditions);
return weaknessCount;
}
/**
* Computes all possible control flows between source and sink and checks, if every single path is sanitized.
* @return true, iff there exists at least one direct unsanitized path between source and sink
*/
private static boolean isNotSanitized(int sourceId,
int sinkId, HashMap<Integer, ArrayList<Integer>> adjList,
HashMap<Integer, ArrayList<Integer>> finalConditions,
HashMap<Integer, Expr> expressions,
ValidityChecker vc,
ArrayList<Integer> conditionsIdList,
HashSet<String> sanitizer,
HashMap<Integer,BasicBlockInContext<IExplodedBasicBlock>> sgNodes) {
log.debug("** get possible control flows from source to sink");
HashMap<Integer, HashSet<ArrayList<Integer>>> paths = new HashMap<Integer, HashSet<ArrayList<Integer>>>();
calculatePaths(sourceId, sinkId, adjList, paths);
HashSet<ArrayList<Integer>> pathList = paths.get(sourceId);
HashSet<ArrayList<Integer>> possibleFlowPaths = new HashSet<ArrayList<Integer>>();
for (ArrayList<Integer> path : pathList) {
boolean isPossibleFlow = isPossibleFlow(path, finalConditions, expressions, vc, conditionsIdList);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < path.size(); i++) {
sb.append(" -> " + path.get(i));
}
sb.append(" ");
if(isPossibleFlow) {
log.debug("FLOW [possible]: " + sb.substring(3)); // cut off the last arrow
possibleFlowPaths.add(path);
} else {
log.debug("FLOW [impossible]: " + sb.substring(3));
}
}
loopPossiblePaths:
for (ArrayList<Integer> possibleFlowPath : possibleFlowPaths) {
boolean containsSanitizer = false;
for (String sanitizerMethod : sanitizer) {
for(int nodeId : possibleFlowPath) {
BasicBlockInContext<IExplodedBasicBlock> node = sgNodes.get(nodeId);
SSAInstruction inst = node.getLastInstruction();
if(inst != null) {
if(inst.toString().contains(sanitizerMethod)) {
containsSanitizer = true;
continue loopPossiblePaths;
}
}
}
}
if(!containsSanitizer) {
return true; // path contains no sanitizer => is direct path between bad source and bad sink
}
}
return false; // every possible path contained at least one sanitizer
}
private static boolean isPossibleFlow(ArrayList<Integer> path,
HashMap<Integer, ArrayList<Integer>> finalConditions,
HashMap<Integer, Expr> expressions,
ValidityChecker vc,
ArrayList<Integer> conditionsIdList) {
vc.pop();
vc.push();
List<Expr> allExpr = new ArrayList<Expr>();
ArrayList<Integer> allConditions = new ArrayList<Integer>();
for (int i=0; i<path.size(); i++) {
int node = path.get(i);
ArrayList<Integer> conditions = finalConditions.get(node);
if(conditionsIdList.contains(node)) {
ArrayList<Integer> childConditions = finalConditions.get(path.get(i+1).intValue());
if(childConditions == null || childConditions.isEmpty() || !(childConditions.contains(node) | childConditions.contains(-node))) { // jump over if-block without else part => else condition needs to be set
allExpr.add(vc.notExpr(expressions.get(node)));
}
}
if(conditions != null) {
for (int condId : conditions) {
if(!allConditions.contains(condId)) {
allConditions.add(condId);
if(condId < 0) {
allExpr.add(vc.notExpr(expressions.get(Math.abs(condId))));
} else {
allExpr.add(expressions.get(condId));
}
}
}
}
}
if(allExpr.isEmpty()) {
return true;
}
Expr completeExpr = vc.andExpr(allExpr);
SatResult satResult = vc.checkUnsat(completeExpr);
boolean satisfiable = satResult.equals(SatResult.SATISFIABLE);
log.info(" isPossibleFlow: checking expression [" + (satisfiable?"SAT":"UNSAT") + "]: " + completeExpr);
return satisfiable;
}
private static void calculatePaths(int currentId, int target,
HashMap<Integer, ArrayList<Integer>> adjList,
HashMap<Integer, HashSet<ArrayList<Integer>>> paths) {
log.debug(" searching for "+currentId+" in adjList.");
ArrayList<Integer> children = adjList.get(currentId);
if (null == children) {
throw new RuntimeException ("No entry found in adjList for "+currentId);
}
HashSet<ArrayList<Integer>> currentPaths = new HashSet<ArrayList<Integer>>();
for(int child : children) {
if(child == target) {
ArrayList<Integer> last = new ArrayList<Integer>();
last.add(child);
currentPaths.add(last);
continue;
}
calculatePaths(child, target, adjList, paths);
HashSet<ArrayList<Integer>> childPaths = paths.get(child);
if(childPaths!= null) {
for (ArrayList<Integer> childPath : childPaths) {
ArrayList<Integer> newPath = new ArrayList<Integer>();
newPath.add(child);
newPath.addAll(childPath);
currentPaths.add(newPath);
}
}
}
paths.put(currentId, currentPaths);
}
/**
* Checks, if sink and source node are mutually excluded because of the respective conditions
* @param sink
* @param source
* @param sgNodesInstId
* @param finalConditions
* @param expressions
* @param vc
* @return
*/
private static boolean isNotMutuallyExclusive(SSAInstruction sink,
SSAInstruction source,
HashMap<SSAInstructionKey, Integer> sgNodesInstId,
HashMap<Integer,ArrayList<Integer>> finalConditions,
HashMap<Integer, Expr> expressions, ValidityChecker vc) {
vc.pop();
vc.push();
int sourceId = sgNodesInstId.get(new SSAInstructionKey(source));
int sinkId = sgNodesInstId.get(new SSAInstructionKey(sink));
ArrayList<Integer> combinedConditions = new ArrayList<Integer>();
if(finalConditions.containsKey(sourceId)) {
combinedConditions.addAll(finalConditions.get(sourceId));
}
if(finalConditions.containsKey(sinkId)) {
combinedConditions.addAll(finalConditions.get(sinkId));
}
Expr expr = getConditionExpression(combinedConditions, expressions, vc);
vc.pop();
vc.push();
if(expr.toString().equalsIgnoreCase("null")) {
log.debug(" isNotMutuallyExclusive: EXPR: "+expr+" is NULL (combinedConditions: "
+ combinedConditions + "/ expressions: " + expressions +")");
return true;
}
SatResult satResult = vc.checkUnsat(expr);
boolean satisfiable = satResult.equals(SatResult.SATISFIABLE);
log.info(" isNotMutuallyExclusive: checking expression [" + (satisfiable?"SAT":"UNSAT") + "]: " + expr);
return satisfiable;
}
private static Expr getConditionExpression(ArrayList<Integer> nodeIds, HashMap<Integer, Expr> expressions, ValidityChecker vc) {
if(nodeIds.isEmpty()) {
return vc.nullExpr();
}
List<Expr> exprList = new ArrayList<Expr>();
for (int i=0; i<nodeIds.size(); i++) {
Integer conditionId = nodeIds.get(i);
Expr tmpExpr = expressions.get(Math.abs(conditionId));
log.debug(" expressions["+conditionId+"] = "+tmpExpr);
if(conditionId<0) {
tmpExpr = vc.notExpr(tmpExpr);
}
exprList.add(tmpExpr);
}
return vc.andExpr(exprList);
}
private static void removeEmptyNodes(ArrayList<Integer> emptyNodes,
HashMap<Integer, ArrayList<Integer>> adjList,
HashMap<Integer, ArrayList<Integer>> adjListReverse, HashMap<Integer,BasicBlockInContext<IExplodedBasicBlock>> sgNodes, HashMap<BasicBlockInContext<IExplodedBasicBlock>,Integer> sgNodesReversed) {
Collections.sort(emptyNodes);
StringBuffer sb = new StringBuffer();
for (int integer : emptyNodes) {
sb.append(", " + integer);
}
sb.append(" ");
log.debug("empty nodes in supergraph:" + sb.substring(1));
// remove empty nodes from supergraph
log.debug("remove empty nodes from supergraph");
for (Integer kill: emptyNodes) {
ArrayList<Integer> children = adjList.get(kill);
if(children == null) {
children = new ArrayList<Integer>();
}
// insert new edges around removed nodes
for(Integer father : adjListReverse.get(kill)) {
ArrayList<Integer> tmpList = adjList.get(father);
if(tmpList==null) {
tmpList = new ArrayList<Integer>();
}
tmpList.remove(kill);
tmpList.addAll(children);
for (Integer childId : children) {
ArrayList<Integer> childFathers = adjListReverse.get(childId);
if(childFathers==null) {
childFathers = new ArrayList<Integer>();
}
childFathers.remove(kill);
childFathers.add(father);
adjListReverse.put(childId, childFathers);
}
adjList.put(father, tmpList);
}
}
for (Integer kill: emptyNodes) { // requires two loops to build the new edges correct
adjList.remove(kill);
sgNodesReversed.remove(sgNodes.get(kill));
sgNodes.remove(kill);
}
}
private static void buildAdjacencyLists(
ICFGSupergraph sg, HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>> sgNodes,
HashMap<BasicBlockInContext<IExplodedBasicBlock>, Integer> sgNodesReversed,
HashMap<Integer, ArrayList<Integer>> adjList,
HashMap<Integer, ArrayList<Integer>> adjListReverse,
ArrayList<Integer> emptyNodes, HashSet<Integer> relevantIDs) {
for (int key1 : sgNodes.keySet()) {
BasicBlockInContext<IExplodedBasicBlock> val1 = sgNodes.get(key1);
Iterator<BasicBlockInContext<IExplodedBasicBlock>> sucIt = sg.getSuccNodes(val1);
// add 'key1->sucId' to adjList
ArrayList<Integer> list = adjList.get(key1);
if(list == null) {
list = new ArrayList<Integer>();
}
while (sucIt.hasNext()) {
BasicBlockInContext<IExplodedBasicBlock> suc = sucIt.next();
if(!sgNodesReversed.containsKey(suc)) {
continue;
}
int sucId = sgNodesReversed.get(suc);
if(!list.contains(sucId)) {
list.add(sucId);
}
// add 'sucId->key1' to adjListReverse
ArrayList<Integer> listReverse = adjListReverse.get(sucId);
if(listReverse == null) {
listReverse = new ArrayList<Integer>();
}
if(!listReverse.contains(key1)) {
listReverse.add(key1);
}
adjListReverse.put(sucId, listReverse);
// add empty nodes to list
Iterator<SSAInstruction> it = suc.iterator();
if(relevantIDs.contains(sucId)) {
if(!emptyNodes.contains(sucId)) {
if(!it.hasNext() && !suc.isEntryBlock() && !suc.isExitBlock() && !suc.isCatchBlock()) {
emptyNodes.add(sucId);
}
}
}
}
adjList.put(key1, list);
}
}
/**
* Analyzes the given nodes of the supergraph and fills the list finalConditions
* @param sgNodes
* @param adjList
* @param currentId
* @param visited
* @param mainEndId
* @param currentConditions
* @param currentConditionsEndId
* @param finalConditions
* @param loops
* @return
*/
private static boolean addConditionsToGraph( // boolean return is used in recursion to signalize the existence of an else block
HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>> sgNodes,
HashMap<Integer, ArrayList<Integer>> adjList,
Integer currentId,
ArrayList<Integer> visited,
Integer mainEndId,
ArrayList<Integer> currentConditions,
HashMap<Integer, Integer> currentConditionsEndId,
HashMap<Integer, ArrayList<Integer>> finalConditions,
HashMap<Integer, Integer> loops) {
if(!visited.contains(currentId)) {
visited.add(currentId);
}
if(currentId == mainEndId) {
finalConditions.put(mainEndId, new ArrayList<Integer>());
return false;
}
SSAInstruction currentInstruction = sgNodes.get(currentId).getLastInstruction();
ArrayList<Integer> children = adjList.get(currentId);
Integer ifStart = 0;
Integer ifEnd = 0;
if(!currentConditions.isEmpty()) { // inside an if-block
ifStart = currentConditions.get(currentConditions.size()-1); // last condition is the most inner condition
ifEnd = currentConditionsEndId.get(ifStart);
if(currentId > Math.abs(ifEnd) && sgNodes.get(currentId).isCatchBlock()) { // most inner if block has else AND current node is join
return false;
}
if(currentId > Math.abs(ifEnd) && Math.abs(ifEnd) != mainEndId) { // most inner if block has else AND current node is join
currentConditionsEndId.put(ifStart,currentId);
return true;
}
if(currentId.intValue() == ifEnd.intValue()) { // end of single if block
return false;
}
if(currentId == (-ifEnd)) { // end of else block
ArrayList<Integer> tmpCond = new ArrayList<Integer>(currentConditions);
HashMap<Integer, Integer> tmpCondEnd = new HashMap<Integer, Integer>(currentConditionsEndId);
int lastId = currentConditions.size();
while(lastId > 0 && currentId == -tmpCondEnd.get(tmpCond.get(--lastId))) { // delete all conditions, which end at this node
Integer del = currentConditions.get(lastId);
currentConditions.remove(del);
currentConditionsEndId.remove(del);
}
}
} // END IF inside an if-block
if(currentInstruction instanceof SSAConditionalBranchInstruction) {
Integer childTrue = Math.min(children.get(0), children.get(1)); // WALA always takes the true branch first
Integer childFalse = Math.max(children.get(0), children.get(1));
ArrayList<Integer> conditions = new ArrayList<Integer>();
for(int i =0; i<currentConditions.size(); i++) {
conditions.add(currentConditions.get(i));
}
finalConditions.put(currentId, conditions);
currentConditions.add(currentId);
boolean isLastIfBlock = childTrue.intValue() == mainEndId.intValue(); // => its an if block without else and without any instructions after it
if(isLastIfBlock) {
childTrue = Math.max(children.get(0), children.get(1));
currentConditionsEndId.put(currentId, mainEndId);
} else {
currentConditionsEndId.put(currentId, childFalse);
}
boolean isRealIfElse = addConditionsToGraph(sgNodes, adjList, childTrue, visited, mainEndId, currentConditions, currentConditionsEndId, finalConditions, loops);
currentConditions.remove(currentId);
Integer newEnd = currentConditionsEndId.remove(currentId);
if(isRealIfElse) {
currentConditions.add(-currentId);
currentConditionsEndId.put(-currentId, -newEnd); // last visited is the reached join from if-block
}
if(!isLastIfBlock) {
return addConditionsToGraph(sgNodes, adjList, childFalse, visited, mainEndId, currentConditions, currentConditionsEndId, finalConditions, loops);
}
return isRealIfElse;
} // END IF conditional branch instruction
else if(currentInstruction instanceof SSAGotoInstruction) {
int child = children.get(0); // goto always points to exactly one child node
if(currentId == Math.abs(ifEnd)-1) { // last node of if block
ArrayList<Integer> conditions = new ArrayList<Integer>();
for(int i =0; i<currentConditions.size(); i++) {
conditions.add(currentConditions.get(i));
}
finalConditions.put(currentId, conditions);
if(!(Math.abs(ifEnd) == child)) {
if(child <= Math.abs(ifStart)) { // is loop
loops.put(ifStart, currentId.intValue());
return false;
}
currentConditionsEndId.put(ifStart, child);
return true;
} else {
return false;
}
}
} // END IF goto instruction
else {
ArrayList<Integer> conditions = new ArrayList<Integer>();
for(int i =0; i<currentConditions.size(); i++) {
conditions.add(currentConditions.get(i));
}
finalConditions.put(currentId, conditions);
}
System.out.println(""+currentInstruction);
boolean isRealIfElse = false;
for(int i=0; i<children.size(); i++) {
int child = children.get(i);
isRealIfElse = isRealIfElse | addConditionsToGraph(sgNodes, adjList, child, visited, mainEndId, currentConditions, currentConditionsEndId, finalConditions, loops);
}
return isRealIfElse;
}
private static void generateDotFile(
HashMap<Integer, BasicBlockInContext<IExplodedBasicBlock>> sgNodes,
HashMap<Integer, ArrayList<Integer>> adjList, String entryClass,
String filePath, HashMap<Integer,ArrayList<Integer>> finalConditions) {
FileWriter fstream;
try {
log.debug("start generating dot file");
String path = AnalysisUtil.getPropertyString(AnalysisUtil.CONFIG_DOT_PATH) + File.separator;
path += "java" + File.separator;
File sgDir = new File(path + entryClass);
sgDir.mkdirs();
File sgFile = new File(path + entryClass + File.separator + filePath);
fstream = new FileWriter(sgFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write("digraph SuperGraph {");
out.newLine();
out.write("node [shape=record];");
out.newLine();
// add relevant nodes to dot
log.debug("add nodes to dot file");
for (Integer key : sgNodes.keySet()) {
BasicBlockInContext<IExplodedBasicBlock> val = sgNodes.get(key);
Iterator<SSAInstruction> insIt = val.iterator();
IExplodedBasicBlock del = val.getDelegate();
int key2 = del.getGraphNodeId(); //cfg.getNumber(val);
// print the labels and define the id (key)
out.write(key + " [");
out.write("label = \" <f0>" + key + "-" + key2 + "| <f1>" + AnalysisUtil.sanitize(val.getMethod().getSignature()));
IR ir = val.getNode().getIR();
SymbolTable symTab = ir.getSymbolTable();
int j = 2;
// print the instruction field of the label
while (insIt.hasNext()) {
// insCount++;
SSAInstruction ins = insIt.next();
if(ins instanceof SSAConditionalBranchInstruction) {
ins = (SSAConditionalBranchInstruction) ins;
SSAInstruction cmp = val.getNode().getDU().getDef(ins.getUse(0));
if(cmp instanceof SSABinaryOpInstruction) {
SSABinaryOpInstruction bCmp = (SSABinaryOpInstruction) cmp;
out.write(" | <f" + j++ + "> " + bCmp.toString(symTab));
}
} else if(ins instanceof SSAInvokeInstruction) {
//TODO
}
out.write(" | <f" + j++ + "> " + AnalysisUtil.sanitize(ins.toString(symTab)));
}
if(finalConditions.containsKey(key)) {
StringBuffer sb = new StringBuffer();
for(int condition : finalConditions.get(key)) {
sb.append(", " + condition);
}
sb.append(" ");
out.write(" | <f" + j++ + "> " + sb.substring(2));
}
if(val.isEntryBlock()) {
out.write(" | <f" + j++ + "> [ENTRY]");
} else if(val.isExitBlock()) {
out.write(" | <f" + j++ + "> [EXIT]");
} else if(val.isCatchBlock()) {
out.write(" | <f" + j++ + "> [CATCH]");
}
out.write("\"];");
out.newLine();
}
// add relevant edges to dot
log.debug("add edges to dot file");
for (Integer src : adjList.keySet()) {
for(int dest : adjList.get(src)) {
out.write(src + "->" + dest + ";");
out.newLine();
}
}
// write dot file to file system
out.write("}");
out.close();
log.info("dot file generated (" + sgFile.getAbsolutePath() + ")");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| epl-1.0 |
Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/filter/ArithmeticExpression.java | 6924 | /**
* 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.activemq.filter;
import javax.jms.JMSException;
/**
* An expression which performs an operation on two expression values
*
*
*/
public abstract class ArithmeticExpression extends BinaryExpression {
protected static final int INTEGER = 1;
protected static final int LONG = 2;
protected static final int DOUBLE = 3;
/**
* @param left
* @param right
*/
public ArithmeticExpression(Expression left, Expression right) {
super(left, right);
}
public static Expression createPlus(Expression left, Expression right) {
return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof String) {
String text = (String)lvalue;
String answer = text + rvalue;
return answer;
} else if (lvalue instanceof Number) {
return plus((Number)lvalue, asNumber(rvalue));
}
throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue);
}
public String getExpressionSymbol() {
return "+";
}
};
}
public static Expression createMinus(Expression left, Expression right) {
return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) {
return minus((Number)lvalue, asNumber(rvalue));
}
throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue);
}
public String getExpressionSymbol() {
return "-";
}
};
}
public static Expression createMultiply(Expression left, Expression right) {
return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) {
return multiply((Number)lvalue, asNumber(rvalue));
}
throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue);
}
public String getExpressionSymbol() {
return "*";
}
};
}
public static Expression createDivide(Expression left, Expression right) {
return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) {
return divide((Number)lvalue, asNumber(rvalue));
}
throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue);
}
public String getExpressionSymbol() {
return "/";
}
};
}
public static Expression createMod(Expression left, Expression right) {
return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) {
return mod((Number)lvalue, asNumber(rvalue));
}
throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue);
}
public String getExpressionSymbol() {
return "%";
}
};
}
protected Number plus(Number left, Number right) {
switch (numberType(left, right)) {
case INTEGER:
return new Integer(left.intValue() + right.intValue());
case LONG:
return new Long(left.longValue() + right.longValue());
default:
return new Double(left.doubleValue() + right.doubleValue());
}
}
protected Number minus(Number left, Number right) {
switch (numberType(left, right)) {
case INTEGER:
return new Integer(left.intValue() - right.intValue());
case LONG:
return new Long(left.longValue() - right.longValue());
default:
return new Double(left.doubleValue() - right.doubleValue());
}
}
protected Number multiply(Number left, Number right) {
switch (numberType(left, right)) {
case INTEGER:
return new Integer(left.intValue() * right.intValue());
case LONG:
return new Long(left.longValue() * right.longValue());
default:
return new Double(left.doubleValue() * right.doubleValue());
}
}
protected Number divide(Number left, Number right) {
return new Double(left.doubleValue() / right.doubleValue());
}
protected Number mod(Number left, Number right) {
return new Double(left.doubleValue() % right.doubleValue());
}
private int numberType(Number left, Number right) {
if (isDouble(left) || isDouble(right)) {
return DOUBLE;
} else if (left instanceof Long || right instanceof Long) {
return LONG;
} else {
return INTEGER;
}
}
private boolean isDouble(Number n) {
return n instanceof Float || n instanceof Double;
}
protected Number asNumber(Object value) {
if (value instanceof Number) {
return (Number)value;
} else {
throw new RuntimeException("Cannot convert value: " + value + " into a number");
}
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object lvalue = left.evaluate(message);
if (lvalue == null) {
return null;
}
Object rvalue = right.evaluate(message);
if (rvalue == null) {
return null;
}
return evaluate(lvalue, rvalue);
}
/**
* @param lvalue
* @param rvalue
* @return
*/
protected abstract Object evaluate(Object lvalue, Object rvalue);
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.cdi.visibility_fat/test-applications/multiModuleAppWeb2.war/src/com/ibm/ws/cdi12/test/web2/Web2Servlet.java | 1128 | /*******************************************************************************
* Copyright (c) 2016, 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.cdi12.test.web2;
import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import org.junit.Test;
import com.ibm.ws.cdi12.test.lib2.BasicBean2;
import componenttest.app.FATServlet;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
@WebServlet("/")
public class Web2Servlet extends FATServlet {
private static final long serialVersionUID = 1L;
@Inject
private BasicBean2 bean2;
@Test
@Mode(TestMode.FULL)
public void testBean2() {
bean2.setData("Test");
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/apps/CommonFatApplications.java | 1590 | /*******************************************************************************
* Copyright (c) 2018 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.fat.common.apps;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.ibm.websphere.simplicity.ShrinkHelper;
import componenttest.topology.impl.LibertyServer;
public class CommonFatApplications {
private static String getPathToTestApps() {
// When executing FATs, the "user.dir" property is <OL root>/dev/<FAT project>/build/libs/autoFVT/
// Hence, to get back to this project, we have to navigate a few levels up.
return System.getProperty("user.dir") + "/../../../../com.ibm.ws.security.fat.common/";
}
public static void buildAndDeployApp(LibertyServer server, String appName, String... packages) throws Exception {
WebArchive jwtBuilderApp = ShrinkHelper.buildDefaultApp(appName, packages);
deployApp(server, jwtBuilderApp, appName);
}
public static void deployApp(LibertyServer server, WebArchive app, String appName) throws Exception {
ShrinkHelper.exportAppToServer(server, app);
server.addInstalledAppForValidation(appName);
}
} | epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.dynacache.web/src/com/ibm/websphere/command/UnavailableCompensatingCommandException.java | 3617 | /*******************************************************************************
* Copyright (c) 2000 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.websphere.command;
import com.ibm.websphere.command.CommandException;
/**
* UnavailableCompensableCommandException is thrown by the
* getCompensatingCommand() method (in the CompensableCommand interface)
* if it finds no compensating command to return.
*
* @ibm-api
*/
public class UnavailableCompensatingCommandException
extends CommandException
{
private static final long serialVersionUID = 8722367931685681097L;
/**
* Constructor without parameters.
*/
public
UnavailableCompensatingCommandException()
{
super();
}
/**
* Constructor with a message.
*
* @param message A string describing the exception.
*/
public
UnavailableCompensatingCommandException(String message)
{
super(message);
}
/**
* Constructor with information for localizing messages.
*
* @param resourceBundleName The name of resource bundle
* that will be used to retrieve the message
* for getMessage() method.
* @param resourceKey The key in the resource bundle that
* will be used to select the specific message that is
* retrieved for the getMessage() method.
* @param formatArguments The arguments to be passed to
* the MessageFormat class to act as replacement variables
* in the message that is retrieved from the resource bundle.
* Valid types are those supported by MessageFormat.
* @param defaultText The default message that will be
* used by the getMessage() method if the resource bundle or the
* key cannot be found.
*/
public UnavailableCompensatingCommandException(String resourceBundleName, //d75515 add
String resourceKey,
Object formatArguments[],
String defaultText)
{
super(resourceBundleName, resourceKey, formatArguments, defaultText);
}
/**
* Constructor with information for localizing messages and an exception
* to chain.
*
* @param resourceBundleName The name of resource bundle
* that will be used to retrieve the message
* for getMessage() method.
* @param resourceKey The key in the resource bundle that
* will be used to select the specific message
* retrieved for the getMessage() method.
* @param formatArguments The arguments to be passed to
* the MessageFormat class to act as replacement variables
* in the message that is retrieved from the resource bundle.
* Valid types are those supported by MessageFormat.
* @param defaultText The default message that will be
* used by the getMessage() method if the resource bundle or the
* key cannot be found.
* @param exception The exception that is to be chained.
*/
public UnavailableCompensatingCommandException(String resourceBundleName, //d75515 add
String resourceKey,
Object formatArguments[],
String defaultText,
Throwable exception)
{
super(resourceBundleName, resourceKey, formatArguments, defaultText, exception);
}
}
| epl-1.0 |
ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/subclass/SubclassPropertiesAudited2Test.java | 922 | package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2.subclass;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2.AbstractPropertiesAudited2Test;
import org.testng.annotations.Test;
/**
* @author Hernán Chanfreau
*
*/
public class SubclassPropertiesAudited2Test extends AbstractPropertiesAudited2Test {
public void configure(Ejb3Configuration cfg) {
try {
URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/interfaces/subclassPropertiesAudited2Mappings.hbm.xml");
cfg.addFile(new File(url.toURI()));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
@Test
public void testRetrieveAudited() {
super.testRetrieveAudited();
}
}
| epl-1.0 |
TypeFox/che | multiuser/keycloak/che-multiuser-keycloak-server/src/main/java/org/eclipse/che/multiuser/keycloak/server/AbstractKeycloakFilter.java | 1143 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.keycloak.server;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
/**
* Base abstract class for the Keycloak-related servlet filters.
*
* <p>In particular it defines commnon use-cases when the authentication / multi-user logic should
* be skipped
*/
public abstract class AbstractKeycloakFilter implements Filter {
protected boolean shouldSkipAuthentication(HttpServletRequest request, String token) {
return request.getScheme().startsWith("ws") || (token != null && token.startsWith("machine"));
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
| epl-1.0 |
chrismathis/eclipsensis | plugins/net.sf.eclipsensis/src/net/sf/eclipsensis/INSISConstants.java | 9012 | /*******************************************************************************
* Copyright (c) 2004-2010 Sunil Kamath (IcemanK).
* All rights reserved.
* This program is made available under the terms of the Common Public License
* v1.0 which is available at http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Sunil Kamath (IcemanK) - initial API and implementation
*******************************************************************************/
package net.sf.eclipsensis;
import net.sf.eclipsensis.util.winapi.WinAPI.HKEY;
import org.eclipse.core.runtime.QualifiedName;
public interface INSISConstants
{
public static final String PLUGIN_ID = EclipseNSISPlugin.getDefault().getBundle().getSymbolicName();
public static final String MAKENSIS_EXE = "makensis.exe"; //$NON-NLS-1$
public static final String NSISCONF_NSH = "nsisconf.nsh"; //$NON-NLS-1$
public static final String NSI_EXTENSION = "nsi"; //$NON-NLS-1$
public static final String NSH_EXTENSION = "nsh"; //$NON-NLS-1$
public static final String NSI_WILDCARD_EXTENSION = "ns[hi]"; //$NON-NLS-1$
public static final String PLUGIN_CONTEXT_PREFIX = PLUGIN_ID + "."; //$NON-NLS-1$
public static final String FILE_ASSOCIATION_ID = EclipseNSISPlugin.getBundleResourceString("%file.association.id"); //$NON-NLS-1$
public static final String EDITOR_ID = EclipseNSISPlugin.getBundleResourceString("%editor.id"); //$NON-NLS-1$
public static final String PREFERENCE_PAGE_ID = EclipseNSISPlugin.getBundleResourceString("%preference.page.id"); //$NON-NLS-1$
public static final String EDITOR_PREFERENCE_PAGE_ID = EclipseNSISPlugin.getBundleResourceString("%editor.preference.page.id"); //$NON-NLS-1$
public static final String TEMPLATES_PREFERENCE_PAGE_ID = EclipseNSISPlugin.getBundleResourceString("%template.preference.page.id"); //$NON-NLS-1$
public static final String TASKTAGS_PREFERENCE_PAGE_ID = EclipseNSISPlugin.getBundleResourceString("%task.tags.preference.page.id"); //$NON-NLS-1$
public static final String HTMLHELP_ID = EclipseNSISPlugin.getBundleResourceString("%htmlhelp.id"); //$NON-NLS-1$
public static final String COMMANDS_VIEW_ID = EclipseNSISPlugin.getBundleResourceString("%commands.view.id"); //$NON-NLS-1$
public static final String PROBLEM_MARKER_ID = EclipseNSISPlugin.getBundleResourceString("%compile.problem.marker.id"); //$NON-NLS-1$
public static final String ERROR_ANNOTATION_NAME = EclipseNSISPlugin.getBundleResourceString("%nsis.error.annotation.name"); //$NON-NLS-1$
public static final String WARNING_ANNOTATION_NAME = EclipseNSISPlugin.getBundleResourceString("%nsis.warning.annotation.name"); //$NON-NLS-1$
public static final String TASK_MARKER_ID = EclipseNSISPlugin.getBundleResourceString("%task.marker.id"); //$NON-NLS-1$
public static final String NSIS_EDITOR_CONTEXT_ID = EclipseNSISPlugin.getBundleResourceString("%context.editingNSISSource.id"); //$NON-NLS-1$
public static final String COMPILE_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%compile.action.id"); //$NON-NLS-1$
public static final String COMPILE_TEST_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%compile.test.action.id"); //$NON-NLS-1$
public static final String TEST_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%test.action.id"); //$NON-NLS-1$
public static final String CLEAR_MARKERS_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%clear.markers.action.id"); //$NON-NLS-1$
public static final String INSERT_TEMPLATE_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.template.command.id"); //$NON-NLS-1$
public static final String GOTO_HELP_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%goto.help.command.id"); //$NON-NLS-1$
public static final String STICKY_HELP_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%sticky.help.command.id"); //$NON-NLS-1$
public static final String INSERT_FILE_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.file.command.id"); //$NON-NLS-1$
public static final String INSERT_DIRECTORY_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.directory.command.id"); //$NON-NLS-1$
public static final String INSERT_COLOR_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.color.command.id"); //$NON-NLS-1$
public static final String INSERT_REGFILE_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.regfile.command.id"); //$NON-NLS-1$
public static final String INSERT_REGKEY_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.regkey.command.id"); //$NON-NLS-1$
public static final String INSERT_REGVAL_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%insert.regval.command.id"); //$NON-NLS-1$
public static final String TABS_TO_SPACES_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%tabs.to.spaces.command.id"); //$NON-NLS-1$
public static final String TOGGLE_COMMENT_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%toggle.comment.command.id"); //$NON-NLS-1$
public static final String ADD_BLOCK_COMMENT_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%add.block.comment.command.id"); //$NON-NLS-1$
public static final String REMOVE_BLOCK_COMMENT_COMMAND_ID = EclipseNSISPlugin.getBundleResourceString("%remove.block.comment.command.id"); //$NON-NLS-1$
public static final String OPEN_ASSOCIATED_SCRIPT_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%open.associated.script.action.id"); //$NON-NLS-1$
public static final String OPEN_ASSOCIATED_HEADERS_ACTION_ID = EclipseNSISPlugin.getBundleResourceString("%open.associated.headers.action.id"); //$NON-NLS-1$
public static final String OPEN_ASSOCIATED_SCRIPT_POPUP_MENU_ID = EclipseNSISPlugin.getBundleResourceString("%open.associated.script.popup.menu.id"); //$NON-NLS-1$
public static final String OPEN_ASSOCIATED_HEADERS_POPUP_MENU_ID = EclipseNSISPlugin.getBundleResourceString("%open.associated.headers.popup.menu.id"); //$NON-NLS-1$
public static final String PLUGIN_HELP_LOCATION_PREFIX = "help/"; //$NON-NLS-1$
public static final String NSISCONTRIB_JS_LOCATION = PLUGIN_HELP_LOCATION_PREFIX + "nsiscontrib.js"; //$NON-NLS-1$
public static final String DOCS_LOCATION_PREFIX = "Docs/"; //$NON-NLS-1$
public static final String KEYWORD_PREFIX = "keyword/"; //$NON-NLS-1$
public static final String CONTRIB_LOCATION_PREFIX = "Contrib/"; //$NON-NLS-1$
public static final String PLUGIN_HELP_DOCS_LOCATION_PREFIX = PLUGIN_HELP_LOCATION_PREFIX+DOCS_LOCATION_PREFIX;
public static final String NSIS_PLATFORM_HELP_PREFIX = PLUGIN_HELP_LOCATION_PREFIX+"NSIS/"; //$NON-NLS-1$
public static final String NSIS_PLATFORM_HELP_DOCS_PREFIX = NSIS_PLATFORM_HELP_PREFIX+DOCS_LOCATION_PREFIX;
public static final String NSIS_CHM_HELP_FILE = "NSIS.chm"; //$NON-NLS-1$
public static final String LANGUAGE_FILES_LOCATION = "Contrib\\Language files"; //$NON-NLS-1$
public static final String MUI_LANGUAGE_FILES_LOCATION = "Contrib\\Modern UI\\Language files"; //$NON-NLS-1$
public static final String LANGUAGE_FILES_EXTENSION = ".nlf"; //$NON-NLS-1$
public static final String MUI_LANGUAGE_FILES_EXTENSION = ".nsh"; //$NON-NLS-1$
public static final String RESOURCE_BUNDLE = "net.sf.eclipsensis.EclipseNSISPluginResources"; //$NON-NLS-1$
public static final String MESSAGE_BUNDLE = "net.sf.eclipsensis.EclipseNSISPluginMessages"; //$NON-NLS-1$
public static final QualifiedName NSIS_COMPILE_TIMESTAMP = new QualifiedName(PLUGIN_ID,"nsisCompileTimestamp"); //$NON-NLS-1$
public static final QualifiedName NSIS_EXE_NAME = new QualifiedName(PLUGIN_ID,"nsisEXEName"); //$NON-NLS-1$
public static final QualifiedName NSIS_EXE_TIMESTAMP = new QualifiedName(PLUGIN_ID,"nsisEXETimestamp"); //$NON-NLS-1$
public static final char LINE_CONTINUATION_CHAR = '\\';
public static final String LINE_SEPARATOR = System.getProperty("line.separator"); //$NON-NLS-1$
public static final char[][] QUOTE_ESCAPE_SEQUENCES = {{'$','\\','"'},{'$','\\','\''},{'$','\\','`'}};
public static final char[][] WHITESPACE_ESCAPE_SEQUENCES = {{'$','\\','r'},{'$','\\','n'},{'$','\\','t'}};
public static final int DIALOG_TEXT_LIMIT = 100;
public static final int DEFAULT_NSIS_TEXT_LIMIT = 1024;
public static final String UNINSTALL_SECTION_NAME = "Uninstall"; //$NON-NLS-1$
public static final String NSIS_PLUGINS_LOCATION = "Plugins"; //$NON-NLS-1$
public static final String NSIS_PLUGINS_EXTENSION = ".dll"; //$NON-NLS-1$
public static final HKEY NSIS_REG_ROOTKEY = HKEY.HKEY_LOCAL_MACHINE;
public static final String NSIS_REG_SUBKEY = "SOFTWARE\\NSIS"; //$NON-NLS-1$
public static final String NSIS_REG_VALUE = ""; //$NON-NLS-1$
public static final String REG_FILE_EXTENSION = ".reg"; //$NON-NLS-1$
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.remote_fat/test-applications/BasicRemote.war/src/com/ibm/ws/ejbcontainer/remote/fat/basic/BusinessRemoteStatelessBean.java | 790 | /*******************************************************************************
* Copyright (c) 2014, 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.ejbcontainer.remote.fat.basic;
import javax.ejb.Remote;
import javax.ejb.Stateless;
@Stateless
@Remote({ BusinessRMI.class, BusinessRemote.class })
public class BusinessRemoteStatelessBean extends AbstractBusinessRemoteBean {
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.security.saml.sso_fat.jaxrs/test-applications/jaxrsclient.war/src/com/ibm/ws/jaxrs/fat/jaxrsclient/JaxRSClient.java | 8779 | /*******************************************************************************
* Copyright (c) 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jaxrs.fat.jaxrsclient;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import com.ibm.websphere.security.saml2.PropagationHelper;
import com.ibm.websphere.security.saml2.Saml20Token;
import com.ibm.ws.security.saml20.fat.commonTest.SAMLCommonTestTools;
/**
* Servlet implementation class CxfSamlSvcClient
*/
public class JaxRSClient extends HttpServlet {
/**
* @see HttpServlet#HttpServlet()
*/
public JaxRSClient() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doWorker(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Got into the svc client");
String appToCall = request.getParameter("targetApp");
if (isUrlEncodedUrl(appToCall)) {
System.out.println("Raw target app: " + appToCall);
appToCall = URLDecoder.decode(appToCall, "UTF-8");
}
System.out.println("Target APP: " + appToCall);
String headerFormat = request.getParameter("headerFormat");
System.out.println("Header Format: " + headerFormat);
String headerName = request.getParameter("header");
System.out.println("Header Name: " + headerName);
String formatTypeToSend = request.getParameter("formatType");
System.out.println("Format Type: " + formatTypeToSend);
Enumeration<String> v = request.getParameterNames();
while (v.hasMoreElements()) {
System.out.println("Parm: " + v.nextElement());
}
// StringBuffer sb = new StringBuffer();
// sb.append(WSSubject.getCallerPrincipal());
// System.out.println(sb.toString()) ;
String mySAML = null;
if (formatTypeToSend == null) {
System.out.println("Assertion format: not set - will test invoking all api's");
testUnsetToken();
return;
}
try {
if (formatTypeToSend.equals("assertion_encoded")) {
System.out.println("Assertion format: assertion_encoded");
mySAML = PropagationHelper.getEncodedSaml20Token(false);
} else {
if (formatTypeToSend.equals("assertion_compressed_encoded")) {
System.out.println("Assertion format: assertion_compressed_encoded");
mySAML = PropagationHelper.getEncodedSaml20Token(true);
} else {
if (formatTypeToSend.equals("assertion_text_only")) {
System.out.println("Assertion format: assertion_text_only");
Saml20Token myTmpSAML = PropagationHelper.getSaml20Token();
if (myTmpSAML != null) {
mySAML = SAMLCommonTestTools.trimXML(myTmpSAML.getSAMLAsString());
}
} else {
if (formatTypeToSend.equals("junk")) {
System.out.println("Assertion format: junk");
mySAML = "my dog has fleas";
} else {
if (formatTypeToSend.equals("empty")) {
System.out.println("Assertion format: junk");
mySAML = "";
} else {
System.out.println("App received an invalid Assertion format request - exiting");
return;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Caught an exception trying to obtain the saml assertion" + e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
return;
}
System.out.println("SAMLAssertion to send: " + mySAML);
Client client = ClientBuilder.newClient();
if (headerFormat.equals("propagate_token_string_true")) {
System.out.println("Set the propagation handler string property - true");
client.property("com.ibm.ws.jaxrs.client.saml.sendToken", "true");
}
if (headerFormat.equals("propagate_token_boolean_true")) {
System.out.println("Set the propagation handler boolean property - true");
client.property("com.ibm.ws.jaxrs.client.saml.sendToken", true);
}
if (headerFormat.equals("propagate_token_string_false")) {
System.out.println("Set the propagation handler string property - false");
client.property("com.ibm.ws.jaxrs.client.saml.sendToken", "false");
}
if (headerFormat.equals("propagate_token_boolean_false")) {
System.out.println("Set the propagation handler boolean property - false");
client.property("com.ibm.ws.jaxrs.client.saml.sendToken", false);
}
WebTarget myResource = client.target(appToCall).queryParam("saml_name", headerName);
try {
String Rresponse = null;
if (!headerFormat.contains("propagate_token")) {
System.out.println("Pass the header");
Rresponse = myResource.request(MediaType.TEXT_PLAIN).header(headerName, mySAML).header("saml_name", headerName).get(String.class);
} else {
System.out.println("Use the propagation handler");
Rresponse = myResource.request(MediaType.TEXT_PLAIN).header("saml_name", headerName).get(String.class);
}
System.out.println("Response: " + Rresponse);
System.out.println("exiting the svc client");
PrintWriter pw = response.getWriter();
pw.println(Rresponse);
} catch (Exception e) {
e.printStackTrace();
if (e.getClass().getName().equals("javax.ws.rs.NotAuthorizedException")) {
System.out.println("Caught a 401 exception calling external App.");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
} else {
System.out.println("Caught an exception calling external App.");
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
}
/**
* Checks to see if the provided URL contains a URL-encoded {@code "://"} string. The URL-encoded string equivalent is
* {@code "%3A%2F%2F"}.
*/
boolean isUrlEncodedUrl(String url) {
return (url != null && url.contains("%3A%2F%2F"));
}
private void testUnsetToken() {
try {
PropagationHelper.getEncodedSaml20Token(false);
} catch (Exception e) {
System.out.println("failed on False");
}
try {
PropagationHelper.getEncodedSaml20Token(true);
} catch (Exception e) {
System.out.println("failed on true");
}
try {
PropagationHelper.getSaml20Token();
} catch (Exception e) {
System.out.println("failed on text");
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doWorker(request, response);
return;
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doWorker(request, response);
return;
}
}
| epl-1.0 |
jcryptool/crypto | org.jcryptool.crypto.classic.substitution/src/org/jcryptool/crypto/classic/substitution/SubstitutionPlugin.java | 819 | // -----BEGIN DISCLAIMER-----
/*******************************************************************************
* Copyright (c) 2011, 2021 JCrypTool Team and Contributors
*
* All rights reserved. This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
// -----END DISCLAIMER-----
package org.jcryptool.crypto.classic.substitution;
import org.eclipse.ui.plugin.AbstractUIPlugin;
public class SubstitutionPlugin extends AbstractUIPlugin {
/** The plug-in ID. */
public static final String PLUGIN_ID = "org.jcryptool.crypto.classic.substitution"; //$NON-NLS-1$
}
| epl-1.0 |
LangleyStudios/eclipse-avro | test/org.eclipse.emf.ecore/src/org/eclipse/emf/ecore/util/Switch.java | 3244 | /**
* Copyright (c) 2009 TIBCO Software Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Adrian Price
*/
package org.eclipse.emf.ecore.util;
import java.util.List;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
/**
* An abstract base class for all switch classes.
* @since 2.7
*/
public abstract class Switch<T>
{
/**
* Returns the result of interpreting the object as an instance of '<em>EObject</em>'.
* This implementation returns null;
* returning a non-null result will terminate the switch, but this is the last case anyway.
* @param eObject the target of the switch.
* @return the result of interpreting the object as an instance of '<em>EObject</em>'.
* @see #doSwitch(org.eclipse.emf.ecore.EObject)
* @generated
*/
public T defaultCase(EObject eObject)
{
return null;
}
/**
* Calls <code>caseXXX</code> for each (super-)class of the model until one returns a non-null result;
* it yields that result.
* @param eClass the class or superclass of <code>eObject</code> to consider.
* The class's containing <code>EPackage</code> determines whether the receiving switch object can handle the request.
* @param eObject the model object to pass to the appropriate <code>caseXXX</code>.
* @return the first non-null result returned by a <code>caseXXX</code> call.
*/
protected T doSwitch(EClass eClass, EObject eObject)
{
if (isSwitchFor(eClass.getEPackage()))
{
return doSwitch(eClass.getClassifierID(), eObject);
}
else
{
List<EClass> eSuperTypes = eClass.getESuperTypes();
return eSuperTypes.isEmpty() ? defaultCase(eObject) : doSwitch(eSuperTypes.get(0), eObject);
}
}
/**
* Dispatches the target object to the appropriate <code>caseXXX</code> methods.
* @param eObject the model object to pass to the appropriate <code>caseXXX</code>.
* @return the first non-null result returned by a <code>caseXXX</code> call.
*/
public T doSwitch(EObject eObject)
{
return doSwitch(eObject.eClass(), eObject);
}
/**
* Calls <code>caseXXX</code> for each class of the model until one returns a non-null result;
* it yields that result.
* @param classifierID the {@link EClassifier#getClassifierID() classifier ID} of the (super-)class of <code>eObject</code> relative to its defining {@link EPackage}.
* @param eObject the model object to pass to the appropriate <code>caseXXX</code> method.
* @return the first non-null result returned by a <code>caseXXX</code> call.
*/
protected T doSwitch(int classifierID, EObject eObject)
{
return null;
}
/**
* Indicates whether the receiver is a switch for the specified package.
* @param ePackage the package of interest.
* @return <code>true</code> if the receiver is a switch for <code>package</code>.
*/
protected abstract boolean isSwitchFor(EPackage ePackage);
}
| epl-1.0 |
teamfx/openjfx-9-dev-rt | modules/javafx.controls/src/main/java/javafx/scene/control/TabPane.java | 30524 | /*
* Copyright (c) 2011, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.scene.control;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.sun.javafx.collections.UnmodifiableListSet;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ObjectPropertyBase;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.WritableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Side;
import javafx.scene.AccessibleAttribute;
import javafx.scene.AccessibleRole;
import javafx.css.StyleableDoubleProperty;
import javafx.css.CssMetaData;
import javafx.css.PseudoClass;
import javafx.css.converter.SizeConverter;
import javafx.scene.control.skin.TabPaneSkin;
import javafx.beans.DefaultProperty;
import javafx.css.Styleable;
import javafx.css.StyleableProperty;
import javafx.scene.Node;
/**
* <p>A control that allows switching between a group of {@link Tab Tabs}. Only one tab
* is visible at a time. Tabs are added to the TabPane by using the {@link #getTabs}.</p>
*
* <p>Tabs in a TabPane can be positioned at any of the four sides by specifying the
* {@link Side}. </p>
*
* <p>A TabPane has two modes floating or recessed. Applying the styleclass STYLE_CLASS_FLOATING
* will change the TabPane mode to floating.</p>
*
* <p>The tabs width and height can be set to a specific size by
* setting the min and max for height and width. TabPane default width will be
* determined by the largest content width in the TabPane. This is the same for the height.
* If a different size is desired the width and height of the TabPane can
* be overridden by setting the min, pref and max size.</p>
*
* <p>When the number of tabs do not fit the TabPane a menu button will appear on the right.
* The menu button is used to select the tabs that are currently not visible.
* </p>
*
* <p>Example:</p>
* <pre><code>
* TabPane tabPane = new TabPane();
* Tab tab = new Tab();
* tab.setText("new tab");
* tab.setContent(new Rectangle(200,200, Color.LIGHTSTEELBLUE));
* tabPane.getTabs().add(tab);
* </code></pre>
*
* @see Tab
* @since JavaFX 2.0
*/
@DefaultProperty("tabs")
public class TabPane extends Control {
private static final double DEFAULT_TAB_MIN_WIDTH = 0;
private static final double DEFAULT_TAB_MAX_WIDTH = Double.MAX_VALUE;
private static final double DEFAULT_TAB_MIN_HEIGHT = 0;
private static final double DEFAULT_TAB_MAX_HEIGHT = Double.MAX_VALUE;
/**
* TabPane mode will be changed to floating allowing the TabPane
* to be placed alongside other control.
*/
public static final String STYLE_CLASS_FLOATING = "floating";
/**
* Constructs a new TabPane.
*/
public TabPane() {
this((Tab[])null);
}
/**
* Constructs a new TabPane with the given tabs set to show.
*
* @param tabs The {@link Tab tabs} to display inside the TabPane.
* @since JavaFX 8u40
*/
public TabPane(Tab... tabs) {
getStyleClass().setAll("tab-pane");
setAccessibleRole(AccessibleRole.TAB_PANE);
setSelectionModel(new TabPaneSelectionModel(this));
this.tabs.addListener((ListChangeListener<Tab>) c -> {
while (c.next()) {
for (Tab tab : c.getRemoved()) {
if (tab != null && !getTabs().contains(tab)) {
tab.setTabPane(null);
}
}
for (Tab tab : c.getAddedSubList()) {
if (tab != null) {
tab.setTabPane(TabPane.this);
}
}
}
});
if (tabs != null) {
getTabs().addAll(tabs);
}
// initialize pseudo-class state
Side edge = getSide();
pseudoClassStateChanged(TOP_PSEUDOCLASS_STATE, (edge == Side.TOP));
pseudoClassStateChanged(RIGHT_PSEUDOCLASS_STATE, (edge == Side.RIGHT));
pseudoClassStateChanged(BOTTOM_PSEUDOCLASS_STATE, (edge == Side.BOTTOM));
pseudoClassStateChanged(LEFT_PSEUDOCLASS_STATE, (edge == Side.LEFT));
}
private ObservableList<Tab> tabs = FXCollections.observableArrayList();
/**
* <p>The tabs to display in this TabPane. Changing this ObservableList will
* immediately result in the TabPane updating to display the new contents
* of this ObservableList.</p>
*
* <p>If the tabs ObservableList changes, the selected tab will remain the previously
* selected tab, if it remains within this ObservableList. If the previously
* selected tab is no longer in the tabs ObservableList, the selected tab will
* become the first tab in the ObservableList.</p>
* @return the list of tabs
*/
public final ObservableList<Tab> getTabs() {
return tabs;
}
private ObjectProperty<SingleSelectionModel<Tab>> selectionModel = new SimpleObjectProperty<SingleSelectionModel<Tab>>(this, "selectionModel");
/**
* <p>Sets the model used for tab selection. By changing the model you can alter
* how the tabs are selected and which tabs are first or last.</p>
* @param value the selection model
*/
public final void setSelectionModel(SingleSelectionModel<Tab> value) { selectionModel.set(value); }
/**
* <p>Gets the model used for tab selection.</p>
* @return the model used for tab selection
*/
public final SingleSelectionModel<Tab> getSelectionModel() { return selectionModel.get(); }
/**
* The selection model used for selecting tabs.
* @return selection model property
*/
public final ObjectProperty<SingleSelectionModel<Tab>> selectionModelProperty() { return selectionModel; }
private ObjectProperty<Side> side;
/**
* <p>The position to place the tabs in this TabPane. Whenever this changes
* the TabPane will immediately update the location of the tabs to reflect
* this.</p>
*
* @param value the side
*/
public final void setSide(Side value) {
sideProperty().set(value);
}
/**
* The current position of the tabs in the TabPane. The default position
* for the tabs is Side.Top.
*
* @return The current position of the tabs in the TabPane.
*/
public final Side getSide() {
return side == null ? Side.TOP : side.get();
}
/**
* The position of the tabs in the TabPane.
* @return the side property
*/
public final ObjectProperty<Side> sideProperty() {
if (side == null) {
side = new ObjectPropertyBase<Side>(Side.TOP) {
private Side oldSide;
@Override protected void invalidated() {
oldSide = get();
pseudoClassStateChanged(TOP_PSEUDOCLASS_STATE, (oldSide == Side.TOP || oldSide == null));
pseudoClassStateChanged(RIGHT_PSEUDOCLASS_STATE, (oldSide == Side.RIGHT));
pseudoClassStateChanged(BOTTOM_PSEUDOCLASS_STATE, (oldSide == Side.BOTTOM));
pseudoClassStateChanged(LEFT_PSEUDOCLASS_STATE, (oldSide == Side.LEFT));
}
@Override
public Object getBean() {
return TabPane.this;
}
@Override
public String getName() {
return "side";
}
};
}
return side;
}
private ObjectProperty<TabClosingPolicy> tabClosingPolicy;
/**
* <p>Specifies how the TabPane handles tab closing from an end-users
* perspective. The options are:</p>
*
* <ul>
* <li> TabClosingPolicy.UNAVAILABLE: Tabs can not be closed by the user
* <li> TabClosingPolicy.SELECTED_TAB: Only the currently selected tab will
* have the option to be closed, with a graphic next to the tab
* text being shown. The graphic will disappear when a tab is no
* longer selected.
* <li> TabClosingPolicy.ALL_TABS: All tabs will have the option to be
* closed.
* </ul>
*
* <p>Refer to the {@link TabClosingPolicy} enumeration for further details.</p>
*
* The default closing policy is TabClosingPolicy.SELECTED_TAB
* @param value the closing policy
*/
public final void setTabClosingPolicy(TabClosingPolicy value) {
tabClosingPolicyProperty().set(value);
}
/**
* The closing policy for the tabs.
*
* @return The closing policy for the tabs.
*/
public final TabClosingPolicy getTabClosingPolicy() {
return tabClosingPolicy == null ? TabClosingPolicy.SELECTED_TAB : tabClosingPolicy.get();
}
/**
* The closing policy for the tabs.
* @return the closing policy property
*/
public final ObjectProperty<TabClosingPolicy> tabClosingPolicyProperty() {
if (tabClosingPolicy == null) {
tabClosingPolicy = new SimpleObjectProperty<TabClosingPolicy>(this, "tabClosingPolicy", TabClosingPolicy.SELECTED_TAB);
}
return tabClosingPolicy;
}
private BooleanProperty rotateGraphic;
/**
* <p>Specifies whether the graphic inside a Tab is rotated or not, such
* that it is always upright, or rotated in the same way as the Tab text is.</p>
*
* <p>By default rotateGraphic is set to false, to represent the fact that
* the graphic isn't rotated, resulting in it always appearing upright. If
* rotateGraphic is set to {@code true}, the graphic will rotate such that it
* rotates with the tab text.</p>
*
* @param value a flag indicating whether to rotate the graphic
*/
public final void setRotateGraphic(boolean value) {
rotateGraphicProperty().set(value);
}
/**
* Returns {@code true} if the graphic inside a Tab is rotated. The
* default is {@code false}
*
* @return the rotatedGraphic state.
*/
public final boolean isRotateGraphic() {
return rotateGraphic == null ? false : rotateGraphic.get();
}
/**
* The rotateGraphic state of the tabs in the TabPane.
* @return the rotateGraphic property
*/
public final BooleanProperty rotateGraphicProperty() {
if (rotateGraphic == null) {
rotateGraphic = new SimpleBooleanProperty(this, "rotateGraphic", false);
}
return rotateGraphic;
}
private DoubleProperty tabMinWidth;
/**
* <p>The minimum width of the tabs in the TabPane. This can be used to limit
* the length of text in tabs to prevent truncation. Setting the min equal
* to the max will fix the width of the tab. By default the min equals to the max.
*
* This value can also be set via CSS using {@code -fx-tab-min-width}
*
* </p>
* @param value the minimum width of the tabs
*/
public final void setTabMinWidth(double value) {
tabMinWidthProperty().setValue(value);
}
/**
* The minimum width of the tabs in the TabPane.
*
* @return The minimum width of the tabs
*/
public final double getTabMinWidth() {
return tabMinWidth == null ? DEFAULT_TAB_MIN_WIDTH : tabMinWidth.getValue();
}
/**
* The minimum width of the tabs in the TabPane.
* @return the minimum width property
*/
public final DoubleProperty tabMinWidthProperty() {
if (tabMinWidth == null) {
tabMinWidth = new StyleableDoubleProperty(DEFAULT_TAB_MIN_WIDTH) {
@Override
public CssMetaData<TabPane,Number> getCssMetaData() {
return StyleableProperties.TAB_MIN_WIDTH;
}
@Override
public Object getBean() {
return TabPane.this;
}
@Override
public String getName() {
return "tabMinWidth";
}
};
}
return tabMinWidth;
}
/**
* <p>Specifies the maximum width of a tab. This can be used to limit
* the length of text in tabs. If the tab text is longer than the maximum
* width the text will be truncated. Setting the max equal
* to the min will fix the width of the tab. By default the min equals to the max
*
* This value can also be set via CSS using {@code -fx-tab-max-width}.</p>
*/
private DoubleProperty tabMaxWidth;
public final void setTabMaxWidth(double value) {
tabMaxWidthProperty().setValue(value);
}
/**
* The maximum width of the tabs in the TabPane.
*
* @return The maximum width of the tabs
*/
public final double getTabMaxWidth() {
return tabMaxWidth == null ? DEFAULT_TAB_MAX_WIDTH : tabMaxWidth.getValue();
}
/**
* The maximum width of the tabs in the TabPane.
* @return the maximum width property
*/
public final DoubleProperty tabMaxWidthProperty() {
if (tabMaxWidth == null) {
tabMaxWidth = new StyleableDoubleProperty(DEFAULT_TAB_MAX_WIDTH) {
@Override
public CssMetaData<TabPane,Number> getCssMetaData() {
return StyleableProperties.TAB_MAX_WIDTH;
}
@Override
public Object getBean() {
return TabPane.this;
}
@Override
public String getName() {
return "tabMaxWidth";
}
};
}
return tabMaxWidth;
}
private DoubleProperty tabMinHeight;
/**
* <p>The minimum height of the tabs in the TabPane. This can be used to limit
* the height in tabs. Setting the min equal to the max will fix the height
* of the tab. By default the min equals to the max.
*
* This value can also be set via CSS using {@code -fx-tab-min-height}
* </p>
* @param value the minimum height of the tabs
*/
public final void setTabMinHeight(double value) {
tabMinHeightProperty().setValue(value);
}
/**
* The minimum height of the tabs in the TabPane.
*
* @return the minimum height of the tabs
*/
public final double getTabMinHeight() {
return tabMinHeight == null ? DEFAULT_TAB_MIN_HEIGHT : tabMinHeight.getValue();
}
/**
* The minimum height of the tab.
* @return the minimum height property
*/
public final DoubleProperty tabMinHeightProperty() {
if (tabMinHeight == null) {
tabMinHeight = new StyleableDoubleProperty(DEFAULT_TAB_MIN_HEIGHT) {
@Override
public CssMetaData<TabPane,Number> getCssMetaData() {
return StyleableProperties.TAB_MIN_HEIGHT;
}
@Override
public Object getBean() {
return TabPane.this;
}
@Override
public String getName() {
return "tabMinHeight";
}
};
}
return tabMinHeight;
}
/**
* <p>The maximum height if the tabs in the TabPane. This can be used to limit
* the height in tabs. Setting the max equal to the min will fix the height
* of the tab. By default the min equals to the max.
*
* This value can also be set via CSS using -fx-tab-max-height
* </p>
*/
private DoubleProperty tabMaxHeight;
public final void setTabMaxHeight(double value) {
tabMaxHeightProperty().setValue(value);
}
/**
* The maximum height of the tabs in the TabPane.
*
* @return The maximum height of the tabs
*/
public final double getTabMaxHeight() {
return tabMaxHeight == null ? DEFAULT_TAB_MAX_HEIGHT : tabMaxHeight.getValue();
}
/**
* <p>The maximum height of the tabs in the TabPane.</p>
* @return the maximum height of the tabs
*/
public final DoubleProperty tabMaxHeightProperty() {
if (tabMaxHeight == null) {
tabMaxHeight = new StyleableDoubleProperty(DEFAULT_TAB_MAX_HEIGHT) {
@Override
public CssMetaData<TabPane,Number> getCssMetaData() {
return StyleableProperties.TAB_MAX_HEIGHT;
}
@Override
public Object getBean() {
return TabPane.this;
}
@Override
public String getName() {
return "tabMaxHeight";
}
};
}
return tabMaxHeight;
}
/** {@inheritDoc} */
@Override protected Skin<?> createDefaultSkin() {
return new TabPaneSkin(this);
}
/** {@inheritDoc} */
@Override public Node lookup(String selector) {
Node n = super.lookup(selector);
if (n == null) {
for(Tab tab : tabs) {
n = tab.lookup(selector);
if (n != null) break;
}
}
return n;
}
/** {@inheritDoc} */
public Set<Node> lookupAll(String selector) {
if (selector == null) return null;
final List<Node> results = new ArrayList<>();
results.addAll(super.lookupAll(selector));
for(Tab tab : tabs) {
results.addAll(tab.lookupAll(selector));
}
return new UnmodifiableListSet<Node>(results);
}
/***************************************************************************
* *
* Stylesheet Handling *
* *
**************************************************************************/
private static class StyleableProperties {
private static final CssMetaData<TabPane,Number> TAB_MIN_WIDTH =
new CssMetaData<TabPane,Number>("-fx-tab-min-width",
SizeConverter.getInstance(), DEFAULT_TAB_MIN_WIDTH) {
@Override
public boolean isSettable(TabPane n) {
return n.tabMinWidth == null || !n.tabMinWidth.isBound();
}
@Override
public StyleableProperty<Number> getStyleableProperty(TabPane n) {
return (StyleableProperty<Number>)(WritableValue<Number>)n.tabMinWidthProperty();
}
};
private static final CssMetaData<TabPane,Number> TAB_MAX_WIDTH =
new CssMetaData<TabPane,Number>("-fx-tab-max-width",
SizeConverter.getInstance(), DEFAULT_TAB_MAX_WIDTH) {
@Override
public boolean isSettable(TabPane n) {
return n.tabMaxWidth == null || !n.tabMaxWidth.isBound();
}
@Override
public StyleableProperty<Number> getStyleableProperty(TabPane n) {
return (StyleableProperty<Number>)(WritableValue<Number>)n.tabMaxWidthProperty();
}
};
private static final CssMetaData<TabPane,Number> TAB_MIN_HEIGHT =
new CssMetaData<TabPane,Number>("-fx-tab-min-height",
SizeConverter.getInstance(), DEFAULT_TAB_MIN_HEIGHT) {
@Override
public boolean isSettable(TabPane n) {
return n.tabMinHeight == null || !n.tabMinHeight.isBound();
}
@Override
public StyleableProperty<Number> getStyleableProperty(TabPane n) {
return (StyleableProperty<Number>)(WritableValue<Number>)n.tabMinHeightProperty();
}
};
private static final CssMetaData<TabPane,Number> TAB_MAX_HEIGHT =
new CssMetaData<TabPane,Number>("-fx-tab-max-height",
SizeConverter.getInstance(), DEFAULT_TAB_MAX_HEIGHT) {
@Override
public boolean isSettable(TabPane n) {
return n.tabMaxHeight == null || !n.tabMaxHeight.isBound();
}
@Override
public StyleableProperty<Number> getStyleableProperty(TabPane n) {
return (StyleableProperty<Number>)(WritableValue<Number>)n.tabMaxHeightProperty();
}
};
private static final List<CssMetaData<? extends Styleable, ?>> STYLEABLES;
static {
final List<CssMetaData<? extends Styleable, ?>> styleables =
new ArrayList<CssMetaData<? extends Styleable, ?>>(Control.getClassCssMetaData());
styleables.add(TAB_MIN_WIDTH);
styleables.add(TAB_MAX_WIDTH);
styleables.add(TAB_MIN_HEIGHT);
styleables.add(TAB_MAX_HEIGHT);
STYLEABLES = Collections.unmodifiableList(styleables);
}
}
/**
* @return The CssMetaData associated with this class, which may include the
* CssMetaData of its superclasses.
* @since JavaFX 8.0
*/
public static List<CssMetaData<? extends Styleable, ?>> getClassCssMetaData() {
return StyleableProperties.STYLEABLES;
}
/**
* {@inheritDoc}
* @since JavaFX 8.0
*/
@Override
public List<CssMetaData<? extends Styleable, ?>> getControlCssMetaData() {
return getClassCssMetaData();
}
private static final PseudoClass TOP_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("top");
private static final PseudoClass BOTTOM_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("bottom");
private static final PseudoClass LEFT_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("left");
private static final PseudoClass RIGHT_PSEUDOCLASS_STATE = PseudoClass.getPseudoClass("right");
/***************************************************************************
* *
* Support classes *
* *
**************************************************************************/
static class TabPaneSelectionModel extends SingleSelectionModel<Tab> {
private final TabPane tabPane;
public TabPaneSelectionModel(final TabPane t) {
if (t == null) {
throw new NullPointerException("TabPane can not be null");
}
this.tabPane = t;
// watching for changes to the items list content
final ListChangeListener<Tab> itemsContentObserver = c -> {
while (c.next()) {
for (Tab tab : c.getRemoved()) {
if (tab != null && !tabPane.getTabs().contains(tab)) {
if (tab.isSelected()) {
tab.setSelected(false);
final int tabIndex = c.getFrom();
// we always try to select the nearest, non-disabled
// tab from the position of the closed tab.
findNearestAvailableTab(tabIndex, true);
}
}
}
if (c.wasAdded() || c.wasRemoved()) {
// The selected tab index can be out of sync with the list of tab if
// we add or remove tabs before the selected tab.
if (getSelectedIndex() != tabPane.getTabs().indexOf(getSelectedItem())) {
clearAndSelect(tabPane.getTabs().indexOf(getSelectedItem()));
}
}
}
if (getSelectedIndex() == -1 && getSelectedItem() == null && tabPane.getTabs().size() > 0) {
// we go looking for the first non-disabled tab, as opposed to
// just selecting the first tab (fix for RT-36908)
findNearestAvailableTab(0, true);
} else if (tabPane.getTabs().isEmpty()) {
clearSelection();
}
};
if (this.tabPane.getTabs() != null) {
this.tabPane.getTabs().addListener(itemsContentObserver);
}
}
// API Implementation
@Override public void select(int index) {
if (index < 0 || (getItemCount() > 0 && index >= getItemCount()) ||
(index == getSelectedIndex() && getModelItem(index).isSelected())) {
return;
}
// Unselect the old tab
if (getSelectedIndex() >= 0 && getSelectedIndex() < tabPane.getTabs().size()) {
tabPane.getTabs().get(getSelectedIndex()).setSelected(false);
}
setSelectedIndex(index);
Tab tab = getModelItem(index);
if (tab != null) {
setSelectedItem(tab);
}
// Select the new tab
if (getSelectedIndex() >= 0 && getSelectedIndex() < tabPane.getTabs().size()) {
tabPane.getTabs().get(getSelectedIndex()).setSelected(true);
}
/* Does this get all the change events */
tabPane.notifyAccessibleAttributeChanged(AccessibleAttribute.FOCUS_ITEM);
}
@Override public void select(Tab tab) {
final int itemCount = getItemCount();
for (int i = 0; i < itemCount; i++) {
final Tab value = getModelItem(i);
if (value != null && value.equals(tab)) {
select(i);
return;
}
}
if (tab != null) {
setSelectedItem(tab);
}
}
@Override protected Tab getModelItem(int index) {
final ObservableList<Tab> items = tabPane.getTabs();
if (items == null) return null;
if (index < 0 || index >= items.size()) return null;
return items.get(index);
}
@Override protected int getItemCount() {
final ObservableList<Tab> items = tabPane.getTabs();
return items == null ? 0 : items.size();
}
private Tab findNearestAvailableTab(int tabIndex, boolean doSelect) {
// we always try to select the nearest, non-disabled
// tab from the position of the closed tab.
final int tabCount = getItemCount();
int i = 1;
Tab bestTab = null;
while (true) {
// look leftwards
int downPos = tabIndex - i;
if (downPos >= 0) {
Tab _tab = getModelItem(downPos);
if (_tab != null && ! _tab.isDisable()) {
bestTab = _tab;
break;
}
}
// look rightwards. We subtract one as we need
// to take into account that a tab has been removed
// and if we don't do this we'll miss the tab
// to the right of the tab (as it has moved into
// the removed tabs position).
int upPos = tabIndex + i - 1;
if (upPos < tabCount) {
Tab _tab = getModelItem(upPos);
if (_tab != null && ! _tab.isDisable()) {
bestTab = _tab;
break;
}
}
if (downPos < 0 && upPos >= tabCount) {
break;
}
i++;
}
if (doSelect && bestTab != null) {
select(bestTab);
}
return bestTab;
}
}
/**
* <p>This specifies how the TabPane handles tab closing from an end-users
* perspective. The options are:</p>
*
* <ul>
* <li> TabClosingPolicy.UNAVAILABLE: Tabs can not be closed by the user
* <li> TabClosingPolicy.SELECTED_TAB: Only the currently selected tab will
* have the option to be closed, with a graphic next to the tab
* text being shown. The graphic will disappear when a tab is no
* longer selected.
* <li> TabClosingPolicy.ALL_TABS: All tabs will have the option to be
* closed.
* </ul>
* @since JavaFX 2.0
*/
public enum TabClosingPolicy {
/**
* Only the currently selected tab will have the option to be closed, with a
* graphic next to the tab text being shown. The graphic will disappear when
* a tab is no longer selected.
*/
SELECTED_TAB,
/**
* All tabs will have the option to be closed.
*/
ALL_TABS,
/**
* Tabs can not be closed by the user.
*/
UNAVAILABLE
}
}
| gpl-2.0 |
debian-pkg-android-tools/android-platform-libcore | ojluni/src/main/java/java/util/Date.java | 57234 | /*
* Copyright (C) 2014 The Android Open Source Project
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
import java.text.DateFormat;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.lang.ref.SoftReference;
import sun.util.calendar.BaseCalendar;
import sun.util.calendar.CalendarDate;
import sun.util.calendar.CalendarSystem;
import sun.util.calendar.CalendarUtils;
import sun.util.calendar.Era;
import sun.util.calendar.Gregorian;
/**
* The class <code>Date</code> represents a specific instant
* in time, with millisecond precision.
* <p>
* Prior to JDK 1.1, the class <code>Date</code> had two additional
* functions. It allowed the interpretation of dates as year, month, day, hour,
* minute, and second values. It also allowed the formatting and parsing
* of date strings. Unfortunately, the API for these functions was not
* amenable to internationalization. As of JDK 1.1, the
* <code>Calendar</code> class should be used to convert between dates and time
* fields and the <code>DateFormat</code> class should be used to format and
* parse date strings.
* The corresponding methods in <code>Date</code> are deprecated.
* <p>
* Although the <code>Date</code> class is intended to reflect
* coordinated universal time (UTC), it may not do so exactly,
* depending on the host environment of the Java Virtual Machine.
* Nearly all modern operating systems assume that 1 day =
* 24 × 60 × 60 = 86400 seconds
* in all cases. In UTC, however, about once every year or two there
* is an extra second, called a "leap second." The leap
* second is always added as the last second of the day, and always
* on December 31 or June 30. For example, the last minute of the
* year 1995 was 61 seconds long, thanks to an added leap second.
* Most computer clocks are not accurate enough to be able to reflect
* the leap-second distinction.
* <p>
* Some computer standards are defined in terms of Greenwich mean
* time (GMT), which is equivalent to universal time (UT). GMT is
* the "civil" name for the standard; UT is the
* "scientific" name for the same standard. The
* distinction between UTC and UT is that UTC is based on an atomic
* clock and UT is based on astronomical observations, which for all
* practical purposes is an invisibly fine hair to split. Because the
* earth's rotation is not uniform (it slows down and speeds up
* in complicated ways), UT does not always flow uniformly. Leap
* seconds are introduced as needed into UTC so as to keep UTC within
* 0.9 seconds of UT1, which is a version of UT with certain
* corrections applied. There are other time and date systems as
* well; for example, the time scale used by the satellite-based
* global positioning system (GPS) is synchronized to UTC but is
* <i>not</i> adjusted for leap seconds. An interesting source of
* further information is the U.S. Naval Observatory, particularly
* the Directorate of Time at:
* <blockquote><pre>
* <a href=http://tycho.usno.navy.mil>http://tycho.usno.navy.mil</a>
* </pre></blockquote>
* <p>
* and their definitions of "Systems of Time" at:
* <blockquote><pre>
* <a href=http://tycho.usno.navy.mil/systime.html>http://tycho.usno.navy.mil/systime.html</a>
* </pre></blockquote>
* <p>
* In all methods of class <code>Date</code> that accept or return
* year, month, date, hours, minutes, and seconds values, the
* following representations are used:
* <ul>
* <li>A year <i>y</i> is represented by the integer
* <i>y</i> <code>- 1900</code>.
* <li>A month is represented by an integer from 0 to 11; 0 is January,
* 1 is February, and so forth; thus 11 is December.
* <li>A date (day of month) is represented by an integer from 1 to 31
* in the usual manner.
* <li>An hour is represented by an integer from 0 to 23. Thus, the hour
* from midnight to 1 a.m. is hour 0, and the hour from noon to 1
* p.m. is hour 12.
* <li>A minute is represented by an integer from 0 to 59 in the usual manner.
* <li>A second is represented by an integer from 0 to 61; the values 60 and
* 61 occur only for leap seconds and even then only in Java
* implementations that actually track leap seconds correctly. Because
* of the manner in which leap seconds are currently introduced, it is
* extremely unlikely that two leap seconds will occur in the same
* minute, but this specification follows the date and time conventions
* for ISO C.
* </ul>
* <p>
* In all cases, arguments given to methods for these purposes need
* not fall within the indicated ranges; for example, a date may be
* specified as January 32 and is interpreted as meaning February 1.
*
* @author James Gosling
* @author Arthur van Hoff
* @author Alan Liu
* @see java.text.DateFormat
* @see java.util.Calendar
* @see java.util.TimeZone
* @since JDK1.0
*/
public class Date
implements java.io.Serializable, Cloneable, Comparable<Date>
{
private static final BaseCalendar gcal =
CalendarSystem.getGregorianCalendar();
private static BaseCalendar jcal;
private transient long fastTime;
/*
* If cdate is null, then fastTime indicates the time in millis.
* If cdate.isNormalized() is true, then fastTime and cdate are in
* synch. Otherwise, fastTime is ignored, and cdate indicates the
* time.
*/
private transient BaseCalendar.Date cdate;
// Initialized just before the value is used. See parse().
private static int defaultCenturyStart;
/* use serialVersionUID from modified java.util.Date for
* interoperability with JDK1.1. The Date was modified to write
* and read only the UTC time.
*/
private static final long serialVersionUID = 7523967970034938905L;
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents the time at which it was allocated, measured to the
* nearest millisecond.
*
* @see java.lang.System#currentTimeMillis()
*/
public Date() {
this(System.currentTimeMillis());
}
/**
* Allocates a <code>Date</code> object and initializes it to
* represent the specified number of milliseconds since the
* standard base time known as "the epoch", namely January 1,
* 1970, 00:00:00 GMT.
*
* @param date the milliseconds since January 1, 1970, 00:00:00 GMT.
* @see java.lang.System#currentTimeMillis()
*/
public Date(long date) {
fastTime = date;
}
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents midnight, local time, at the beginning of the day
* specified by the <code>year</code>, <code>month</code>, and
* <code>date</code> arguments.
*
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date)</code>
* or <code>GregorianCalendar(year + 1900, month, date)</code>.
*/
@Deprecated
public Date(int year, int month, int date) {
this(year, month, date, 0, 0, 0);
}
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents the instant at the start of the minute specified by
* the <code>year</code>, <code>month</code>, <code>date</code>,
* <code>hrs</code>, and <code>min</code> arguments, in the local
* time zone.
*
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @param hrs the hours between 0-23.
* @param min the minutes between 0-59.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date,
* hrs, min)</code> or <code>GregorianCalendar(year + 1900,
* month, date, hrs, min)</code>.
*/
@Deprecated
public Date(int year, int month, int date, int hrs, int min) {
this(year, month, date, hrs, min, 0);
}
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents the instant at the start of the second specified
* by the <code>year</code>, <code>month</code>, <code>date</code>,
* <code>hrs</code>, <code>min</code>, and <code>sec</code> arguments,
* in the local time zone.
*
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @param hrs the hours between 0-23.
* @param min the minutes between 0-59.
* @param sec the seconds between 0-59.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date,
* hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900,
* month, date, hrs, min, sec)</code>.
*/
@Deprecated
public Date(int year, int month, int date, int hrs, int min, int sec) {
int y = year + 1900;
// month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
if (month >= 12) {
y += month / 12;
month %= 12;
} else if (month < 0) {
y += CalendarUtils.floorDivide(month, 12);
month = CalendarUtils.mod(month, 12);
}
BaseCalendar cal = getCalendarSystem(y);
cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
getTimeImpl();
cdate = null;
}
/**
* Allocates a <code>Date</code> object and initializes it so that
* it represents the date and time indicated by the string
* <code>s</code>, which is interpreted as if by the
* {@link Date#parse} method.
*
* @param s a string representation of the date.
* @see java.text.DateFormat
* @see java.util.Date#parse(java.lang.String)
* @deprecated As of JDK version 1.1,
* replaced by <code>DateFormat.parse(String s)</code>.
*/
@Deprecated
public Date(String s) {
this(parse(s));
}
/**
* Return a copy of this object.
*/
public Object clone() {
Date d = null;
try {
d = (Date)super.clone();
if (cdate != null) {
d.cdate = (BaseCalendar.Date) cdate.clone();
}
} catch (CloneNotSupportedException e) {} // Won't happen
return d;
}
/**
* Determines the date and time based on the arguments. The
* arguments are interpreted as a year, month, day of the month,
* hour of the day, minute within the hour, and second within the
* minute, exactly as for the <tt>Date</tt> constructor with six
* arguments, except that the arguments are interpreted relative
* to UTC rather than to the local time zone. The time indicated is
* returned represented as the distance, measured in milliseconds,
* of that time from the epoch (00:00:00 GMT on January 1, 1970).
*
* @param year the year minus 1900.
* @param month the month between 0-11.
* @param date the day of the month between 1-31.
* @param hrs the hours between 0-23.
* @param min the minutes between 0-59.
* @param sec the seconds between 0-59.
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT for
* the date and time specified by the arguments.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(year + 1900, month, date,
* hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900,
* month, date, hrs, min, sec)</code>, using a UTC
* <code>TimeZone</code>, followed by <code>Calendar.getTime().getTime()</code>.
*/
@Deprecated
public static long UTC(int year, int month, int date,
int hrs, int min, int sec) {
int y = year + 1900;
// month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
if (month >= 12) {
y += month / 12;
month %= 12;
} else if (month < 0) {
y += CalendarUtils.floorDivide(month, 12);
month = CalendarUtils.mod(month, 12);
}
int m = month + 1;
BaseCalendar cal = getCalendarSystem(y);
BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null);
udate.setNormalizedDate(y, m, date).setTimeOfDay(hrs, min, sec, 0);
// Use a Date instance to perform normalization. Its fastTime
// is the UTC value after the normalization.
Date d = new Date(0);
d.normalize(udate);
return d.fastTime;
}
/**
* Attempts to interpret the string <tt>s</tt> as a representation
* of a date and time. If the attempt is successful, the time
* indicated is returned represented as the distance, measured in
* milliseconds, of that time from the epoch (00:00:00 GMT on
* January 1, 1970). If the attempt fails, an
* <tt>IllegalArgumentException</tt> is thrown.
* <p>
* It accepts many syntaxes; in particular, it recognizes the IETF
* standard date syntax: "Sat, 12 Aug 1995 13:30:00 GMT". It also
* understands the continental U.S. time-zone abbreviations, but for
* general use, a time-zone offset should be used: "Sat, 12 Aug 1995
* 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich
* meridian). If no time zone is specified, the local time zone is
* assumed. GMT and UTC are considered equivalent.
* <p>
* The string <tt>s</tt> is processed from left to right, looking for
* data of interest. Any material in <tt>s</tt> that is within the
* ASCII parenthesis characters <tt>(</tt> and <tt>)</tt> is ignored.
* Parentheses may be nested. Otherwise, the only characters permitted
* within <tt>s</tt> are these ASCII characters:
* <blockquote><pre>
* abcdefghijklmnopqrstuvwxyz
* ABCDEFGHIJKLMNOPQRSTUVWXYZ
* 0123456789,+-:/</pre></blockquote>
* and whitespace characters.<p>
* A consecutive sequence of decimal digits is treated as a decimal
* number:<ul>
* <li>If a number is preceded by <tt>+</tt> or <tt>-</tt> and a year
* has already been recognized, then the number is a time-zone
* offset. If the number is less than 24, it is an offset measured
* in hours. Otherwise, it is regarded as an offset in minutes,
* expressed in 24-hour time format without punctuation. A
* preceding <tt>-</tt> means a westward offset. Time zone offsets
* are always relative to UTC (Greenwich). Thus, for example,
* <tt>-5</tt> occurring in the string would mean "five hours west
* of Greenwich" and <tt>+0430</tt> would mean "four hours and
* thirty minutes east of Greenwich." It is permitted for the
* string to specify <tt>GMT</tt>, <tt>UT</tt>, or <tt>UTC</tt>
* redundantly-for example, <tt>GMT-5</tt> or <tt>utc+0430</tt>.
* <li>The number is regarded as a year number if one of the
* following conditions is true:
* <ul>
* <li>The number is equal to or greater than 70 and followed by a
* space, comma, slash, or end of string
* <li>The number is less than 70, and both a month and a day of
* the month have already been recognized</li>
* </ul>
* If the recognized year number is less than 100, it is
* interpreted as an abbreviated year relative to a century of
* which dates are within 80 years before and 19 years after
* the time when the Date class is initialized.
* After adjusting the year number, 1900 is subtracted from
* it. For example, if the current year is 1999 then years in
* the range 19 to 99 are assumed to mean 1919 to 1999, while
* years from 0 to 18 are assumed to mean 2000 to 2018. Note
* that this is slightly different from the interpretation of
* years less than 100 that is used in {@link java.text.SimpleDateFormat}.
* <li>If the number is followed by a colon, it is regarded as an hour,
* unless an hour has already been recognized, in which case it is
* regarded as a minute.
* <li>If the number is followed by a slash, it is regarded as a month
* (it is decreased by 1 to produce a number in the range <tt>0</tt>
* to <tt>11</tt>), unless a month has already been recognized, in
* which case it is regarded as a day of the month.
* <li>If the number is followed by whitespace, a comma, a hyphen, or
* end of string, then if an hour has been recognized but not a
* minute, it is regarded as a minute; otherwise, if a minute has
* been recognized but not a second, it is regarded as a second;
* otherwise, it is regarded as a day of the month. </ul><p>
* A consecutive sequence of letters is regarded as a word and treated
* as follows:<ul>
* <li>A word that matches <tt>AM</tt>, ignoring case, is ignored (but
* the parse fails if an hour has not been recognized or is less
* than <tt>1</tt> or greater than <tt>12</tt>).
* <li>A word that matches <tt>PM</tt>, ignoring case, adds <tt>12</tt>
* to the hour (but the parse fails if an hour has not been
* recognized or is less than <tt>1</tt> or greater than <tt>12</tt>).
* <li>Any word that matches any prefix of <tt>SUNDAY, MONDAY, TUESDAY,
* WEDNESDAY, THURSDAY, FRIDAY</tt>, or <tt>SATURDAY</tt>, ignoring
* case, is ignored. For example, <tt>sat, Friday, TUE</tt>, and
* <tt>Thurs</tt> are ignored.
* <li>Otherwise, any word that matches any prefix of <tt>JANUARY,
* FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
* OCTOBER, NOVEMBER</tt>, or <tt>DECEMBER</tt>, ignoring case, and
* considering them in the order given here, is recognized as
* specifying a month and is converted to a number (<tt>0</tt> to
* <tt>11</tt>). For example, <tt>aug, Sept, april</tt>, and
* <tt>NOV</tt> are recognized as months. So is <tt>Ma</tt>, which
* is recognized as <tt>MARCH</tt>, not <tt>MAY</tt>.
* <li>Any word that matches <tt>GMT, UT</tt>, or <tt>UTC</tt>, ignoring
* case, is treated as referring to UTC.
* <li>Any word that matches <tt>EST, CST, MST</tt>, or <tt>PST</tt>,
* ignoring case, is recognized as referring to the time zone in
* North America that is five, six, seven, or eight hours west of
* Greenwich, respectively. Any word that matches <tt>EDT, CDT,
* MDT</tt>, or <tt>PDT</tt>, ignoring case, is recognized as
* referring to the same time zone, respectively, during daylight
* saving time.</ul><p>
* Once the entire string s has been scanned, it is converted to a time
* result in one of two ways. If a time zone or time-zone offset has been
* recognized, then the year, month, day of month, hour, minute, and
* second are interpreted in UTC and then the time-zone offset is
* applied. Otherwise, the year, month, day of month, hour, minute, and
* second are interpreted in the local time zone.
*
* @param s a string to be parsed as a date.
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by the string argument.
* @see java.text.DateFormat
* @deprecated As of JDK version 1.1,
* replaced by <code>DateFormat.parse(String s)</code>.
*/
@Deprecated
public static long parse(String s) {
int year = Integer.MIN_VALUE;
int mon = -1;
int mday = -1;
int hour = -1;
int min = -1;
int sec = -1;
int millis = -1;
int c = -1;
int i = 0;
int n = -1;
int wst = -1;
int tzoffset = -1;
int prevc = 0;
syntax:
{
if (s == null)
break syntax;
int limit = s.length();
while (i < limit) {
c = s.charAt(i);
i++;
if (c <= ' ' || c == ',')
continue;
if (c == '(') { // skip comments
int depth = 1;
while (i < limit) {
c = s.charAt(i);
i++;
if (c == '(') depth++;
else if (c == ')')
if (--depth <= 0)
break;
}
continue;
}
if ('0' <= c && c <= '9') {
n = c - '0';
while (i < limit && '0' <= (c = s.charAt(i)) && c <= '9') {
n = (n * 10) + (c - '0');
i++;
}
if (prevc == '+' || prevc == '-' && year != Integer.MIN_VALUE) {
if (tzoffset != 0 && tzoffset != -1)
break syntax;
// timezone offset
if (n < 24) {
n = n * 60; // EG. "GMT-3"
// Support for Timezones of the form GMT-3:30. We look for an ':" and
// parse the number following it as loosely as the original hours
// section (i.e, no range or validity checks).
int minutesPart = 0;
if (i < limit && (s.charAt(i) == ':')) {
i++;
while (i < limit && '0' <= (c = s.charAt(i)) && c <= '9') {
minutesPart = (minutesPart * 10) + (c - '0');
i++;
}
}
n += minutesPart;
} else {
n = (n % 100) + ((n / 100) * 60); // eg "GMT-0430"
}
if (prevc == '+') // plus means east of GMT
n = -n;
tzoffset = n;
} else if (n >= 70)
if (year != Integer.MIN_VALUE)
break syntax;
else if (c <= ' ' || c == ',' || c == '/' || i >= limit)
// year = n < 1900 ? n : n - 1900;
year = n;
else
break syntax;
else if (c == ':')
if (hour < 0)
hour = (byte) n;
else if (min < 0)
min = (byte) n;
else
break syntax;
else if (c == '/')
if (mon < 0)
mon = (byte) (n - 1);
else if (mday < 0)
mday = (byte) n;
else
break syntax;
else if (i < limit && c != ',' && c > ' ' && c != '-')
break syntax;
else if (hour >= 0 && min < 0)
min = (byte) n;
else if (min >= 0 && sec < 0)
sec = (byte) n;
else if (mday < 0)
mday = (byte) n;
// Handle two-digit years < 70 (70-99 handled above).
else if (year == Integer.MIN_VALUE && mon >= 0 && mday >= 0)
year = n;
else
break syntax;
prevc = 0;
} else if (c == '/' || c == ':' || c == '+' || c == '-')
prevc = c;
else {
int st = i - 1;
while (i < limit) {
c = s.charAt(i);
if (!('A' <= c && c <= 'Z' || 'a' <= c && c <= 'z'))
break;
i++;
}
if (i <= st + 1)
break syntax;
int k;
for (k = wtb.length; --k >= 0;)
if (wtb[k].regionMatches(true, 0, s, st, i - st)) {
int action = ttb[k];
if (action != 0) {
if (action == 1) { // pm
if (hour > 12 || hour < 1)
break syntax;
else if (hour < 12)
hour += 12;
} else if (action == 14) { // am
if (hour > 12 || hour < 1)
break syntax;
else if (hour == 12)
hour = 0;
} else if (action <= 13) { // month!
if (mon < 0)
mon = (byte) (action - 2);
else
break syntax;
} else {
tzoffset = action - 10000;
}
}
break;
}
if (k < 0)
break syntax;
prevc = 0;
}
}
if (year == Integer.MIN_VALUE || mon < 0 || mday < 0)
break syntax;
// Parse 2-digit years within the correct default century.
if (year < 100) {
synchronized (Date.class) {
if (defaultCenturyStart == 0) {
defaultCenturyStart = gcal.getCalendarDate().getYear() - 80;
}
}
year += (defaultCenturyStart / 100) * 100;
if (year < defaultCenturyStart) year += 100;
}
if (sec < 0)
sec = 0;
if (min < 0)
min = 0;
if (hour < 0)
hour = 0;
BaseCalendar cal = getCalendarSystem(year);
if (tzoffset == -1) { // no time zone specified, have to use local
BaseCalendar.Date ldate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
ldate.setDate(year, mon + 1, mday);
ldate.setTimeOfDay(hour, min, sec, 0);
return cal.getTime(ldate);
}
BaseCalendar.Date udate = (BaseCalendar.Date) cal.newCalendarDate(null); // no time zone
udate.setDate(year, mon + 1, mday);
udate.setTimeOfDay(hour, min, sec, 0);
return cal.getTime(udate) + tzoffset * (60 * 1000);
}
// syntax error
throw new IllegalArgumentException();
}
private final static String wtb[] = {
"am", "pm",
"monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday",
"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december",
"gmt", "ut", "utc", "est", "edt", "cst", "cdt",
"mst", "mdt", "pst", "pdt"
};
private final static int ttb[] = {
14, 1, 0, 0, 0, 0, 0, 0, 0,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
10000 + 0, 10000 + 0, 10000 + 0, // GMT/UT/UTC
10000 + 5 * 60, 10000 + 4 * 60, // EST/EDT
10000 + 6 * 60, 10000 + 5 * 60, // CST/CDT
10000 + 7 * 60, 10000 + 6 * 60, // MST/MDT
10000 + 8 * 60, 10000 + 7 * 60 // PST/PDT
};
/**
* Returns a value that is the result of subtracting 1900 from the
* year that contains or begins with the instant in time represented
* by this <code>Date</code> object, as interpreted in the local
* time zone.
*
* @return the year represented by this date, minus 1900.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.YEAR) - 1900</code>.
*/
@Deprecated
public int getYear() {
return normalize().getYear() - 1900;
}
/**
* Sets the year of this <tt>Date</tt> object to be the specified
* value plus 1900. This <code>Date</code> object is modified so
* that it represents a point in time within the specified year,
* with the month, date, hour, minute, and second the same as
* before, as interpreted in the local time zone. (Of course, if
* the date was February 29, for example, and the year is set to a
* non-leap year, then the new date will be treated as if it were
* on March 1.)
*
* @param year the year value.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.YEAR, year + 1900)</code>.
*/
@Deprecated
public void setYear(int year) {
getCalendarDate().setNormalizedYear(year + 1900);
}
/**
* Returns a number representing the month that contains or begins
* with the instant in time represented by this <tt>Date</tt> object.
* The value returned is between <code>0</code> and <code>11</code>,
* with the value <code>0</code> representing January.
*
* @return the month represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.MONTH)</code>.
*/
@Deprecated
public int getMonth() {
return normalize().getMonth() - 1; // adjust 1-based to 0-based
}
/**
* Sets the month of this date to the specified value. This
* <tt>Date</tt> object is modified so that it represents a point
* in time within the specified month, with the year, date, hour,
* minute, and second the same as before, as interpreted in the
* local time zone. If the date was October 31, for example, and
* the month is set to June, then the new date will be treated as
* if it were on July 1, because June has only 30 days.
*
* @param month the month value between 0-11.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.MONTH, int month)</code>.
*/
@Deprecated
public void setMonth(int month) {
int y = 0;
if (month >= 12) {
y = month / 12;
month %= 12;
} else if (month < 0) {
y = CalendarUtils.floorDivide(month, 12);
month = CalendarUtils.mod(month, 12);
}
BaseCalendar.Date d = getCalendarDate();
if (y != 0) {
d.setNormalizedYear(d.getNormalizedYear() + y);
}
d.setMonth(month + 1); // adjust 0-based to 1-based month numbering
}
/**
* Returns the day of the month represented by this <tt>Date</tt> object.
* The value returned is between <code>1</code> and <code>31</code>
* representing the day of the month that contains or begins with the
* instant in time represented by this <tt>Date</tt> object, as
* interpreted in the local time zone.
*
* @return the day of the month represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.DAY_OF_MONTH)</code>.
*/
@Deprecated
// Android removed stray @deprecated tag.
public int getDate() {
return normalize().getDayOfMonth();
}
/**
* Sets the day of the month of this <tt>Date</tt> object to the
* specified value. This <tt>Date</tt> object is modified so that
* it represents a point in time within the specified day of the
* month, with the year, month, hour, minute, and second the same
* as before, as interpreted in the local time zone. If the date
* was April 30, for example, and the date is set to 31, then it
* will be treated as if it were on May 1, because April has only
* 30 days.
*
* @param date the day of the month value between 1-31.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.DAY_OF_MONTH, int date)</code>.
*/
@Deprecated
public void setDate(int date) {
getCalendarDate().setDayOfMonth(date);
}
/**
* Returns the day of the week represented by this date. The
* returned value (<tt>0</tt> = Sunday, <tt>1</tt> = Monday,
* <tt>2</tt> = Tuesday, <tt>3</tt> = Wednesday, <tt>4</tt> =
* Thursday, <tt>5</tt> = Friday, <tt>6</tt> = Saturday)
* represents the day of the week that contains or begins with
* the instant in time represented by this <tt>Date</tt> object,
* as interpreted in the local time zone.
*
* @return the day of the week represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.DAY_OF_WEEK)</code>.
*/
@Deprecated
public int getDay() {
return normalize().getDayOfWeek() - gcal.SUNDAY;
}
/**
* Returns the hour represented by this <tt>Date</tt> object. The
* returned value is a number (<tt>0</tt> through <tt>23</tt>)
* representing the hour within the day that contains or begins
* with the instant in time represented by this <tt>Date</tt>
* object, as interpreted in the local time zone.
*
* @return the hour represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.HOUR_OF_DAY)</code>.
*/
@Deprecated
public int getHours() {
return normalize().getHours();
}
/**
* Sets the hour of this <tt>Date</tt> object to the specified value.
* This <tt>Date</tt> object is modified so that it represents a point
* in time within the specified hour of the day, with the year, month,
* date, minute, and second the same as before, as interpreted in the
* local time zone.
*
* @param hours the hour value.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.HOUR_OF_DAY, int hours)</code>.
*/
@Deprecated
public void setHours(int hours) {
getCalendarDate().setHours(hours);
}
/**
* Returns the number of minutes past the hour represented by this date,
* as interpreted in the local time zone.
* The value returned is between <code>0</code> and <code>59</code>.
*
* @return the number of minutes past the hour represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.MINUTE)</code>.
*/
@Deprecated
public int getMinutes() {
return normalize().getMinutes();
}
/**
* Sets the minutes of this <tt>Date</tt> object to the specified value.
* This <tt>Date</tt> object is modified so that it represents a point
* in time within the specified minute of the hour, with the year, month,
* date, hour, and second the same as before, as interpreted in the
* local time zone.
*
* @param minutes the value of the minutes.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.MINUTE, int minutes)</code>.
*/
@Deprecated
public void setMinutes(int minutes) {
getCalendarDate().setMinutes(minutes);
}
/**
* Returns the number of seconds past the minute represented by this date.
* The value returned is between <code>0</code> and <code>61</code>. The
* values <code>60</code> and <code>61</code> can only occur on those
* Java Virtual Machines that take leap seconds into account.
*
* @return the number of seconds past the minute represented by this date.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.get(Calendar.SECOND)</code>.
*/
@Deprecated
public int getSeconds() {
return normalize().getSeconds();
}
/**
* Sets the seconds of this <tt>Date</tt> to the specified value.
* This <tt>Date</tt> object is modified so that it represents a
* point in time within the specified second of the minute, with
* the year, month, date, hour, and minute the same as before, as
* interpreted in the local time zone.
*
* @param seconds the seconds value.
* @see java.util.Calendar
* @deprecated As of JDK version 1.1,
* replaced by <code>Calendar.set(Calendar.SECOND, int seconds)</code>.
*/
@Deprecated
public void setSeconds(int seconds) {
getCalendarDate().setSeconds(seconds);
}
/**
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
public long getTime() {
return getTimeImpl();
}
private final long getTimeImpl() {
if (cdate != null && !cdate.isNormalized()) {
normalize();
}
return fastTime;
}
/**
* Sets this <code>Date</code> object to represent a point in time that is
* <code>time</code> milliseconds after January 1, 1970 00:00:00 GMT.
*
* @param time the number of milliseconds.
*/
public void setTime(long time) {
fastTime = time;
cdate = null;
}
/**
* Tests if this date is before the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant of time
* represented by this <tt>Date</tt> object is strictly
* earlier than the instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean before(Date when) {
return getMillisOf(this) < getMillisOf(when);
}
/**
* Tests if this date is after the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant represented
* by this <tt>Date</tt> object is strictly later than the
* instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
/**
* Compares two dates for equality.
* The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a <code>Date</code> object that
* represents the same point in time, to the millisecond, as this object.
* <p>
* Thus, two <code>Date</code> objects are equal if and only if the
* <code>getTime</code> method returns the same <code>long</code>
* value for both.
*
* @param obj the object to compare with.
* @return <code>true</code> if the objects are the same;
* <code>false</code> otherwise.
* @see java.util.Date#getTime()
*/
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
/**
* Returns the millisecond value of this <code>Date</code> object
* without affecting its internal state.
*/
static final long getMillisOf(Date date) {
if (date.cdate == null || date.cdate.isNormalized()) {
return date.fastTime;
}
BaseCalendar.Date d = (BaseCalendar.Date) date.cdate.clone();
return gcal.getTime(d);
}
/**
* Compares two Dates for ordering.
*
* @param anotherDate the <code>Date</code> to be compared.
* @return the value <code>0</code> if the argument Date is equal to
* this Date; a value less than <code>0</code> if this Date
* is before the Date argument; and a value greater than
* <code>0</code> if this Date is after the Date argument.
* @since 1.2
* @exception NullPointerException if <code>anotherDate</code> is null.
*/
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
/**
* Returns a hash code value for this object. The result is the
* exclusive OR of the two halves of the primitive <tt>long</tt>
* value returned by the {@link Date#getTime}
* method. That is, the hash code is the value of the expression:
* <blockquote><pre>
* (int)(this.getTime()^(this.getTime() >>> 32))</pre></blockquote>
*
* @return a hash code value for this object.
*/
public int hashCode() {
long ht = this.getTime();
return (int) ht ^ (int) (ht >> 32);
}
/**
* Converts this <code>Date</code> object to a <code>String</code>
* of the form:
* <blockquote><pre>
* dow mon dd hh:mm:ss zzz yyyy</pre></blockquote>
* where:<ul>
* <li><tt>dow</tt> is the day of the week (<tt>Sun, Mon, Tue, Wed,
* Thu, Fri, Sat</tt>).
* <li><tt>mon</tt> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun,
* Jul, Aug, Sep, Oct, Nov, Dec</tt>).
* <li><tt>dd</tt> is the day of the month (<tt>01</tt> through
* <tt>31</tt>), as two decimal digits.
* <li><tt>hh</tt> is the hour of the day (<tt>00</tt> through
* <tt>23</tt>), as two decimal digits.
* <li><tt>mm</tt> is the minute within the hour (<tt>00</tt> through
* <tt>59</tt>), as two decimal digits.
* <li><tt>ss</tt> is the second within the minute (<tt>00</tt> through
* <tt>61</tt>, as two decimal digits.
* <li><tt>zzz</tt> is the time zone (and may reflect daylight saving
* time). Standard time zone abbreviations include those
* recognized by the method <tt>parse</tt>. If time zone
* information is not available, then <tt>zzz</tt> is empty -
* that is, it consists of no characters at all.
* <li><tt>yyyy</tt> is the year, as four decimal digits.
* </ul>
*
* @return a string representation of this date.
* @see java.util.Date#toLocaleString()
* @see java.util.Date#toGMTString()
*/
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
/**
* Converts the given name to its 3-letter abbreviation (e.g.,
* "monday" -> "Mon") and stored the abbreviation in the given
* <code>StringBuilder</code>.
*/
private static final StringBuilder convertToAbbr(StringBuilder sb, String name) {
sb.append(Character.toUpperCase(name.charAt(0)));
sb.append(name.charAt(1)).append(name.charAt(2));
return sb;
}
/**
* Creates a string representation of this <tt>Date</tt> object in an
* implementation-dependent form. The intent is that the form should
* be familiar to the user of the Java application, wherever it may
* happen to be running. The intent is comparable to that of the
* "<code>%c</code>" format supported by the <code>strftime()</code>
* function of ISO C.
*
* @return a string representation of this date, using the locale
* conventions.
* @see java.text.DateFormat
* @see java.util.Date#toString()
* @see java.util.Date#toGMTString()
* @deprecated As of JDK version 1.1,
* replaced by <code>DateFormat.format(Date date)</code>.
*/
@Deprecated
public String toLocaleString() {
DateFormat formatter = DateFormat.getDateTimeInstance();
return formatter.format(this);
}
/**
* Creates a string representation of this <tt>Date</tt> object of
* the form:
* <blockquote<pre>
* d mon yyyy hh:mm:ss GMT</pre></blockquote>
* where:<ul>
* <li><i>d</i> is the day of the month (<tt>1</tt> through <tt>31</tt>),
* as one or two decimal digits.
* <li><i>mon</i> is the month (<tt>Jan, Feb, Mar, Apr, May, Jun, Jul,
* Aug, Sep, Oct, Nov, Dec</tt>).
* <li><i>yyyy</i> is the year, as four decimal digits.
* <li><i>hh</i> is the hour of the day (<tt>00</tt> through <tt>23</tt>),
* as two decimal digits.
* <li><i>mm</i> is the minute within the hour (<tt>00</tt> through
* <tt>59</tt>), as two decimal digits.
* <li><i>ss</i> is the second within the minute (<tt>00</tt> through
* <tt>61</tt>), as two decimal digits.
* <li><i>GMT</i> is exactly the ASCII letters "<tt>GMT</tt>" to indicate
* Greenwich Mean Time.
* </ul><p>
* The result does not depend on the local time zone.
*
* @return a string representation of this date, using the Internet GMT
* conventions.
* @see java.text.DateFormat
* @see java.util.Date#toString()
* @see java.util.Date#toLocaleString()
* @deprecated As of JDK version 1.1,
* replaced by <code>DateFormat.format(Date date)</code>, using a
* GMT <code>TimeZone</code>.
*/
@Deprecated
public String toGMTString() {
// d MMM yyyy HH:mm:ss 'GMT'
long t = getTime();
BaseCalendar cal = getCalendarSystem(t);
BaseCalendar.Date date =
(BaseCalendar.Date) cal.getCalendarDate(getTime(), (TimeZone)null);
StringBuilder sb = new StringBuilder(32);
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 1).append(' '); // d
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
sb.append(date.getYear()).append(' '); // yyyy
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2); // ss
sb.append(" GMT"); // ' GMT'
return sb.toString();
}
/**
* Returns the offset, measured in minutes, for the local time zone
* relative to UTC that is appropriate for the time represented by
* this <code>Date</code> object.
* <p>
* For example, in Massachusetts, five time zones west of Greenwich:
* <blockquote><pre>
* new Date(96, 1, 14).getTimezoneOffset() returns 300</pre></blockquote>
* because on February 14, 1996, standard time (Eastern Standard Time)
* is in use, which is offset five hours from UTC; but:
* <blockquote><pre>
* new Date(96, 5, 1).getTimezoneOffset() returns 240</pre></blockquote>
* because on June 1, 1996, daylight saving time (Eastern Daylight Time)
* is in use, which is offset only four hours from UTC.<p>
* This method produces the same result as if it computed:
* <blockquote><pre>
* (this.getTime() - UTC(this.getYear(),
* this.getMonth(),
* this.getDate(),
* this.getHours(),
* this.getMinutes(),
* this.getSeconds())) / (60 * 1000)
* </pre></blockquote>
*
* @return the time-zone offset, in minutes, for the current time zone.
* @see java.util.Calendar#ZONE_OFFSET
* @see java.util.Calendar#DST_OFFSET
* @see java.util.TimeZone#getDefault
* @deprecated As of JDK version 1.1,
* replaced by <code>-(Calendar.get(Calendar.ZONE_OFFSET) +
* Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)</code>.
*/
@Deprecated
public int getTimezoneOffset() {
int zoneOffset;
if (cdate == null) {
GregorianCalendar cal = new GregorianCalendar(fastTime);
zoneOffset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET));
} else {
normalize();
zoneOffset = cdate.getZoneOffset();
}
return -zoneOffset/60000; // convert to minutes
}
private final BaseCalendar.Date getCalendarDate() {
if (cdate == null) {
BaseCalendar cal = getCalendarSystem(fastTime);
cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime,
TimeZone.getDefaultRef());
}
return cdate;
}
private final BaseCalendar.Date normalize() {
if (cdate == null) {
BaseCalendar cal = getCalendarSystem(fastTime);
cdate = (BaseCalendar.Date) cal.getCalendarDate(fastTime,
TimeZone.getDefaultRef());
return cdate;
}
// Normalize cdate with the TimeZone in cdate first. This is
// required for the compatible behavior.
if (!cdate.isNormalized()) {
cdate = normalize(cdate);
}
// If the default TimeZone has changed, then recalculate the
// fields with the new TimeZone.
TimeZone tz = TimeZone.getDefaultRef();
if (tz != cdate.getZone()) {
cdate.setZone(tz);
CalendarSystem cal = getCalendarSystem(cdate);
cal.getCalendarDate(fastTime, cdate);
}
return cdate;
}
// fastTime and the returned data are in sync upon return.
private final BaseCalendar.Date normalize(BaseCalendar.Date date) {
int y = date.getNormalizedYear();
int m = date.getMonth();
int d = date.getDayOfMonth();
int hh = date.getHours();
int mm = date.getMinutes();
int ss = date.getSeconds();
int ms = date.getMillis();
TimeZone tz = date.getZone();
// If the specified year can't be handled using a long value
// in milliseconds, GregorianCalendar is used for full
// compatibility with underflow and overflow. This is required
// by some JCK tests. The limits are based max year values -
// years that can be represented by max values of d, hh, mm,
// ss and ms. Also, let GregorianCalendar handle the default
// cutover year so that we don't need to worry about the
// transition here.
if (y == 1582 || y > 280000000 || y < -280000000) {
if (tz == null) {
tz = TimeZone.getTimeZone("GMT");
}
GregorianCalendar gc = new GregorianCalendar(tz);
gc.clear();
gc.set(gc.MILLISECOND, ms);
gc.set(y, m-1, d, hh, mm, ss);
fastTime = gc.getTimeInMillis();
BaseCalendar cal = getCalendarSystem(fastTime);
date = (BaseCalendar.Date) cal.getCalendarDate(fastTime, tz);
return date;
}
BaseCalendar cal = getCalendarSystem(y);
if (cal != getCalendarSystem(date)) {
date = (BaseCalendar.Date) cal.newCalendarDate(tz);
date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms);
}
// Perform the GregorianCalendar-style normalization.
fastTime = cal.getTime(date);
// In case the normalized date requires the other calendar
// system, we need to recalculate it using the other one.
BaseCalendar ncal = getCalendarSystem(fastTime);
if (ncal != cal) {
date = (BaseCalendar.Date) ncal.newCalendarDate(tz);
date.setNormalizedDate(y, m, d).setTimeOfDay(hh, mm, ss, ms);
fastTime = ncal.getTime(date);
}
return date;
}
/**
* Returns the Gregorian or Julian calendar system to use with the
* given date. Use Gregorian from October 15, 1582.
*
* @param year normalized calendar year (not -1900)
* @return the CalendarSystem to use for the specified date
*/
private static final BaseCalendar getCalendarSystem(int year) {
if (year >= 1582) {
return gcal;
}
return getJulianCalendar();
}
private static final BaseCalendar getCalendarSystem(long utc) {
// Quickly check if the time stamp given by `utc' is the Epoch
// or later. If it's before 1970, we convert the cutover to
// local time to compare.
if (utc >= 0
|| utc >= GregorianCalendar.DEFAULT_GREGORIAN_CUTOVER
- TimeZone.getDefaultRef().getOffset(utc)) {
return gcal;
}
return getJulianCalendar();
}
private static final BaseCalendar getCalendarSystem(BaseCalendar.Date cdate) {
if (jcal == null) {
return gcal;
}
if (cdate.getEra() != null) {
return jcal;
}
return gcal;
}
synchronized private static final BaseCalendar getJulianCalendar() {
if (jcal == null) {
jcal = (BaseCalendar) CalendarSystem.forName("julian");
}
return jcal;
}
/**
* Save the state of this object to a stream (i.e., serialize it).
*
* @serialData The value returned by <code>getTime()</code>
* is emitted (long). This represents the offset from
* January 1, 1970, 00:00:00 GMT in milliseconds.
*/
private void writeObject(ObjectOutputStream s)
throws IOException
{
s.writeLong(getTimeImpl());
}
/**
* Reconstitute this object from a stream (i.e., deserialize it).
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
fastTime = s.readLong();
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/vm/tests/kernel/java/lang/ClassLoaderTestLoad.java | 1316 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgueni V. Brevnov, Roman S. Bushmanov
*/
package java.lang;
import junit.framework.TestCase;
public class ClassLoaderTestLoad extends TestCase {
public void test1() {
try {
for (int i = 0; i < 100; i++) {
ClassLoader.getSystemClassLoader()
.loadClass("java.lang.Object", true);
}
} catch (ClassNotFoundException e) {
fail(e.toString());
}
}
} | gpl-2.0 |
Irishsmurf/Rmi-Assignment | src/UI/Clinic/CancelAppointment.java | 1882 |
package Clinic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for cancelAppointment complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="cancelAppointment">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="arg0" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="arg1" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="arg2" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "cancelAppointment", propOrder = {
"arg0",
"arg1",
"arg2"
})
public class CancelAppointment {
protected int arg0;
protected int arg1;
protected int arg2;
/**
* Gets the value of the arg0 property.
*
*/
public int getArg0() {
return arg0;
}
/**
* Sets the value of the arg0 property.
*
*/
public void setArg0(int value) {
this.arg0 = value;
}
/**
* Gets the value of the arg1 property.
*
*/
public int getArg1() {
return arg1;
}
/**
* Sets the value of the arg1 property.
*
*/
public void setArg1(int value) {
this.arg1 = value;
}
/**
* Gets the value of the arg2 property.
*
*/
public int getArg2() {
return arg2;
}
/**
* Sets the value of the arg2 property.
*
*/
public void setArg2(int value) {
this.arg2 = value;
}
}
| gpl-2.0 |
SpoonLabs/astor | examples/math_63/src/main/java/org/apache/commons/math/stat/descriptive/summary/Product.java | 7420 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.stat.descriptive.summary;
import java.io.Serializable;
import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic;
import org.apache.commons.math.stat.descriptive.WeightedEvaluation;
import org.apache.commons.math.util.FastMath;
/**
* Returns the product of the available values.
* <p>
* If there are no values in the dataset, or any of the values are
* <code>NaN</code>, then <code>NaN</code> is returned.</p>
* <p>
* <strong>Note that this implementation is not synchronized.</strong> If
* multiple threads access an instance of this class concurrently, and at least
* one of the threads invokes the <code>increment()</code> or
* <code>clear()</code> method, it must be synchronized externally.</p>
*
* @version $Revision$ $Date$
*/
public class Product extends AbstractStorelessUnivariateStatistic implements Serializable, WeightedEvaluation {
/** Serializable version identifier */
private static final long serialVersionUID = 2824226005990582538L;
/**The number of values that have been added */
private long n;
/**
* The current Running Product.
*/
private double value;
/**
* Create a Product instance
*/
public Product() {
n = 0;
value = Double.NaN;
}
/**
* Copy constructor, creates a new {@code Product} identical
* to the {@code original}
*
* @param original the {@code Product} instance to copy
*/
public Product(Product original) {
copy(original, this);
}
/**
* {@inheritDoc}
*/
@Override
public void increment(final double d) {
if (n == 0) {
value = d;
} else {
value *= d;
}
n++;
}
/**
* {@inheritDoc}
*/
@Override
public double getResult() {
return value;
}
/**
* {@inheritDoc}
*/
public long getN() {
return n;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
value = Double.NaN;
n = 0;
}
/**
* Returns the product of the entries in the specified portion of
* the input array, or <code>Double.NaN</code> if the designated subarray
* is empty.
* <p>
* Throws <code>IllegalArgumentException</code> if the array is null.</p>
*
* @param values the input array
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the product of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the array is null or the array index
* parameters are not valid
*/
@Override
public double evaluate(final double[] values, final int begin, final int length) {
double product = Double.NaN;
if (test(values, begin, length)) {
product = 1.0;
for (int i = begin; i < begin + length; i++) {
product *= values[i];
}
}
return product;
}
/**
* <p>Returns the weighted product of the entries in the specified portion of
* the input array, or <code>Double.NaN</code> if the designated subarray
* is empty.</p>
*
* <p>Throws <code>IllegalArgumentException</code> if any of the following are true:
* <ul><li>the values array is null</li>
* <li>the weights array is null</li>
* <li>the weights array does not have the same length as the values array</li>
* <li>the weights array contains one or more infinite values</li>
* <li>the weights array contains one or more NaN values</li>
* <li>the weights array contains negative values</li>
* <li>the start and length arguments do not determine a valid array</li>
* </ul></p>
*
* <p>Uses the formula, <pre>
* weighted product = ∏values[i]<sup>weights[i]</sup>
* </pre>
* that is, the weights are applied as exponents when computing the weighted product.</p>
*
* @param values the input array
* @param weights the weights array
* @param begin index of the first array element to include
* @param length the number of elements to include
* @return the product of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the parameters are not valid
* @since 2.1
*/
public double evaluate(final double[] values, final double[] weights,
final int begin, final int length) {
double product = Double.NaN;
if (test(values, weights, begin, length)) {
product = 1.0;
for (int i = begin; i < begin + length; i++) {
product *= FastMath.pow(values[i], weights[i]);
}
}
return product;
}
/**
* <p>Returns the weighted product of the entries in the input array.</p>
*
* <p>Throws <code>IllegalArgumentException</code> if any of the following are true:
* <ul><li>the values array is null</li>
* <li>the weights array is null</li>
* <li>the weights array does not have the same length as the values array</li>
* <li>the weights array contains one or more infinite values</li>
* <li>the weights array contains one or more NaN values</li>
* <li>the weights array contains negative values</li>
* </ul></p>
*
* <p>Uses the formula, <pre>
* weighted product = ∏values[i]<sup>weights[i]</sup>
* </pre>
* that is, the weights are applied as exponents when computing the weighted product.</p>
*
* @param values the input array
* @param weights the weights array
* @return the product of the values or Double.NaN if length = 0
* @throws IllegalArgumentException if the parameters are not valid
* @since 2.1
*/
public double evaluate(final double[] values, final double[] weights) {
return evaluate(values, weights, 0, values.length);
}
/**
* {@inheritDoc}
*/
@Override
public Product copy() {
Product result = new Product();
copy(this, result);
return result;
}
/**
* Copies source to dest.
* <p>Neither source nor dest can be null.</p>
*
* @param source Product to copy
* @param dest Product to copy to
* @throws NullPointerException if either source or dest is null
*/
public static void copy(Product source, Product dest) {
dest.n = source.n;
dest.value = source.value;
}
}
| gpl-2.0 |
vincent-wen/ams | src/main/java/ca/ams/models/GPDRepository.java | 87 | package ca.ams.models;
public interface GPDRepository extends UserRepository<GPD>{
}
| gpl-2.0 |
chdoig/ache | src/main/java/focusedCrawler/link/classifier/builder/wrapper/ParserLink.java | 3978 | /*
############################################################################
##
## Copyright (C) 2006-2009 University of Utah. All rights reserved.
##
## This file is part of DeepPeep.
##
## This file may be used under the terms of the GNU General Public
## License version 2.0 as published by the Free Software Foundation
## and appearing in the file LICENSE.GPL included in the packaging of
## this file. Please review the following to ensure GNU General Public
## Licensing requirements will be met:
## http://www.opensource.org/licenses/gpl-license.php
##
## If you are unsure which license is appropriate for your use (for
## instance, you are interested in developing a commercial derivative
## of DeepPeep), please contact us at deeppeep@sci.utah.edu.
##
## This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
## WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
##
############################################################################
*/
package focusedCrawler.link.classifier.builder.wrapper;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import focusedCrawler.util.Page;
/**
* <p>Title: </p>
* <p/>
* <p>Description: This class gets words related to links: url, anchor and around</p>
* <p/>
* <p>Copyright: Copyright (c) 2004</p>
* <p/>
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class ParserLink {
private HashMap map;
public ParserLink() {
map = new HashMap();
}
public void extractLinks(Page page, String[] features) throws IOException,
SAXException {
String content = page.getContent();
DOMParser parser = new DOMParser();
parser.parse(new InputSource(new BufferedReader(new StringReader(content))));
Document doc = parser.getDocument();
}
public void extract(String file) throws IOException, SAXException {
DOMParser parser = new DOMParser();
parser.parse(file);
Document doc = parser.getDocument();
parse(doc);
Vector words = new Vector();
NodeList list = doc.getElementsByTagName("a");
for (int i = 0; i < list.getLength(); i++) {
parse(list.item(i));
}
}
public void parse(Node node) {
NamedNodeMap attrs = node.getAttributes();
String nodeName = node.getNodeName();
String textBefore = "";
String url = "";
if (Node.TEXT_NODE == node.getNodeType()) {
textBefore = node.getNodeValue().trim();
}
// if(nodeName.equals("A")){
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
Node attr = attrs.item(i);
String attrName = ((attr.getNodeName().trim()).toLowerCase());
String attrValue = ((attr.getNodeValue().trim()).toLowerCase());
if (attrName.equals("href")) {
url = attrValue;
}
System.out.println("TEST");
}
}
// }
NodeList children = node.getChildNodes();
if (children != null) {
int len = children.getLength();
for (int i = 0; i < len; i++) {
parse(children.item(i));
}
}
}
public static void main(String[] args) {
ParserLink parserlink = new ParserLink();
try {
parserlink.extract(args[0]);
} catch (SAXException ex) {
} catch (IOException ex) {
}
}
}
| gpl-2.0 |
king19860907/disconf | disconf-web/src/main/java/com/baidu/disconf/web/service/user/service/impl/UserMgrImpl.java | 2210 | package com.baidu.disconf.web.service.user.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.baidu.disconf.web.service.user.bo.User;
import com.baidu.disconf.web.service.user.dao.UserDao;
import com.baidu.disconf.web.service.user.dto.Visitor;
import com.baidu.disconf.web.service.user.service.UserInnerMgr;
import com.baidu.disconf.web.service.user.service.UserMgr;
import com.baidu.disconf.web.service.user.vo.VisitorVo;
import com.baidu.ub.common.commons.ThreadContext;
/**
* @author liaoqiqi
* @version 2013-12-5
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserMgrImpl implements UserMgr {
protected static final Logger LOG = LoggerFactory.getLogger(UserMgrImpl.class);
@Autowired
private UserInnerMgr userInnerMgr;
@Autowired
private UserDao userDao;
@Override
public Visitor getVisitor(Long userId) {
return userInnerMgr.getVisitor(userId);
}
@Override
public VisitorVo getCurVisitor() {
Visitor visitor = ThreadContext.getSessionVisitor();
if (visitor == null) {
return null;
}
VisitorVo visitorVo = new VisitorVo();
visitorVo.setId(visitor.getId());
visitorVo.setName(visitor.getLoginUserName());
return visitorVo;
}
/**
* 创建
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public Long create(User user) {
user = userDao.create(user);
return user.getId();
}
/**
*
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void create(List<User> users) {
userDao.create(users);
}
@Override
public List<User> getAll() {
return userDao.findAll();
}
@Override
public User getUser(Long userId) {
return userDao.get(userId);
}
}
| gpl-2.0 |
samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/tools/internal/ws/Invoker.java | 9487 | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.internal.ws;
import com.sun.istack.internal.tools.MaskingClassLoader;
import com.sun.istack.internal.tools.ParallelWorldClassLoader;
import com.sun.tools.internal.ws.resources.WscompileMessages;
import com.sun.tools.internal.xjc.api.util.ToolsJarNotFoundException;
import com.sun.xml.internal.bind.util.Which;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceFeature;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Invokes JAX-WS tools in a special class loader that can pick up APT classes,
* even if it's not available in the tool launcher classpath.
*
* @author Kohsuke Kawaguchi
*/
public final class Invoker {
static int invoke(String mainClass, String[] args) throws Throwable {
// use the platform default proxy if available.
// see sun.net.spi.DefaultProxySelector for details.
if(!noSystemProxies) {
try {
System.setProperty("java.net.useSystemProxies","true");
} catch (SecurityException e) {
// failing to set this property isn't fatal
}
}
ClassLoader oldcc = Thread.currentThread().getContextClassLoader();
try {
ClassLoader cl = Invoker.class.getClassLoader();
if(Arrays.asList(args).contains("-Xendorsed"))
cl = createClassLoader(cl); // perform JDK6 workaround hack
else {
if(!checkIfLoading21API()) {
if(Service.class.getClassLoader()==null)
System.err.println(WscompileMessages.INVOKER_NEED_ENDORSED());
else
System.err.println(WscompileMessages.WRAPPER_TASK_LOADING_20_API(Which.which(Service.class)));
return -1;
}
//find and load tools.jar
List<URL> urls = new ArrayList<URL>();
findToolsJar(cl, urls);
if(urls.size() > 0){
List<String> mask = new ArrayList<String>(Arrays.asList(maskedPackages));
// first create a protected area so that we load JAXB/WS 2.1 API
// and everything that depends on them inside
cl = new MaskingClassLoader(cl,mask);
// then this classloader loads the API and tools.jar
cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), cl);
// finally load the rest of the RI. The actual class files are loaded from ancestors
cl = new ParallelWorldClassLoader(cl,"");
}
}
Thread.currentThread().setContextClassLoader(cl);
Class compileTool = cl.loadClass(mainClass);
Constructor ctor = compileTool.getConstructor(OutputStream.class);
Object tool = ctor.newInstance(System.out);
Method runMethod = compileTool.getMethod("run",String[].class);
boolean r = (Boolean)runMethod.invoke(tool,new Object[]{args});
return r ? 0 : 1;
} catch (ToolsJarNotFoundException e) {
System.err.println(e.getMessage());
} catch (InvocationTargetException e) {
throw e.getCause();
} catch(ClassNotFoundException e){
throw e;
}finally {
Thread.currentThread().setContextClassLoader(oldcc);
}
return -1;
}
/**
* Returns true if the RI appears to be loading the JAX-WS 2.1 API.
*/
public static boolean checkIfLoading21API() {
try {
Service.class.getMethod("getPort",Class.class, WebServiceFeature[].class);
// yup. things look good.
return true;
} catch (NoSuchMethodException e) {
} catch (LinkageError e) {
}
// nope
return false;
}
/**
* Creates a classloader that can load JAXB/WS 2.1 API and tools.jar,
* and then return a classloader that can RI classes, which can see all those APIs and tools.jar.
*/
public static ClassLoader createClassLoader(ClassLoader cl) throws ClassNotFoundException, MalformedURLException, ToolsJarNotFoundException {
URL[] urls = findIstackAPIs(cl);
if(urls.length==0)
return cl; // we seem to be able to load everything already. no need for the hack
List<String> mask = new ArrayList<String>(Arrays.asList(maskedPackages));
if(urls.length>1) {
// we need to load 2.1 API from side. so add them to the mask
mask.add("javax.xml.bind.");
mask.add("javax.xml.ws.");
}
// first create a protected area so that we load JAXB/WS 2.1 API
// and everything that depends on them inside
cl = new MaskingClassLoader(cl,mask);
// then this classloader loads the API and tools.jar
cl = new URLClassLoader(urls, cl);
// finally load the rest of the RI. The actual class files are loaded from ancestors
cl = new ParallelWorldClassLoader(cl,"");
return cl;
}
/**
* Creates a classloader for loading JAXB/WS 2.1 jar and tools.jar
*/
private static URL[] findIstackAPIs(ClassLoader cl) throws ClassNotFoundException, MalformedURLException, ToolsJarNotFoundException {
List<URL> urls = new ArrayList<URL>();
if(Service.class.getClassLoader()==null) {
// JAX-WS API is loaded from bootstrap classloader
URL res = cl.getResource("javax/xml/ws/EndpointReference.class");
if(res==null)
throw new ClassNotFoundException("There's no JAX-WS 2.1 API in the classpath");
urls.add(ParallelWorldClassLoader.toJarUrl(res));
res = cl.getResource("javax/xml/bind/annotation/XmlSeeAlso.class");
if(res==null)
throw new ClassNotFoundException("There's no JAXB 2.1 API in the classpath");
urls.add(ParallelWorldClassLoader.toJarUrl(res));
}
findToolsJar(cl, urls);
return urls.toArray(new URL[urls.size()]);
}
private static void findToolsJar(ClassLoader cl, List<URL> urls) throws ToolsJarNotFoundException, MalformedURLException {
try {
Class.forName("com.sun.tools.javac.Main",false,cl);
Class.forName("com.sun.tools.apt.Main",false,cl);
// we can already load them in the parent class loader.
// so no need to look for tools.jar.
// this happens when we are run inside IDE/Ant, or
// in Mac OS.
} catch (ClassNotFoundException e) {
// otherwise try to find tools.jar
File jreHome = new File(System.getProperty("java.home"));
File toolsJar = new File( jreHome.getParent(), "lib/tools.jar" );
if (!toolsJar.exists()) {
throw new ToolsJarNotFoundException(toolsJar);
}
urls.add(toolsJar.toURL());
}
}
/**
* The list of package prefixes we want the
* {@link MaskingClassLoader} to prevent the parent
* classLoader from loading
*/
public static String[] maskedPackages = new String[]{
"com.sun.istack.internal.tools.",
"com.sun.tools.internal.jxc.",
"com.sun.tools.internal.xjc.",
"com.sun.tools.internal.ws.",
"com.sun.codemodel.internal.",
"com.sun.relaxng.",
"com.sun.xml.internal.xsom.",
"com.sun.xml.internal.bind.",
"com.sun.xml.internal.ws."
};
/**
* Escape hatch to work around IBM JDK problem.
* See http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?nav=false&forum=367&thread=164718&cat=10
*/
public static boolean noSystemProxies = false;
static {
try {
noSystemProxies = Boolean.getBoolean(Invoker.class.getName()+".noSystemProxies");
} catch(SecurityException e) {
// ignore
}
}
}
| gpl-2.0 |
codenameone/CodenameOne | Samples/samples/AutocompleteInTabsTest/AutocompleteInTabsTest.java | 2945 | package com.codename1.samples;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
import com.codename1.ui.AutoCompleteTextField;
import com.codename1.ui.Container;
import com.codename1.ui.Tabs;
import com.codename1.ui.layouts.BorderLayout;
/**
* This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose
* of building native mobile applications using Java.
*/
public class AutocompleteInTabsTest {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
Tabs tabs = new Tabs();
Container tabsContainer1 = new Container(new BorderLayout());
Container tabsContainer2 = new Container(new BorderLayout());
Form hi = new Form("Popup test");
AutoCompleteTextField autocompleteTab1 = new
AutoCompleteTextField("1", "2", "3", "11", "22", "33");
//autocompleteTab1.setMinimumLength(1);
AutoCompleteTextField autocompleteTab2 = new
AutoCompleteTextField("1", "2", "3", "4", "11", "22", "33", "44");
autocompleteTab2.setMinimumLength(1);
// pop up appears to be
//drawn semi off screen and
// see attached screenshot in email
tabsContainer1.add(BorderLayout.CENTER, autocompleteTab1);
tabs.addTab("working tab", tabsContainer1);
tabsContainer2.add(BorderLayout.CENTER, autocompleteTab2);
tabs.addTab("failing tab", tabsContainer2);
hi.add(tabs);
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
| gpl-2.0 |
oscarservice/oscar-old | src/main/java/oscar/oscarRx/dao/RxCloneFavoritesDAO.java | 1662 | /**
* Copyright (c) 2006-. OSCARservice, OpenSoft System. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package oscar.oscarRx.dao;
import java.util.List;
import oscar.oscarRx.model.Favorites;
import oscar.oscarRx.model.Favoritesprivilege;
/**
*
* @author toby
*/
public interface RxCloneFavoritesDAO {
public List<Favorites> getFavoritesFromProvider(String providerNo);
public List<Favorites> getFavoritesFromIDs(List<Integer> list);
public void setFavoritesForProvider(String providerNo, List<Favorites> list);
public List<String> getProviders();
public void setFavoritesPrivilege(String providerNo,boolean openpublic, boolean writeable);
public Favoritesprivilege getFavoritesPrivilege(String providerNo);
public String getProviderName(String providerNo);
}
| gpl-2.0 |
aeng/zanata-helper | server/src/main/java/org/zanata/sync/controller/ZanataSignIn.java | 3505 | package org.zanata.sync.controller;
import java.io.IOException;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import org.apache.deltaspike.core.api.common.DeltaSpike;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import lombok.Getter;
import lombok.Setter;
/**
* @author Patrick Huang <a href="mailto:pahuang@redhat.com">pahuang@redhat.com</a>
*/
@RequestScoped
@Named("zanataSignIn")
public class ZanataSignIn {
private static final Logger log =
LoggerFactory.getLogger(ZanataSignIn.class);
@Inject
@DeltaSpike
private HttpServletRequest request;
@Getter
@Setter
private String url;
private String errorMessage;
@Setter
@Getter
private String originalRequest;
@Getter
private List<String> productionServerUrls = ImmutableList.<String>builder()
.add("http://localhost:8080/zanata")
.add("https://translate.zanata.org")
.add("https://translate.jboss.org")
.add("https://fedora.zanata.org")
.build();
@Setter
@Getter
private String selectedUrl;
public boolean hasError() {
return errorMessage != null;
}
public String getErrorMessage() {
return errorMessage;
}
public void signIn() {
try {
FacesContext context = FacesContext.getCurrentInstance();
String zanataAuthUrl = generateOAuthURL();
if (hasError()) {
return;
}
OAuthClientRequest request = OAuthClientRequest
.authorizationLocation(zanataAuthUrl)
.setClientId("zanata_sync")
.setRedirectURI(appRoot() + "/auth/" + originalRequest)
.buildQueryMessage();
log.info("=========== redirecting to {}", request.getLocationUri());
context.getExternalContext().redirect(request.getLocationUri());
context.responseComplete();
} catch (IOException | OAuthSystemException e) {
errorMessage = e.getMessage();
}
}
private String generateOAuthURL() {
String zanataUrl = Strings.isNullOrEmpty(selectedUrl) ? url : selectedUrl;
if (Strings.isNullOrEmpty(zanataUrl)) {
errorMessage = "You must select one production server or enter your own Zanata URL";
return null;
}
String authorizeUri = "authorize/";
if (zanataUrl.endsWith("/")) {
return zanataUrl + authorizeUri;
} else {
return zanataUrl + "/" + authorizeUri;
}
}
private String appRoot() {
String contextPath = request.getContextPath();
contextPath =
Strings.isNullOrEmpty(contextPath) ? "" : "/" + contextPath;
String scheme = request.getScheme();
int serverPort = request.getServerPort();
String serverName = request.getServerName();
String port = serverPort == 80 ? "" : ":" + serverPort;
return scheme + "://" + serverName + port + contextPath;
}
}
| gpl-2.0 |
qinyuemin/OfferMe | OfferMe/OfferLinkTest/src/com/offerme/client/service/cv/CVList.java | 555 | package com.offerme.client.service.cv;
import java.util.ArrayList;
import java.util.List;
public class CVList {
private int responseCode = -1;
private List<PersonalCV> cvList;
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
public List<PersonalCV> getCVList() {
if (cvList == null) {
cvList = new ArrayList<PersonalCV>();
}
return cvList;
}
public void setCVList(List<PersonalCV> chatMessageList) {
this.cvList = chatMessageList;
}
}
| gpl-2.0 |
ntj/ComplexRapidMiner | src/com/rapidminer/operator/similarity/attributebased/OverlapNumericalSimilarity.java | 1705 | /*
* RapidMiner
*
* Copyright (C) 2001-2008 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.similarity.attributebased;
/**
* A variant of simple matching for numerical attributes.
*
* @author Michael Wurst
* @version $Id: OverlapNumericalSimilarity.java,v 1.5 2008/09/12 10:30:58 tobiasmalbrecht Exp $
*/
public class OverlapNumericalSimilarity extends AbstractRealValueBasedSimilarity {
private static final long serialVersionUID = -7971832501308873149L;
public double similarity(double[] e1, double[] e2) {
double wxy = 0.0;
double wx = 0.0;
double wy = 0.0;
for (int i = 0; i < e1.length; i++) {
if ((!Double.isNaN(e1[i])) && (!Double.isNaN(e2[i]))) {
wx = wx + e1[i];
wy = wy + e2[i];
wxy = wxy + Math.min(e1[i], e2[i]);
}
}
return wxy / Math.min(wx, wy);
}
public boolean isDistance() {
return false;
}
}
| gpl-2.0 |
mixaceh/openyu-socklet | openyu-socklet-core/src/main/java/org/openyu/socklet/message/vo/CategoryType.java | 3723 | package org.openyu.socklet.message.vo;
import org.openyu.commons.enumz.ByteEnum;
import org.openyu.commons.lang.ByteHelper;
/**
* 訊息種類類別
*/
public enum CategoryType implements ByteEnum {
/**
* 握手協定-tcp, client->server
*/
HANDSHAKE_CLIENT((byte) 1) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 握手協定-tcp, relation->server
*/
HANDSHAKE_RELATION((byte) 2) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 握手協定-tcp, server->client, server->relation
*/
HANDSHAKE_SERVER((byte) 3) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定-tcp, client->server
*/
MESSAGE_CLIENT((byte) 11) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定-tcp, server->relation, receive
*/
MESSAGE_RELATION((byte) 12) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定-tcp, server->client, server->server
*/
MESSAGE_SERVER((byte) 13) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定-tcp, client->server, server->server 不立即處理, 而是放到queue中, 類似mq
*/
MESSAGE_QUEUE((byte) 14) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定內部用-udp, server->relation,發送用
*
* 此為特別協定,只有在acceptor中使用,不開放外部使用
*/
MESSAGE_ACCEPTOR((byte) 15) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 訊息協定邏輯用-udp, server->relation,發送用
*/
MESSAGE_SYNC((byte) 16) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
*
*/
KEEP_ALIVE_CLIENT((byte) 31) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
*
*/
KEEP_ALIVE_RELATIOM((byte) 32) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
*
*/
KEEP_ALIVE_SERVER((byte) 33) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 檔案協定, tcp
*/
FILE_CLIENT((byte) 41) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 檔案協定, tcp
*/
FILE_RELATIOM((byte) 42) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
/**
* 檔案協定, tcp
*/
FILE_SERVER((byte) 43) {
public byte[] toByteArray() {
if (byteArray == null) {
byteArray = new byte[] { getValue() };
}
return byteArray;
}
},
;
private final byte value;
protected byte[] byteArray;
private CategoryType(byte value) {
this.value = value;
}
public byte getValue() {
return value;
}
public abstract byte[] toByteArray();
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | frameworks/opt/telephony/src/java/com/android/internal/telephony/DataCallState.java | 9262 | /*
* Copyright (C) 2009 Qualcomm Innovation Center, Inc. All Rights Reserved.
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.os.SystemProperties;
import android.util.Log;
import com.android.internal.telephony.DataConnection.FailCause;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* This is RIL_Data_Call_Response_v5 from ril.h
* TODO: Rename to DataCallResponse.
*/
public class DataCallState {
private final boolean DBG = true;
private final String LOG_TAG = "GSM";
public int version = 0;
public int status = 0;
public int cid = 0;
public int active = 0;
public String type = "";
public String ifname = "";
public String [] addresses = new String[0];
public String [] dnses = new String[0];
public String[] gateways = new String[0];
public int suggestedRetryTime = -1;
/**
* Class returned by onSetupConnectionCompleted.
*/
public enum SetupResult {
SUCCESS,
ERR_BadCommand,
ERR_UnacceptableParameter,
ERR_GetLastErrorFromRil,
ERR_Stale,
ERR_RilError;
public FailCause mFailCause;
SetupResult() {
mFailCause = FailCause.fromInt(0);
}
@Override
public String toString() {
return name() + " SetupResult.mFailCause=" + mFailCause;
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("DataCallState: {")
.append("version=").append(version)
.append(" status=").append(status)
.append(" retry=").append(suggestedRetryTime)
.append(" cid=").append(cid)
.append(" active=").append(active)
.append(" type=").append(type)
.append("' ifname='").append(ifname);
sb.append("' addresses=[");
for (String addr : addresses) {
sb.append(addr);
sb.append(",");
}
if (addresses.length > 0) sb.deleteCharAt(sb.length()-1);
sb.append("] dnses=[");
for (String addr : dnses) {
sb.append(addr);
sb.append(",");
}
if (dnses.length > 0) sb.deleteCharAt(sb.length()-1);
sb.append("] gateways=[");
for (String addr : gateways) {
sb.append(addr);
sb.append(",");
}
if (gateways.length > 0) sb.deleteCharAt(sb.length()-1);
sb.append("]}");
return sb.toString();
}
public SetupResult setLinkProperties(LinkProperties linkProperties,
boolean okToUseSystemPropertyDns) {
SetupResult result;
// Start with clean network properties and if we have
// a failure we'll clear again at the bottom of this code.
if (linkProperties == null)
linkProperties = new LinkProperties();
else
linkProperties.clear();
if (status == FailCause.NONE.getErrorCode()) {
String propertyPrefix = "net." + ifname + ".";
try {
// set interface name
linkProperties.setInterfaceName(ifname);
// set link addresses
if (addresses != null && addresses.length > 0) {
for (String addr : addresses) {
addr = addr.trim();
if (addr.isEmpty()) continue;
LinkAddress la;
int addrPrefixLen;
String [] ap = addr.split("/");
if (ap.length == 2) {
addr = ap[0];
addrPrefixLen = Integer.parseInt(ap[1]);
} else {
addrPrefixLen = 0;
}
InetAddress ia;
try {
ia = NetworkUtils.numericToInetAddress(addr);
} catch (IllegalArgumentException e) {
throw new UnknownHostException("Non-numeric ip addr=" + addr);
}
if (! ia.isAnyLocalAddress()) {
if (addrPrefixLen == 0) {
// Assume point to point
addrPrefixLen = (ia instanceof Inet4Address) ? 32 : 128;
}
if (DBG) Log.d(LOG_TAG, "addr/pl=" + addr + "/" + addrPrefixLen);
la = new LinkAddress(ia, addrPrefixLen);
linkProperties.addLinkAddress(la);
}
}
} else {
throw new UnknownHostException("no address for ifname=" + ifname);
}
// set dns servers
if (dnses != null && dnses.length > 0) {
for (String addr : dnses) {
addr = addr.trim();
if (addr.isEmpty()) continue;
InetAddress ia;
try {
ia = NetworkUtils.numericToInetAddress(addr);
} catch (IllegalArgumentException e) {
throw new UnknownHostException("Non-numeric dns addr=" + addr);
}
if (! ia.isAnyLocalAddress()) {
linkProperties.addDns(ia);
}
}
} else if (okToUseSystemPropertyDns){
String dnsServers[] = new String[2];
dnsServers[0] = SystemProperties.get(propertyPrefix + "dns1");
dnsServers[1] = SystemProperties.get(propertyPrefix + "dns2");
for (String dnsAddr : dnsServers) {
dnsAddr = dnsAddr.trim();
if (dnsAddr.isEmpty()) continue;
InetAddress ia;
try {
ia = NetworkUtils.numericToInetAddress(dnsAddr);
} catch (IllegalArgumentException e) {
throw new UnknownHostException("Non-numeric dns addr=" + dnsAddr);
}
if (! ia.isAnyLocalAddress()) {
linkProperties.addDns(ia);
}
}
} else {
throw new UnknownHostException("Empty dns response and no system default dns");
}
// set gateways
if ((gateways == null) || (gateways.length == 0)) {
String sysGateways = SystemProperties.get(propertyPrefix + "gw");
if (sysGateways != null) {
gateways = sysGateways.split(" ");
} else {
gateways = new String[0];
}
}
for (String addr : gateways) {
addr = addr.trim();
if (addr.isEmpty()) continue;
InetAddress ia;
try {
ia = NetworkUtils.numericToInetAddress(addr);
} catch (IllegalArgumentException e) {
throw new UnknownHostException("Non-numeric gateway addr=" + addr);
}
if (! ia.isAnyLocalAddress()) {
linkProperties.addRoute(new RouteInfo(ia));
}
}
result = SetupResult.SUCCESS;
} catch (UnknownHostException e) {
Log.d(LOG_TAG, "setLinkProperties: UnknownHostException " + e);
e.printStackTrace();
result = SetupResult.ERR_UnacceptableParameter;
}
} else {
if (version < 4) {
result = SetupResult.ERR_GetLastErrorFromRil;
} else {
result = SetupResult.ERR_RilError;
}
}
// An error occurred so clear properties
if (result != SetupResult.SUCCESS) {
if(DBG) {
Log.d(LOG_TAG, "setLinkProperties: error clearing LinkProperties " +
"status=" + status + " result=" + result);
}
linkProperties.clear();
}
return result;
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.adempiere.adempiere/base/src/main/java-gen/org/compiere/model/X_C_ChargeType_DocType.java | 5140 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for C_ChargeType_DocType
* @author Adempiere (generated)
* @version Release 3.5.4a - $Id$ */
public class X_C_ChargeType_DocType extends PO implements I_C_ChargeType_DocType, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20090915L;
/** Standard Constructor */
public X_C_ChargeType_DocType (Properties ctx, int C_ChargeType_DocType_ID, String trxName)
{
super (ctx, C_ChargeType_DocType_ID, trxName);
/** if (C_ChargeType_DocType_ID == 0)
{
setC_ChargeType_ID (0);
setC_DocType_ID (0);
setIsAllowNegative (true);
// Y
setIsAllowPositive (true);
// Y
} */
}
/** Load Constructor */
public X_C_ChargeType_DocType (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 3 - Client - Org
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_ChargeType_DocType[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_ChargeType getC_ChargeType() throws RuntimeException
{
return (I_C_ChargeType)MTable.get(getCtx(), I_C_ChargeType.Table_Name)
.getPO(getC_ChargeType_ID(), get_TrxName()); }
/** Set Charge Type.
@param C_ChargeType_ID Charge Type */
public void setC_ChargeType_ID (int C_ChargeType_ID)
{
if (C_ChargeType_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ChargeType_ID, Integer.valueOf(C_ChargeType_ID));
}
/** Get Charge Type.
@return Charge Type */
public int getC_ChargeType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ChargeType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_DocType getC_DocType() throws RuntimeException
{
return (I_C_DocType)MTable.get(getCtx(), I_C_DocType.Table_Name)
.getPO(getC_DocType_ID(), get_TrxName()); }
/** Set Document Type.
@param C_DocType_ID
Document type or rules
*/
public void setC_DocType_ID (int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID));
}
/** Get Document Type.
@return Document type or rules
*/
public int getC_DocType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Allow Negative.
@param IsAllowNegative Allow Negative */
public void setIsAllowNegative (boolean IsAllowNegative)
{
set_Value (COLUMNNAME_IsAllowNegative, Boolean.valueOf(IsAllowNegative));
}
/** Get Allow Negative.
@return Allow Negative */
public boolean isAllowNegative ()
{
Object oo = get_Value(COLUMNNAME_IsAllowNegative);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Allow Positive.
@param IsAllowPositive Allow Positive */
public void setIsAllowPositive (boolean IsAllowPositive)
{
set_Value (COLUMNNAME_IsAllowPositive, Boolean.valueOf(IsAllowPositive));
}
/** Get Allow Positive.
@return Allow Positive */
public boolean isAllowPositive ()
{
Object oo = get_Value(COLUMNNAME_IsAllowPositive);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | gpl-2.0 |
arthurmelo88/palmetalADP | adempiere_360/base/src/org/compiere/model/X_AD_Package_Imp.java | 8279 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package org.compiere.model;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.KeyNamePair;
/** Generated Model for AD_Package_Imp
* @author Adempiere (generated)
* @version Release 3.6.0LTS - $Id$ */
public class X_AD_Package_Imp extends PO implements I_AD_Package_Imp, I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 20100614L;
/** Standard Constructor */
public X_AD_Package_Imp (Properties ctx, int AD_Package_Imp_ID, String trxName)
{
super (ctx, AD_Package_Imp_ID, trxName);
/** if (AD_Package_Imp_ID == 0)
{
setAD_Package_Imp_ID (0);
setDescription (null);
setName (null);
setProcessing (false);
} */
}
/** Load Constructor */
public X_AD_Package_Imp (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** AccessLevel
* @return 4 - System
*/
protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_AD_Package_Imp[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Package Imp..
@param AD_Package_Imp_ID Package Imp. */
public void setAD_Package_Imp_ID (int AD_Package_Imp_ID)
{
if (AD_Package_Imp_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Package_Imp_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Package_Imp_ID, Integer.valueOf(AD_Package_Imp_ID));
}
/** Get Package Imp..
@return Package Imp. */
public int getAD_Package_Imp_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Package_Imp_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_Package_Imp_ID()));
}
/** Set CreatedDate.
@param CreatedDate CreatedDate */
public void setCreatedDate (String CreatedDate)
{
set_Value (COLUMNNAME_CreatedDate, CreatedDate);
}
/** Get CreatedDate.
@return CreatedDate */
public String getCreatedDate ()
{
return (String)get_Value(COLUMNNAME_CreatedDate);
}
/** Set Creator.
@param Creator Creator */
public void setCreator (String Creator)
{
set_Value (COLUMNNAME_Creator, Creator);
}
/** Get Creator.
@return Creator */
public String getCreator ()
{
return (String)get_Value(COLUMNNAME_Creator);
}
/** Set CreatorContact.
@param CreatorContact CreatorContact */
public void setCreatorContact (String CreatorContact)
{
set_Value (COLUMNNAME_CreatorContact, CreatorContact);
}
/** Get CreatorContact.
@return CreatorContact */
public String getCreatorContact ()
{
return (String)get_Value(COLUMNNAME_CreatorContact);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set EMail Address.
@param EMail
Electronic Mail Address
*/
public void setEMail (String EMail)
{
set_Value (COLUMNNAME_EMail, EMail);
}
/** Get EMail Address.
@return Electronic Mail Address
*/
public String getEMail ()
{
return (String)get_Value(COLUMNNAME_EMail);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set PK_Status.
@param PK_Status PK_Status */
public void setPK_Status (String PK_Status)
{
set_Value (COLUMNNAME_PK_Status, PK_Status);
}
/** Get PK_Status.
@return PK_Status */
public String getPK_Status ()
{
return (String)get_Value(COLUMNNAME_PK_Status);
}
/** Set Package Version.
@param PK_Version Package Version */
public void setPK_Version (String PK_Version)
{
set_Value (COLUMNNAME_PK_Version, PK_Version);
}
/** Get Package Version.
@return Package Version */
public String getPK_Version ()
{
return (String)get_Value(COLUMNNAME_PK_Version);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Release No.
@param ReleaseNo
Internal Release Number
*/
public void setReleaseNo (String ReleaseNo)
{
set_Value (COLUMNNAME_ReleaseNo, ReleaseNo);
}
/** Get Release No.
@return Internal Release Number
*/
public String getReleaseNo ()
{
return (String)get_Value(COLUMNNAME_ReleaseNo);
}
/** Set Uninstall.
@param Uninstall Uninstall */
public void setUninstall (boolean Uninstall)
{
set_Value (COLUMNNAME_Uninstall, Boolean.valueOf(Uninstall));
}
/** Get Uninstall.
@return Uninstall */
public boolean isUninstall ()
{
Object oo = get_Value(COLUMNNAME_Uninstall);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set UpdatedDate.
@param UpdatedDate UpdatedDate */
public void setUpdatedDate (String UpdatedDate)
{
set_Value (COLUMNNAME_UpdatedDate, UpdatedDate);
}
/** Get UpdatedDate.
@return UpdatedDate */
public String getUpdatedDate ()
{
return (String)get_Value(COLUMNNAME_UpdatedDate);
}
/** Set Version.
@param Version
Version of the table definition
*/
public void setVersion (String Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
public String getVersion ()
{
return (String)get_Value(COLUMNNAME_Version);
}
} | gpl-2.0 |
md-5/jdk10 | src/java.base/share/classes/java/io/PipedReader.java | 12369 | /*
* Copyright (c) 1996, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
/**
* Piped character-input streams.
*
* @author Mark Reinhold
* @since 1.1
*/
public class PipedReader extends Reader {
boolean closedByWriter = false;
boolean closedByReader = false;
boolean connected = false;
/* REMIND: identification of the read and write sides needs to be
more sophisticated. Either using thread groups (but what about
pipes within a thread?) or using finalization (but it may be a
long time until the next GC). */
Thread readSide;
Thread writeSide;
/**
* The size of the pipe's circular input buffer.
*/
private static final int DEFAULT_PIPE_SIZE = 1024;
/**
* The circular buffer into which incoming data is placed.
*/
char buffer[];
/**
* The index of the position in the circular buffer at which the
* next character of data will be stored when received from the connected
* piped writer. <code>in<0</code> implies the buffer is empty,
* {@code in==out} implies the buffer is full
*/
int in = -1;
/**
* The index of the position in the circular buffer at which the next
* character of data will be read by this piped reader.
*/
int out = 0;
/**
* Creates a {@code PipedReader} so
* that it is connected to the piped writer
* {@code src}. Data written to {@code src}
* will then be available as input from this stream.
*
* @param src the stream to connect to.
* @throws IOException if an I/O error occurs.
*/
public PipedReader(PipedWriter src) throws IOException {
this(src, DEFAULT_PIPE_SIZE);
}
/**
* Creates a {@code PipedReader} so that it is connected
* to the piped writer {@code src} and uses the specified
* pipe size for the pipe's buffer. Data written to {@code src}
* will then be available as input from this stream.
* @param src the stream to connect to.
* @param pipeSize the size of the pipe's buffer.
* @throws IOException if an I/O error occurs.
* @throws IllegalArgumentException if {@code pipeSize <= 0}.
* @since 1.6
*/
public PipedReader(PipedWriter src, int pipeSize) throws IOException {
initPipe(pipeSize);
connect(src);
}
/**
* Creates a {@code PipedReader} so
* that it is not yet {@linkplain #connect(java.io.PipedWriter)
* connected}. It must be {@linkplain java.io.PipedWriter#connect(
* java.io.PipedReader) connected} to a {@code PipedWriter}
* before being used.
*/
public PipedReader() {
initPipe(DEFAULT_PIPE_SIZE);
}
/**
* Creates a {@code PipedReader} so that it is not yet
* {@link #connect(java.io.PipedWriter) connected} and uses
* the specified pipe size for the pipe's buffer.
* It must be {@linkplain java.io.PipedWriter#connect(
* java.io.PipedReader) connected} to a {@code PipedWriter}
* before being used.
*
* @param pipeSize the size of the pipe's buffer.
* @throws IllegalArgumentException if {@code pipeSize <= 0}.
* @since 1.6
*/
public PipedReader(int pipeSize) {
initPipe(pipeSize);
}
private void initPipe(int pipeSize) {
if (pipeSize <= 0) {
throw new IllegalArgumentException("Pipe size <= 0");
}
buffer = new char[pipeSize];
}
/**
* Causes this piped reader to be connected
* to the piped writer {@code src}.
* If this object is already connected to some
* other piped writer, an {@code IOException}
* is thrown.
* <p>
* If {@code src} is an
* unconnected piped writer and {@code snk}
* is an unconnected piped reader, they
* may be connected by either the call:
*
* <pre>{@code snk.connect(src)} </pre>
* <p>
* or the call:
*
* <pre>{@code src.connect(snk)} </pre>
* <p>
* The two calls have the same effect.
*
* @param src The piped writer to connect to.
* @throws IOException if an I/O error occurs.
*/
public void connect(PipedWriter src) throws IOException {
src.connect(this);
}
/**
* Receives a char of data. This method will block if no input is
* available.
*/
synchronized void receive(int c) throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByWriter || closedByReader) {
throw new IOException("Pipe closed");
} else if (readSide != null && !readSide.isAlive()) {
throw new IOException("Read end dead");
}
writeSide = Thread.currentThread();
while (in == out) {
if ((readSide != null) && !readSide.isAlive()) {
throw new IOException("Pipe broken");
}
/* full: kick any waiting readers */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
if (in < 0) {
in = 0;
out = 0;
}
buffer[in++] = (char) c;
if (in >= buffer.length) {
in = 0;
}
}
/**
* Receives data into an array of characters. This method will
* block until some input is available.
*/
synchronized void receive(char c[], int off, int len) throws IOException {
while (--len >= 0) {
receive(c[off++]);
}
}
/**
* Notifies all waiting threads that the last character of data has been
* received.
*/
synchronized void receivedLast() {
closedByWriter = true;
notifyAll();
}
/**
* Reads the next character of data from this piped stream.
* If no character is available because the end of the stream
* has been reached, the value {@code -1} is returned.
* This method blocks until input data is available, the end of
* the stream is detected, or an exception is thrown.
*
* @return the next character of data, or {@code -1} if the end of the
* stream is reached.
* @throws IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> {@code broken}</a>,
* {@link #connect(java.io.PipedWriter) unconnected}, closed,
* or an I/O error occurs.
*/
public synchronized int read() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
readSide = Thread.currentThread();
int trials = 2;
while (in < 0) {
if (closedByWriter) {
/* closed by writer, return EOF */
return -1;
}
if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) {
throw new IOException("Pipe broken");
}
/* might be a writer waiting */
notifyAll();
try {
wait(1000);
} catch (InterruptedException ex) {
throw new java.io.InterruptedIOException();
}
}
int ret = buffer[out++];
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -1;
}
return ret;
}
/**
* Reads up to {@code len} characters of data from this piped
* stream into an array of characters. Less than {@code len} characters
* will be read if the end of the data stream is reached or if
* {@code len} exceeds the pipe's buffer size. This method
* blocks until at least one character of input is available.
*
* @param cbuf the buffer into which the data is read.
* @param off the start offset of the data.
* @param len the maximum number of characters read.
* @return the total number of characters read into the buffer, or
* {@code -1} if there is no more data because the end of
* the stream has been reached.
* @throws IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> {@code broken}</a>,
* {@link #connect(java.io.PipedWriter) unconnected}, closed,
* or an I/O error occurs.
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public synchronized int read(char cbuf[], int off, int len) throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
/* possibly wait on the first character */
int c = read();
if (c < 0) {
return -1;
}
cbuf[off] = (char)c;
int rlen = 1;
while ((in >= 0) && (--len > 0)) {
cbuf[off + rlen] = buffer[out++];
rlen++;
if (out >= buffer.length) {
out = 0;
}
if (in == out) {
/* now empty */
in = -1;
}
}
return rlen;
}
/**
* Tell whether this stream is ready to be read. A piped character
* stream is ready if the circular buffer is not empty.
*
* @throws IOException if the pipe is
* <a href=PipedInputStream.html#BROKEN> {@code broken}</a>,
* {@link #connect(java.io.PipedWriter) unconnected}, or closed.
*/
public synchronized boolean ready() throws IOException {
if (!connected) {
throw new IOException("Pipe not connected");
} else if (closedByReader) {
throw new IOException("Pipe closed");
} else if (writeSide != null && !writeSide.isAlive()
&& !closedByWriter && (in < 0)) {
throw new IOException("Write end dead");
}
if (in < 0) {
return false;
} else {
return true;
}
}
/**
* Closes this piped stream and releases any system resources
* associated with the stream.
*
* @throws IOException if an I/O error occurs.
*/
public void close() throws IOException {
in = -1;
closedByReader = true;
}
}
| gpl-2.0 |
IceOnFire/J2MEGaming | ScroogePuyoMayCry/src/it/ice/puyomaycry/actions/CoccolaAction.java | 509 | package it.ice.puyomaycry.actions;
import it.ice.puyomaycry.properties.Properties;
import it.ice.puyomaycry.properties.PuyoProperty;
import it.ice.puyomaycry.states.States;
import it.ice.scrooge.Action;
import it.ice.scrooge.Node;
public class CoccolaAction extends Action {
public CoccolaAction(Node agent) {
super(agent);
}
protected void run() {
PuyoProperty affetto = (PuyoProperty) node
.getProperty(Properties.AFFETTO);
affetto.increase();
node.setActiveState(States.COCCOLANTE);
}
}
| gpl-2.0 |
bugcy013/opennms-tmp-tools | opennms-correlation/drools-correlation-engine/src/main/java/org/opennms/netmgt/correlation/drools/Impact.java | 1738 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2007-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.correlation.drools;
import org.opennms.netmgt.xml.event.Event;
/**
* <p>Impact class.</p>
*
* @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a>
* @version $Id: $
*/
public class Impact extends Cause {
/**
* <p>Constructor for Impact.</p>
*
* @param cause a {@link java.lang.Long} object.
* @param symptom a {@link org.opennms.netmgt.xml.event.Event} object.
*/
public Impact(final Long cause, final Event symptom) {
super(Type.IMPACT, cause, symptom);
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/security/src/test/impl/java/org/apache/harmony/security/tests/asn1/der/OidTest.java | 7595 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Stepan M. Mishura
*/
package org.apache.harmony.security.tests.asn1.der;
import java.io.IOException;
import java.util.Arrays;
import org.apache.harmony.security.asn1.ASN1Exception;
import org.apache.harmony.security.asn1.ASN1Oid;
import org.apache.harmony.security.asn1.DerInputStream;
import org.apache.harmony.security.asn1.DerOutputStream;
import junit.framework.TestCase;
/**
* ASN.1 DER test for OID type
*
* @see http://asn1.elibel.tm.fr/en/standards/index.htm
*/
public class OidTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(OidTest.class);
}
private static Object[][] oid = {
//oid array format: string / int array / DER encoding
{ "0.0", // as string
new int[] { 0, 0 }, // as int array
new byte[] { 0x06, 0x01, 0x00 } },
//
{ "0.0.3", // as string
new int[] { 0, 0, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x00, 0x03 } },
//
{ "0.1.3", // as string
new int[] { 0, 1, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x01, 0x03 } },
//
{ "0.5", // as string
new int[] { 0, 5 }, // as int array
new byte[] { 0x06, 0x01, 0x05 } },
//
{ "0.39.3", // as string
new int[] { 0, 39, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x27, 0x03 } },
//
{ "1.0.3", // as string
new int[] { 1, 0, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x28, 0x03 } },
//
{ "1.1", // as string
new int[] { 1, 1 }, // as int array
new byte[] { 0x06, 0x01, 0x29 } },
//
{ "1.2.1.2.1",// as string
new int[] { 1, 2, 1, 2, 1 }, // as int array
new byte[] { 0x06, 0x04, 0x2A, 0x01, 0x02, 0x01 } },
//
{
"1.2.840.113554.1.2.2",// as string
new int[] { 1, 2, 840, 113554, 1, 2, 2 }, // as int array
new byte[] { 0x06, 0x09, 0x2A, (byte) 0x86, 0x48,
(byte) 0x86, (byte) 0xF7, 0x12, 0x01, 0x02, 0x02 } },
//
{ "1.39.3",// as string
new int[] { 1, 39, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x4F, 0x03 } },
//
{ "2.0.3",// as string
new int[] { 2, 0, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x50, 0x03 } },
//
{ "2.5.4.3",// as string
new int[] { 2, 5, 4, 3 }, // as int array
new byte[] { 0x06, 0x03, 0x55, 0x04, 0x03 } },
//
{ "2.39.3", // as string
new int[] { 2, 39, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x77, 0x03 } },
//
{ "2.40.3", // as string
new int[] { 2, 40, 3 }, // as int array
new byte[] { 0x06, 0x02, 0x78, 0x03 } },
//
{ "2.47", // as string
new int[] { 2, 47 }, // as int array
new byte[] { 0x06, 0x01, 0x7F } },
//
{ "2.48", // as string
new int[] { 2, 48 }, // as int array
new byte[] { 0x06, 0x02, (byte) 0x81, 0x00 } },
//
{ "2.48.5", // as string
new int[] { 2, 48, 5 }, // as int array
new byte[] { 0x06, 0x03, (byte) 0x81, 0x00, 0x05 } },
//
{ "2.100.3", // as string
new int[] { 2, 100, 3 }, // as int array
new byte[] { 0x06, 0x03, (byte) 0x81, 0x34, 0x03 } } };
public void test_MappingToIntArray() throws IOException {
// oid decoder/encoder for testing
ASN1Oid asn1 = ASN1Oid.getInstance();
// testing decoding
for (int i = 0; i < oid.length; i++) {
int[] decoded = (int[]) asn1.decode(new DerInputStream(
(byte[]) oid[i][2]));
assertTrue("Failed to decode oid: " + oid[i][0], // error message
Arrays.equals((int[]) oid[i][1], // expected array
decoded));
}
// testing encoding
for (int i = 0; i < oid.length; i++) {
byte[] encoded = new DerOutputStream(ASN1Oid.getInstance(),
oid[i][1]).encoded;
assertTrue("Failed to encode oid: " + oid[i][0], // error message
Arrays.equals((byte[]) oid[i][2], // expected encoding
encoded));
}
}
public void testDecode_Invalid() throws IOException {
byte[][] invalid = new byte[][] {
// wrong tag: tag is not 0x06
new byte[] { 0x02, 0x01, 0x00 },
// wrong length: length is 0
new byte[] { 0x06, 0x00 },
// wrong content: bit 8 of the last byte is not 0
new byte[] { 0x06, 0x02, (byte) 0x81, (byte) 0x80 },
// wrong content: is not encoded in fewest number of bytes
//FIXME new byte[] { 0x06, 0x02, (byte) 0x80, (byte) 0x01 }
};
for (int i = 0; i < invalid.length; i++) {
try {
DerInputStream in = new DerInputStream(invalid[i]);
ASN1Oid.getInstance().decode(in);
fail("No expected ASN1Exception for:" + i);
} catch (ASN1Exception e) {
}
}
}
public void test_MappingToString() throws IOException {
// oid decoder/encoder for testing
ASN1Oid asn1 = ASN1Oid.getInstanceForString();
// testing decoding
for (int i = 0; i < oid.length; i++) {
assertEquals("Failed to decode oid: " + oid[i][0], // error message
oid[i][0], // expected string
asn1.decode(new DerInputStream((byte[]) oid[i][2])));
}
// testing encoding
for (int i = 0; i < oid.length; i++) {
assertTrue("Failed to encode oid: " + oid[i][0], // error message
Arrays.equals((byte[]) oid[i][2], // expected encoding
new DerOutputStream(asn1, oid[i][0]).encoded));
}
}
}
| gpl-2.0 |
rac021/blazegraph_1_5_3_cluster_2_nodes | bigdata-jini/src/main/java/com/bigdata/service/jini/JiniClient.java | 14945 | /**
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Mar 24, 2007
*/
package com.bigdata.service.jini;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationProvider;
import org.apache.zookeeper.ZooKeeper;
import com.bigdata.BigdataStatics;
import com.bigdata.jini.start.config.ZookeeperClientConfig;
import com.bigdata.jini.util.ConfigMath;
import com.bigdata.service.AbstractScaleOutClient;
import com.bigdata.service.jini.lookup.DataServicesClient;
import com.bigdata.util.NV;
import com.sun.jini.start.ServiceDescriptor;
/**
* A client capable of connecting to a distributed bigdata federation using
* JINI.
* <p>
* Clients are configured using a Jini service configuration file. The name of
* that file is passed to {@link #newInstance(String[])}. The configuration
* must be consistent with the configuration of the federation to which you
* wish to connect.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
* @param <T>
* The generic type of the client or service.
*/
public class JiniClient<T> extends AbstractScaleOutClient<T> {
/**
* Options understood by the {@link JiniClient}.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
*/
public static interface Options extends AbstractScaleOutClient.Options {
/**
* The timeout in milliseconds that the client will await the discovery
* of a service if there is a cache miss (default
* {@value #DEFAULT_CACHE_MISS_TIMEOUT}).
*
* @see DataServicesClient
*/
String CACHE_MISS_TIMEOUT = "cacheMissTimeout";
String DEFAULT_CACHE_MISS_TIMEOUT = "" + (2 * 1000);
}
/**
* The value is the connected federation and <code>null</code> iff not
* connected.
*/
private final AtomicReference<JiniFederation<T>> fed = new AtomicReference<JiniFederation<T>>();
/**
* The lock used to guard {@link #connect()} and
* {@link #disconnect(boolean)}.
* <p>
* Note: In order to avoid some deadlocks during the shutdown protocol, I
* refactored several methods which were using synchronized(this) to either
* use an {@link AtomicReference} (for {@link #fed} or to use a hidden lock.
*/
private final Lock connectLock = new ReentrantLock(false/* fair */);
public boolean isConnected() {
return fed.get() != null;
}
public JiniFederation<T> getFederation() {
final JiniFederation<T> fed = this.fed.get();
if (fed == null) {
throw new IllegalStateException();
}
return fed;
}
/**
* {@inheritDoc}
* <p>
* Note: Immediate shutdown can cause odd exceptions to be logged. Normal
* shutdown is recommended unless there is a reason to force immediate
* shutdown.
*
* <pre>
* java.rmi.MarshalException: error marshalling arguments; nested exception is:
* java.io.IOException: request I/O interrupted
* at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethodOnce(BasicInvocationHandler.java:785)
* at net.jini.jeri.BasicInvocationHandler.invokeRemoteMethod(BasicInvocationHandler.java:659)
* at net.jini.jeri.BasicInvocationHandler.invoke(BasicInvocationHandler.java:528)
* at $Proxy5.notify(Ljava.lang.String;Ljava.util.UUID;Ljava.lang.String;[B)V(Unknown Source)
* </pre>
*
* These messages may be safely ignored if they occur during immediate
* shutdown.
*
* @param immediateShutdown
* When <code>true</code> the shutdown is <em>abrupt</em>. You
* can expect to see messages about interrupted IO such as
*/
// synchronized
public void disconnect(final boolean immediateShutdown) {
connectLock.lock();
try {
final JiniFederation<T> fed = this.fed.get();
if (fed != null) {
if (immediateShutdown) {
fed.shutdownNow();
} else {
fed.shutdown();
}
}
this.fed.set(null);
} finally {
connectLock.unlock();
}
}
// synchronized
public JiniFederation<T> connect() {
connectLock.lock();
try {
JiniFederation<T> fed = this.fed.get();
if (fed == null) {
fed = new JiniFederation<T>(this, jiniConfig, zooConfig);
this.fed.set(fed);
}
return fed;
} finally {
connectLock.unlock();
}
}
/**
* The {@link JiniClient} configuration.
*/
public final JiniClientConfig jiniConfig;
/**
* The {@link ZooKeeper} client configuration.
*/
public final ZookeeperClientConfig zooConfig;
/**
* The {@link Configuration} object used to initialize this class.
*/
private final Configuration config;
/**
* The {@link JiniClient} configuration.
*/
public JiniClientConfig getJiniClientConfig() {
return jiniConfig;
}
/**
* The {@link ZooKeeper} client configuration.
*/
public final ZookeeperClientConfig getZookeeperClientConfig() {
return zooConfig;
}
/**
* The {@link Configuration} object used to initialize this class.
*/
public final Configuration getConfiguration() {
return config;
}
/**
* {@inheritDoc}
*
* @see #getProperties(String component)
*/
@Override
public Properties getProperties() {
return super.getProperties();
}
/**
* Return the {@link Properties} for the {@link JiniClient} merged with
* those for the named component in the {@link Configuration}. Any
* properties found for the {@link JiniClient} "component" will be read
* first. Properties for the named component are next, and therefore will
* override those given for the {@link JiniClient}. You can specify
* properties for either the {@link JiniClient} or the <i>component</i>
* using:
*
* <pre>
* properties = NV[]{...};
* </pre>
*
* in the appropriate section of the {@link Configuration}. For example:
*
* <pre>
*
* // Jini client configuration
* com.bigdata.service.jini.JiniClient {
*
* // ...
*
* // optional JiniClient properties.
* properties = new NV[] {
*
* new NV("foo","bar")
*
* };
*
* }
* </pre>
*
* And overrides for a named component as:
*
* <pre>
*
* com.bigdata.service.FooBaz {
*
* properties = new NV[] {
*
* new NV("foo","baz"),
* new NV("goo","12"),
*
* };
*
* }
* </pre>
*
* @param component
* The name of the component.
*
* @return The properties specified for that component.
*
* @see #getConfiguration()
*/
public Properties getProperties(final String component)
throws ConfigurationException {
return JiniClient.getProperties(component, getConfiguration());
}
/**
* Read {@value JiniClientConfig.Options#PROPERTIES} for the optional
* application or server class identified by [cls].
* <p>
* Note: Anything read for the specific class will overwrite any value for
* the same properties specified for {@link JiniClient}.
*
* @param className
* The class name of the client or service (optional). When
* specified, properties defined for that class in the
* configuration will be used and will override those specified
* for the {@value Options#NAMESPACE}.
* @param config
* The {@link Configuration}.
*
* @todo this could be replaced by explicit use of the java identifier
* corresponding to the Option and simply collecting all such
* properties into a Properties object using their native type (as
* reported by the ConfigurationFile).
*/
static public Properties getProperties(final String className,
final Configuration config) throws ConfigurationException {
final NV[] a = (NV[]) config
.getEntry(JiniClient.class.getName(),
JiniClientConfig.Options.PROPERTIES, NV[].class,
new NV[] {}/* defaultValue */);
final NV[] b;
if (className != null) {
b = (NV[]) config.getEntry(className,
JiniClientConfig.Options.PROPERTIES, NV[].class,
new NV[] {}/* defaultValue */);
} else
b = null;
final NV[] tmp = ConfigMath.concat(a, b);
final Properties properties = new Properties();
for (NV nv : tmp) {
properties.setProperty(nv.getName(), nv.getValue());
}
if (log.isInfoEnabled() || BigdataStatics.debug) {
final String msg = "className=" + className + " : properties="
+ properties.toString();
if (BigdataStatics.debug)
System.err.println(msg);
if (log.isInfoEnabled())
log.info(msg);
}
return properties;
}
/**
* Installs a {@link SecurityManager} and returns a new client.
*
* @param args
* Either the command line arguments or the arguments from the
* {@link ServiceDescriptor}. Either way they identify the jini
* {@link Configuration} (you may specify either a file or URL)
* and optional overrides for that {@link Configuration}.
*
* @return The new client.
*
* @throws RuntimeException
* if there is a problem reading the jini configuration for the
* client, reading the properties for the client, etc.
*/
public static JiniClient newInstance(final String[] args) {
// set the security manager.
setSecurityManager();
try {
return new JiniClient(args);
} catch (ConfigurationException e) {
throw new RuntimeException(e);
}
}
/**
* Configures a client.
*
* @param args
* The jini {@link Configuration} (you may specify either a file
* or URL) and optional overrides for that {@link Configuration}.
*
* @throws ConfigurationException
*/
public JiniClient(final String[] args) throws ConfigurationException {
this(JiniClient.class, ConfigurationProvider.getInstance(args));
}
/**
* Configures a client.
*
* @param cls
* The class of the client (optional) determines the component
* whose configuration will be read in addition to that for the
* {@link JiniClient} itself. Component specific values will
* override those specified for the {@link JiniClient} in the
* {@link Configuration}.
* @param config
* The configuration object.
*
* @throws ConfigurationException
*/
public JiniClient(final Class cls, final Configuration config)
throws ConfigurationException {
super(JiniClient.getProperties(cls.getName(), config));
this.jiniConfig = new JiniClientConfig(cls.getName(), config);
this.zooConfig = new ZookeeperClientConfig(config);
this.config = config;
}
/**
* Conditionally install a suitable security manager if there is none in
* place. This is required before the client can download code. The code
* will be downloaded from the HTTP server identified by the
* <code>java.rmi.server.codebase</code> property specified for the VM
* running the service.
*/
static protected void setSecurityManager() {
final SecurityManager sm = System.getSecurityManager();
if (sm == null) {
System.setSecurityManager(new SecurityManager());
if (log.isInfoEnabled())
log.info("Set security manager");
} else {
if (log.isInfoEnabled())
log.info("Security manager already in place: " + sm.getClass());
}
}
/**
* Read and return the content of the properties file.
*
* @param propertyFile
* The properties file.
*
* @throws IOException
*/
static protected Properties getProperties(final File propertyFile)
throws IOException {
if(log.isInfoEnabled()) {
log.info("Reading properties: file="+propertyFile);
}
final Properties properties = new Properties();
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(propertyFile));
properties.load(is);
if(log.isInfoEnabled()) {
log.info("Read properties: " + properties);
}
return properties;
} finally {
if (is != null)
is.close();
}
}
}
| gpl-2.0 |
huangfangyi/FanXin-based-HuanXin_2.0beta | app/src/main/java/com/htmessage/fanxinht/manager/HTNotification.java | 7456 | package com.htmessage.fanxinht.manager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.htmessage.sdk.utils.MessageUtils;
import com.htmessage.fanxinht.R;
import com.htmessage.fanxinht.domain.User;
import com.htmessage.fanxinht.acitivity.chat.ChatActivity;
import com.htmessage.sdk.ChatType;
import com.htmessage.sdk.client.HTClient;
import com.htmessage.sdk.model.HTConversation;
import com.htmessage.sdk.model.HTGroup;
import com.htmessage.sdk.model.HTMessage;
import com.htmessage.sdk.model.HTMessageTextBody;
/**
* Created by huangfangyi on 2016/12/19.
* qq 84543217
*/
public class HTNotification {
private NotificationManager manager = null;
private Context mContext;
private NotificationCompat.Builder builder;
public HTNotification(Context context) {
this.mContext = context;
manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//为了版本兼容 选择V4包下的NotificationCompat进行构造
builder = new NotificationCompat.Builder(mContext);
}
public void onNewMessage(HTMessage htMessage) {
String userId = htMessage.getUsername();
String userNick = userId;
Intent intent = new Intent();
intent.setClass(mContext, ChatActivity.class);
intent.putExtra("userId", userId);
if (htMessage.getChatType() == ChatType.singleChat) {
User user = ContactsManager.getInstance().getContactList().get(userId);
if (user != null) {
userNick = user.getNick();
}
} else if (htMessage.getChatType() == ChatType.groupChat) {
HTGroup htGroup = HTClient.getInstance().groupManager().getGroup(userId);
if (htGroup != null) {
userNick = htGroup.getGroupName();
}
intent.putExtra("chatType", MessageUtils.CHAT_GROUP);
}
// if (!HTApp.getInstance().isForegroud()) {
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// PendingIntent pendingIntent = PendingIntent.getActivity(mContext, Integer.valueOf(userId), intent, PendingIntent.FLAG_UPDATE_CURRENT);
// builder
// .setContentIntent(pendingIntent)
// .setContentTitle(userNick)
// // .setTicker("发来一个新消息")
// .setContentText(getContent(htMessage))
// .setWhen(System.currentTimeMillis())
// .setPriority(Notification.PRIORITY_DEFAULT)
//// .setOngoing(false)
//// .setAutoCancel(true)
// .setAutoCancel(true)
// .setFullScreenIntent(pendingIntent, true)
// .setDefaults(Notification.DEFAULT_SOUND)
// .setSmallIcon(mContext.getApplicationInfo().icon);
// // do stuff
// Log.d("isMyProces --->", "isMyProcessInTheForeground");
// NotificationCompatBase.Action action;
//
// //如果描述的PendingIntent已经存在,则在产生新的Intent之前会先取消掉当前的
//// PendingIntent hangPendingIntent = PendingIntent.getActivity(mContext, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//// builder.setFullScreenIntent(hangPendingIntent, true);
//// // notificationManager.notify(2, builder.build());
// } else {
// 如果当前Activity启动在前台,则不开启新的Activity。
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, Integer.valueOf(userId), intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent)
.setContentTitle(userNick)
// .setTicker("发来一个新消息")
.setContentText(getContent(htMessage))
.setWhen(System.currentTimeMillis())
// .setPriority(Notification.PRIORITY_DEFAULT)
// .setOngoing(false)
// .setAutoCancel(true)
// .setDefaults(Notification.DEFAULT_SOUND)
.setSmallIcon(mContext.getApplicationInfo().icon);
// Log.d("isMyProces2 --->", "isMyProcessInTheForeground");
// }
Notification notification = builder.build();
/**
* 判断是否打开了某些设置
* */
if (SettingsManager.getInstance().getSettingMsgNotification()) {
if (SettingsManager.getInstance().getSettingMsgSound() && !SettingsManager.getInstance().getSettingMsgVibrate()) {
notification.flags = Notification.DEFAULT_SOUND;
} else if (SettingsManager.getInstance().getSettingMsgVibrate() && !SettingsManager.getInstance().getSettingMsgSound()) {
notification.flags = Notification.DEFAULT_VIBRATE;
} else if (SettingsManager.getInstance().getSettingMsgVibrate() && SettingsManager.getInstance().getSettingMsgSound()) {
notification.flags = Notification.DEFAULT_ALL;
} else {
notification.flags = Notification.DEFAULT_LIGHTS;
}
}
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(Integer.valueOf(userId), notification);//发送通知
}
public void cancel(int id) {
manager.cancel(id);
}
protected final static int[] msgs = {R.string.sent_a_message, R.string.sent_a_picture,R.string.sent_a_voice, R.string.sent_a_location,R.string.sent_a_video, R.string.sent_a_file,
R.string.contacts_messages};
private String getContent(HTMessage message) {
HTConversation htConversation = HTClient.getInstance().conversationManager().getConversation(message.getFrom());
String notifyText = "";
if (htConversation != null) {
if (htConversation.getUnReadCount() > 0) {
notifyText = mContext.getString(R.string.zhongkuohao) + htConversation.getUnReadCount() + mContext.getString(R.string.zhongkuohao_msg);
}
}
switch (message.getType()) {
case TEXT:
HTMessageTextBody htMessageTextBody = (HTMessageTextBody) message.getBody();
String content = htMessageTextBody.getContent();
if (content != null) {
notifyText += content;
} else {
notifyText += getString(msgs[0]);
}
break;
case IMAGE:
notifyText += getString(msgs[1]);
break;
case VOICE:
notifyText +=getString(msgs[2]);
break;
case LOCATION:
notifyText += getString(msgs[3]);
break;
case VIDEO:
notifyText += getString(msgs[4]);
break;
case FILE:
notifyText += getString(msgs[4]);
break;
}
return notifyText;
}
private String getString(int res){
if(mContext!=null){
return mContext.getString(res);
}
return "";
}
}
| gpl-2.0 |
bugcy013/opennms-tmp-tools | opennms-provision/opennms-detector-datagram/src/main/java/org/opennms/netmgt/provision/detector/datagram/DnsDetector.java | 4788 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2008-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.provision.detector.datagram;
import java.io.IOException;
import java.net.DatagramPacket;
import org.opennms.core.utils.LogUtils;
import org.opennms.netmgt.provision.detector.datagram.client.DatagramClient;
import org.opennms.netmgt.provision.support.BasicDetector;
import org.opennms.netmgt.provision.support.Client;
import org.opennms.netmgt.provision.support.ResponseValidator;
import org.opennms.netmgt.provision.support.dns.DNSAddressRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* <p>DnsDetector class.</p>
*
* @author brozow
* @version $Id: $
*/
@Component
@Scope("prototype")
public class DnsDetector extends BasicDetector<DatagramPacket, DatagramPacket> {
private static final String DEFAULT_SERVICE_NAME = "DNS";
private final static int DEFAULT_PORT = 53;
private final static String DEFAULT_LOOKUP = "localhost";
private String m_lookup = DEFAULT_LOOKUP;
/**
* Default constructor
*/
public DnsDetector() {
super(DEFAULT_SERVICE_NAME, DEFAULT_PORT);
}
/**
* Constructor for creating a non-default service based on this protocol
*
* @param serviceName a {@link java.lang.String} object.
* @param port a int.
*/
public DnsDetector(final String serviceName, final int port) {
super(serviceName, port);
}
/**
* <p>onInit</p>
*/
@Override
protected void onInit() {
final DNSAddressRequest req = addrRequest(getLookup());
send(encode(req), verifyResponse(req));
}
/**
* @param request
* @return
*/
private static ResponseValidator<DatagramPacket> verifyResponse(final DNSAddressRequest request) {
return new ResponseValidator<DatagramPacket>() {
public boolean validate(final DatagramPacket response) {
try {
request.verifyResponse(response.getData(), response.getLength());
} catch (final IOException e) {
LogUtils.infof(this, e, "failed to connect");
return false;
}
return true;
}
};
}
private static DNSAddressRequest addrRequest(final String host) {
return new DNSAddressRequest(host);
}
private static DatagramPacket encode(final DNSAddressRequest dnsPacket) {
final byte[] data = buildRequest(dnsPacket);
return new DatagramPacket(data, data.length);
}
/**
* @param request
* @return
* @throws IOException
*/
private static byte[] buildRequest(final DNSAddressRequest request) {
try {
return request.buildRequest();
} catch (final IOException e) {
// this shouldn't really happen
throw new IllegalStateException("Unable to build dnsRequest!!! This shouldn't happen!!");
}
}
/* (non-Javadoc)
* @see org.opennms.netmgt.provision.detector.BasicDetector#getClient()
*/
/** {@inheritDoc} */
@Override
protected Client<DatagramPacket, DatagramPacket> getClient() {
return new DatagramClient();
}
/**
* <p>setLookup</p>
*
* @param lookup the lookup to set
*/
public void setLookup(final String lookup) {
m_lookup = lookup;
}
/**
* <p>getLookup</p>
*
* @return the lookup
*/
public String getLookup() {
return m_lookup;
}
}
| gpl-2.0 |
damorim/pbicc | test-data/k9/src/SearchModifier.java | 542 | /**
*
*/
package com.fsck.k9.activity;
import com.fsck.k9.R;
import com.fsck.k9.mail.Flag;
enum SearchModifier
{
FLAGGED(R.string.flagged_modifier, new Flag[] { Flag.FLAGGED}, null), UNREAD(R.string.unread_modifier, null, new Flag[] { Flag.SEEN});
final int resId;
final Flag[] requiredFlags;
final Flag[] forbiddenFlags;
SearchModifier(int nResId, Flag[] nRequiredFlags, Flag[] nForbiddenFlags)
{
resId = nResId;
requiredFlags = nRequiredFlags;
forbiddenFlags = nForbiddenFlags;
}
} | gpl-2.0 |
oscarservice/oscar-old | src/main/java/oscar/oscarEncounter/immunization/pageUtil/EctImmPassThruForm.java | 1574 | /**
* Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved.
* This software is published under the GPL GNU General Public License.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* This software was written for the
* Department of Family Medicine
* McMaster University
* Hamilton
* Ontario, Canada
*/
package oscar.oscarEncounter.immunization.pageUtil;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public final class EctImmPassThruForm extends ActionForm {
public void reset(
ActionMapping actionmapping,
HttpServletRequest httpservletrequest) {
}
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
return errors;
}
}
| gpl-2.0 |
shannah/cn1 | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/drlvm/vm/vmcore/src/kernel_classes/javasrc/java/lang/VMExecutionEngine.java | 8186 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgueni Brevnov, Roman S. Bushmanov
*/
package java.lang;
import java.util.Properties;
import java.util.Vector;
/**
* Provides the methods to interact with VM Execution Engine that are used by
* different classes from the <code>java.lang</code> package, such as System,
* Runtime.
* <p>
* This class must be implemented according to the common policy for porting
* interfaces - see the porting interface overview for more detailes.
*
* @api2vm
*/
final class VMExecutionEngine {
/**
* keeps Runnable objects of the shutdown sequence
*/
private static Vector<Runnable> shutdownActions = new Vector<Runnable>();
/**
* This class is not supposed to be instantiated.
*/
private VMExecutionEngine() {
}
/**
* Terminates a Virtual Machine with possible invocation of finilization
* methods. This method is used by the {@link Runtime#exit(int)
* Runtime.exit(int status)} and {@link Runtime#halt(int)
* Runtime.halt(int satus)} methods implementation. When it is called by the
* <code>Runtime.exit(int status)</code> method all shutdown hook threads
* should have been already finished. The needFinilization argument must
* be true if uninvoked finilizers should be called on VM exit. The
* implementation simply calls the
* {@link VMExecutionEngine#exit(int, boolean, Runnable[])
* VMExecutionEngine.exit(int status, boolean needFinalization,
* Runnable[] shutdownSequence)} method with an array of
* <code>Runnable</code> objects which were registered before by means of
* the {@link VMExecutionEngine#registerShutdownAction(Runnable)
* VMExecutionEngine.registerShutdownAction(Runnable action)} method.
*
* @param status exit status
* @param needFinalize specifies that finalization must be performed. If
* true then it perfoms finalization of all not finalized objects
* that have finalizers
* @api2vm
*/
static void exit(int status, boolean needFinalization) {
exit(status, needFinalization, shutdownActions.toArray(new Runnable[0]));
}
/**
* Call to this method forces VM to
* <ol>
* <li> Execute uninvoked finilizers if needFinalization is true </li>
* <li> Forcibly stop all running non-system threads
* <li> Sequentially execute the <code>run</code> method for each object
* of the shutdownSequence array. The execution starts from the last
* element of the array. No threads will be created to perform
* execution. If uncatched exception occurs it's stack trace is
* printed to the error stream and the next element of the array if
* any will be executed
* <li> Exit
* </ol>
*
* @param status exit status
* @param needFinalization indicates that finilization should be performed
* @param shutdownSequence array of shutdown actions
* @api2vm
*/
private static native void exit(int status, boolean needFinalization,
Runnable[] shutdownSequence);
/**
* This method provides an information about the assertion status specified
* via command line options.
* <p>
*
* @see java.lang.Class#desiredAssertionStatus()
*
* @param clss the class to be initialized with the assertion status. Note,
* assertion status is applicable to top-level classes only, therefore
* any member/local class passed is a subject to conversion to corresponding
* top-level declaring class. Also, <code>null</code> argument can be used to
* check if any assertion was specified through command line options.
* @param recursive controls whether this method should check exact match
* with name of the class, or check (super)packages recursively
* (most specific one has precedence).
* @param defaultStatus if no specific package setting found,
* this value may override command-line defaults. This parameter is
* actual only when <code>recursive == true</code>.
* @see java.lang.ClassLoader#setDefaultAssertionStatus(boolean)
* @return 0 - unspecified, < 0 - false, > 0 - true
* @api2vm
*/
static native int getAssertionStatus(Class clss, boolean recursive,
int defaultStatus);
/**
* This method satisfies the requirements of the specification for the
* {@link Runtime#availableProcessors() Runtime.availableProcessors()}
* method.
* @api2vm
*/
static native int getAvailableProcessors();
/**
* This method satisfies the requirements of the specification for the
* {@link System#getProperties() System.getProperties()} method.
* <p>
* Additionally a class library implementation may relay on existance of
* the following properties "vm.boot.class.path" & "vm.boot.library.path".
* The "vm.boot.class.path" property can be used to load classes and
* resources which reside in the bootstrap sequence of the VM.
* The "vm.boot.library.path" property can be used to find libraries that
* should be obtatined by classes which were loaded by bootstrap class loader.
* @api2vm
*/
static native Properties getProperties();
/**
* Adds the specified action to the list of shutdown actions. The
* {@link Runnable#run() Runnable.run()} method of the specified action
* object is executed after all non-system threads have been stopped. Last
* registered action is executed before previously registered actions. Each
* action should not create threads inside. It is expected that registered
* actions doesn't requre a lot of time to complete.
* <p>
* Typicily one may use this method to close open files, connections etc. on
* Virtual Machine exit
* @param action action which should be performed on VM exit
* @api2vm
*/
public static void registerShutdownAction(Runnable action) {
shutdownActions.add(action);
}
/**
* This method satisfies the requirements of the specification for the
* {@link Runtime#traceInstructions(boolean)
* Runtime.traceInstructions(boolean on)} method.
* @api2vm
*/
static native void traceInstructions(boolean enable);
/**
* This method satisfies the requirements of the specification for the
* {@link Runtime#traceMethodCalls(boolean)
* Runtime.traceMethodCalls(boolean on)} method.
* @api2vm
*/
static native void traceMethodCalls(boolean enable);
/**
* Returns the current system time in milliseconds since
* the Unix epoch (midnight, 1 Jan, 1970).
* @api2vm
*/
static native long currentTimeMillis();
/**
* Returns the current value of a system timer with the best accuracy
* the OS can provide, in nanoseconds.
* @api2vm
*/
static native long nanoTime();
/**
* Returns platform-specific name of the specified library.
* @api2vm
*/
static native String mapLibraryName(String libname);
}
| gpl-2.0 |
mviitanen/marsmod | mcp/src/minecraft_server/net/minecraft/world/WorldServerMulti.java | 924 | package net.minecraft.world;
import net.minecraft.profiler.Profiler;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.storage.DerivedWorldInfo;
import net.minecraft.world.storage.ISaveHandler;
public class WorldServerMulti extends WorldServer
{
private static final String __OBFID = "CL_00001430";
public WorldServerMulti(MinecraftServer p_i45283_1_, ISaveHandler p_i45283_2_, String p_i45283_3_, int p_i45283_4_, WorldSettings p_i45283_5_, WorldServer p_i45283_6_, Profiler p_i45283_7_)
{
super(p_i45283_1_, p_i45283_2_, p_i45283_3_, p_i45283_4_, p_i45283_5_, p_i45283_7_);
this.mapStorage = p_i45283_6_.mapStorage;
this.worldScoreboard = p_i45283_6_.getScoreboard();
this.worldInfo = new DerivedWorldInfo(p_i45283_6_.getWorldInfo());
}
/**
* Saves the chunks to disk.
*/
protected void saveLevel() throws MinecraftException {}
}
| gpl-2.0 |
yaogdu/spring-oauth-server | src/test/java/com/monkeyk/sos/TestApplicationContextInitializer.java | 864 | package com.monkeyk.sos;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.io.ClassPathResource;
/**
* @author Shengzhao Li
*/
public class TestApplicationContextInitializer implements ApplicationContextInitializer<AbstractApplicationContext> {
@Override
public void initialize(AbstractApplicationContext applicationContext) {
PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
//load test.properties
propertyPlaceholderConfigurer.setLocation(new ClassPathResource("test.properties"));
applicationContext.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);
}
} | gpl-2.0 |
Debian/openjfx | modules/base/src/main/java/javafx/beans/binding/Binding.java | 4464 | /*
* Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javafx.beans.binding;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import com.sun.javafx.collections.annotations.ReturnsUnmodifiableCollection;
/**
* A {@code Binding} calculates a value that depends on one or more sources. The
* sources are usually called the dependency of a binding. A binding observes
* its dependencies for changes and updates its value automatically.
* <p>
* While a dependency of a binding can be anything, it is almost always an
* implementation of {@link javafx.beans.value.ObservableValue}. {@code Binding}
* implements {@code ObservableValue} allowing to use it in another binding.
* With that one can assemble very complex bindings from simple bindings.
* <p>
* All bindings in the JavaFX runtime are calculated lazily. That means, if
* a dependency changes, the result of a binding is not immediately
* recalculated, but it is marked as invalid. Next time the value of an invalid
* binding is requested, it is recalculated.
* <p>
* It is recommended to use one of the base classes defined in this package
* (e.g. {@link DoubleBinding}) to define a custom binding, because these
* classes already provide most of the needed functionality. See
* {@link DoubleBinding} for an example.
*
* @see DoubleBinding
*
*
* @since JavaFX 2.0
*/
public interface Binding<T> extends ObservableValue<T> {
/**
* Checks if a binding is valid.
*
* @return {@code true} if the {@code Binding} is valid, {@code false}
* otherwise
*/
boolean isValid();
/**
* Mark a binding as invalid. This forces the recalculation of the value of
* the {@code Binding} next time it is request.
*/
void invalidate();
/**
* Returns the dependencies of a binding in an unmodifiable
* {@link javafx.collections.ObservableList}. The implementation is
* optional. The main purpose of this method is to support developers during
* development. It allows to explore and monitor dependencies of a binding
* during runtime.
* <p>
* Because this method should not be used in production code, it is
* recommended to implement this functionality as sparse as possible. For
* example if the dependencies do not change, each call can generate a new
* {@code ObservableList}, avoiding the necessity to store the result.
*
* @return an unmodifiable {@code} ObservableList of the dependencies
*/
@ReturnsUnmodifiableCollection
ObservableList<?> getDependencies();
/**
* Signals to the {@code Binding} that it will not be used anymore and any
* references can be removed. A call of this method usually results in the
* binding stopping to observe its dependencies by unregistering its
* listener(s). The implementation is optional.
* <p>
* All bindings in our implementation use instances of
* {@link javafx.beans.WeakInvalidationListener}, which means usually
* a binding does not need to be disposed. But if you plan to use your
* application in environments that do not support {@code WeakReferences}
* you have to dispose unused {@code Bindings} to avoid memory leaks.
*/
void dispose();
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest02153.java | 2598 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest02153")
public class BenchmarkTest02153 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar;
String guess = "ABC";
char switchTarget = guess.charAt(2);
// Simple case statement that assigns param to bar on conditions 'A' or 'C'
switch (switchTarget) {
case 'A':
bar = param;
break;
case 'B':
bar = "bobs_your_uncle";
break;
case 'C':
case 'D':
bar = param;
break;
default:
bar = "bobs_your_uncle";
break;
}
String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='"+ bar +"'";
try {
java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
java.sql.PreparedStatement statement = connection.prepareStatement( sql, new int[] { 1, 2 } );
statement.setString(1, "foo");
statement.execute();
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
}
}
| gpl-2.0 |
rfdrake/opennms | opennms-config-model/src/main/java/org/opennms/netmgt/config/datacollection/descriptors/ResourceTypeDescriptor.java | 14818 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
/*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.1.2.1</a>, using an XML
* Schema.
* $Id$
*/
package org.opennms.netmgt.config.datacollection.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.opennms.netmgt.config.datacollection.ResourceType;
/**
* Class ResourceTypeDescriptor.
*
* @version $Revision$ $Date$
*/
@SuppressWarnings("all") public class ResourceTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ResourceTypeDescriptor() {
super();
_nsURI = "http://xmlns.opennms.org/xsd/config/datacollection";
_xmlName = "resourceType";
_elementDefinition = true;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _name
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_name", "name", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ResourceType target = (ResourceType) object;
return target.getName();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ResourceType target = (ResourceType) object;
target.setName( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _name
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _label
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_label", "label", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ResourceType target = (ResourceType) object;
return target.getLabel();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ResourceType target = (ResourceType) object;
target.setLabel( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _label
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _resourceLabel
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_resourceLabel", "resourceLabel", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ResourceType target = (ResourceType) object;
return target.getResourceLabel();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ResourceType target = (ResourceType) object;
target.setResourceLabel( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _resourceLabel
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _persistenceSelectorStrategy
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.PersistenceSelectorStrategy.class, "_persistenceSelectorStrategy", "persistenceSelectorStrategy", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ResourceType target = (ResourceType) object;
return target.getPersistenceSelectorStrategy();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ResourceType target = (ResourceType) object;
target.setPersistenceSelectorStrategy( (org.opennms.netmgt.config.datacollection.PersistenceSelectorStrategy) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.PersistenceSelectorStrategy();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.PersistenceSelectorStrategy");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _persistenceSelectorStrategy
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _storageStrategy
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.opennms.netmgt.config.datacollection.StorageStrategy.class, "_storageStrategy", "storageStrategy", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ResourceType target = (ResourceType) object;
return target.getStorageStrategy();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ResourceType target = (ResourceType) object;
target.setStorageStrategy( (org.opennms.netmgt.config.datacollection.StorageStrategy) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.opennms.netmgt.config.datacollection.StorageStrategy();
}
};
desc.setSchemaType("org.opennms.netmgt.config.datacollection.StorageStrategy");
desc.setHandler(handler);
desc.setNameSpaceURI("http://xmlns.opennms.org/xsd/config/datacollection");
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _storageStrategy
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class<?> getJavaClass(
) {
return org.opennms.netmgt.config.datacollection.ResourceType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
@Override
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/langtools/test/tools/javac/ConditionalWithVoid.java | 1466 | /*
* Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4974927
* @summary The compiler was allowing void types in its parsing of conditional expressions.
* @author tball
*
* @compile/fail ConditionalWithVoid.java
*/
public class ConditionalWithVoid {
public int test(Object o) {
// Should fail to compile since Object.wait() has a void return type.
System.out.println(o instanceof String ? o.hashCode() : o.wait());
}
}
| gpl-2.0 |
RangerRick/opennms | opennms-services/src/main/java/org/opennms/netmgt/linkd/snmp/QBridgeDot1dTpFdbTable.java | 2309 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) 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.
*
* OpenNMS(R) 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 OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.netmgt.linkd.snmp;
import java.net.InetAddress;
import org.opennms.netmgt.snmp.SnmpInstId;
import org.opennms.netmgt.snmp.SnmpObjId;
/**
* <P>Dot1DBaseTable uses a SnmpSession to collect the QBridge.forwarding table entries
* It implements the SnmpHandler to receive notifications when a reply is
* received/error occurs in the SnmpSession used to send requests/receive
* replies.</P>
*
* @author <A HREF="mailto:rssntn67@yahoo.it">Antonio Russo</A>
* @see <A HREF="http://www.ietf.org/rfc/rfc1213.txt">RFC1213</A>
* @version $Id: $
*/
public class QBridgeDot1dTpFdbTable extends SnmpTable<QBridgeDot1dTpFdbTableEntry> {
/**
* <p>Constructor for QBridgeDot1dTpFdbTable.</p>
*
* @param address a {@link java.net.InetAddress} object.
*/
public QBridgeDot1dTpFdbTable(InetAddress address) {
super(address, "qBridgedot1dTpFdbTable", QBridgeDot1dTpFdbTableEntry.ms_elemList);
}
/** {@inheritDoc} */
protected QBridgeDot1dTpFdbTableEntry createTableEntry(SnmpObjId base, SnmpInstId inst, Object val) {
return new QBridgeDot1dTpFdbTableEntry();
}
}
| gpl-2.0 |
AKSW/LIMES-CORE | limes-core/src/main/java/org/aksw/limes/core/execution/engine/filter/IFilter.java | 4615 | package org.aksw.limes.core.execution.engine.filter;
import org.aksw.limes.core.io.cache.ACache;
import org.aksw.limes.core.io.mapping.AMapping;
/**
* Implements the filter interface.
*
* @author Axel-C. Ngonga Ngomo (ngonga@informatik.uni-leipzig.de)
* @author Kleanthi Georgala (georgala@informatik.uni-leipzig.de)
* @version 1.0
*/
public interface IFilter {
/**
* Naive filter function for mapping using a threshold as filtering
* criterion.
*
* @param map
* Map bearing the results of Link Specification
* @param threshold
* Value of threshold
* @return a filtered mapping that satisfies sim {@literal >}= threshold
*/
public AMapping filter(AMapping map, double threshold);
/**
* Filter function for mapping using a condition and a threshold as
* filtering criterion.
*
* @param map
* Map bearing the results of Link Specification
* @param condition
* The condition for filtering
* @param threshold
* Value of threshold
* @param source
* Source knowledge base
* @param target
* Target knowledge base
* @param sourceVar
* Source property
* @param targetVar
* Target property
* @return a filtered mapping that satisfies both the condition and the
* threshold
*/
public AMapping filter(AMapping map, String condition, double threshold, ACache source, ACache target,
String sourceVar, String targetVar);
/**
* Filter function for mapping using a condition and two thresholds as
* filtering criterion.
*
* @param map
* map bearing the results of Link Specification
* @param condition
* The condition for filtering
* @param threshold
* Value of the first threshold
* @param mainThreshold
* Value of second threshold
* @param source
* Source knowledge base
* @param target
* Target knowledge base
* @param sourceVar
* Source property
* @param targetVar
* Target property
* @return a filtered mapping that satisfies both the condition and the
* thresholds
*/
public AMapping filter(AMapping map, String condition, double threshold, double mainThreshold, ACache source,
ACache target, String sourceVar, String targetVar);
/**
* Reverse filter function for mapping using a condition and two thresholds
* as filtering criterion.
*
* @param map
* Map bearing the results of Link Specification
* @param condition
* The condition for filtering
* @param threshold
* Value of the first threshold
* @param mainThreshold
* Value of second threshold
* @param source
* Source knowledge base
* @param target
* Target knowledge base
* @param sourceVar
* Source property
* @param targetVar
* Target property
* @return a filtered mapping that satisfies both the condition and the
* thresholds
*/
public AMapping reversefilter(AMapping map, String condition, double threshold, double mainThreshold, ACache source,
ACache target, String sourceVar, String targetVar);
/**
* Filter for linear combinations when operation is set to "add", given the
* expression a*sim1 + b*sim2 {@literal >}= t or multiplication given the
* expression (a*sim1)*(b*sim2) {@literal >}= t, which is not likely to be
* used.
*
* @param map1
* Map bearing the results of sim1 {@literal >}= (t-b)/a for add,
* sim1 {@literal >}= t/(a*b) for mult
* @param map2
* Map bearing the results of sim2 {@literal >}= (t-a)/b for add,
* sim2 {@literal >}= t/(a*b) for mult
* @param coef1
* Value of first coefficient
* @param coef2
* Value of second coefficient
* @param threshold
* Value of threshold
* @param operation
* Mathematical operation
* @return a filtered mapping that satisfies a*sim1 + b*sim2 {@literal >}= t
* for add, (a*sim1)*(b*sim2) {@literal >}= t for mult
*/
public AMapping filter(AMapping map1, AMapping map2, double coef1, double coef2, double threshold,
String operation);
}
| gpl-2.0 |
unktomi/form-follows-function | mjavac/langtools/test/tools/javadoc/generics/wildcards/Main.java | 1803 | /*
* Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4421066
* @summary Verify the contents of the ClassDoc of a generic class.
* @library ../../lib
* @compile -source 1.5 ../../lib/Tester.java Main.java
* @run main Main
*/
import java.io.IOException;
import com.sun.javadoc.*;
public class Main extends Tester.Doclet {
private static final Tester tester = new Tester("Main", "pkg1");
public static void main(String[] args) throws IOException {
tester.run();
tester.verify();
}
public static boolean start(RootDoc root) {
try {
for (ClassDoc cd : root.classes()) {
tester.printClass(cd);
}
return true;
} catch (IOException e) {
return false;
}
}
}
| gpl-2.0 |
kephale/java3d-core | src/classes/share/javax/media/j3d/InputDevice.java | 7033 | /*
* Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
*/
package javax.media.j3d;
/**
* InputDevice is the interface through which Java 3D and Java 3D
* application programs communicate with a device driver. All input
* devices that Java 3D uses must implement the InputDevice interface and
* be registered with Java 3D via a call to
* PhysicalEnvironment.addInputDevice(InputDevice). An input device
* transfers information to the Java 3D implementation and Java 3D
* applications by writing transform information to sensors that the
* device driver has created and manages. The driver can update its
* sensor information each time the pollAndProcessInput method is
* called.
*/
public interface InputDevice {
/**
* Signifies that the driver for a device is a blocking driver and that
* it should be scheduled for regular reads by Java 3D. A blocking driver
* is defined as a driver that can cause the thread accessing the driver
* (the Java 3D implementation thread calling the pollAndProcessInput
* method) to block while the data is being accessed from the driver.
*/
public static final int BLOCKING = 3;
/**
* Signifies that the driver for a device is a non-blocking driver and
* that it should be scheduled for regular reads by Java 3D. A
* non-blocking driver is defined as a driver that does not cause the
* calling thread to block while data is being retrieved from the
* driver. If no data is available from the device, pollAndProcessInput
* should return without updating the sensor read value.
*/
public static final int NON_BLOCKING = 4;
/**
* Signifies that the Java 3D implementation should not schedule
* regular reads on the sensors of this device; the Java 3D
* implementation will only call pollAndProcessInput when one of the
* device's sensors' getRead methods is called. A DEMAND_DRIVEN driver
* must always provide the current value of the sensor on demand whenever
* pollAndProcessInput is called. This means that DEMAND_DRIVEN drivers
* are non-blocking by definition.
*/
public static final int DEMAND_DRIVEN = 5;
/**
* This method initializes the device. A device should be initialized
* before it is registered with Java 3D via the
* PhysicalEnvironment.addInputDevice(InputDevice) method call.
* @return return true for succesful initialization, false for failure
*/
public abstract boolean initialize();
/**
* This method sets the device's current position and orientation as the
* devices nominal position and orientation (establish its reference
* frame relative to the "Tracker base" reference frame).
*/
public abstract void setNominalPositionAndOrientation();
/**
* This method causes the device's sensor readings to be updated by the
* device driver. For BLOCKING and NON_BLOCKING drivers, this method is
* called regularly and the Java 3D implementation can cache the sensor
* values. For DEMAND_DRIVEN drivers this method is called each time one
* of the Sensor.getRead methods is called, and is not otherwise called.
*/
public abstract void pollAndProcessInput();
/**
* This method will not be called by the Java 3D implementation and
* should be implemented as an empty method.
*/
public abstract void processStreamInput();
/**
* Code to process the clean up of the device and relinquish associated
* resources. This method should be called after the device has been
* unregistered from Java 3D via the
* PhysicalEnvironment.removeInputDevice(InputDevice) method call.
*/
public abstract void close();
/**
* This method retrieves the device's processing mode: one of BLOCKING,
* NON_BLOCKING, or DEMAND_DRIVEN. The Java 3D implementation calls
* this method when PhysicalEnvironment.addInputDevice(InputDevice) is
* called to register the device with Java 3D. If this method returns
* any value other than BLOCKING, NON_BLOCKING, or DEMAND_DRIVEN,
* addInputDevice will throw an IllegalArgumentException.
* @return Returns the devices processing mode, one of BLOCKING,
* NON_BLOCKING, or DEMAND_DRIVEN
*/
public abstract int getProcessingMode();
/**
* This method sets the device's processing mode to one of: BLOCKING,
* NON_BLOCKING, or DEMAND_DRIVEN. Many drivers will be written to run
* in only one mode. Applications using such drivers should not attempt
* to set the processing mode. This method should throw an
* IllegalArgumentException if there is an attempt to set the processing
* mode to anything other than the aforementioned three values.
*
* <p>
* NOTE: this method should <i>not</i> be called after the input
* device has been added to a PhysicalEnvironment. The
* processingMode must remain constant while a device is attached
* to a PhysicalEnvironment.
*
* @param mode One of BLOCKING, NON_BLOCKING, or DEMAND_DRIVEN
*/
public abstract void setProcessingMode(int mode);
/**
* This method gets the number of sensors associated with the device.
* @return the device's sensor count.
*/
public int getSensorCount();
/**
* Gets the specified Sensor associated with the device. Each InputDevice
* implementation is responsible for creating and managing its own set of
* sensors. The sensor indices begin at zero and end at number of
* sensors minus one. Each sensor should have had
* Sensor.setDevice(InputDevice) set properly before addInputDevice
* is called.
* @param sensorIndex the sensor to retrieve
* @return Returns the specified sensor.
*/
public Sensor getSensor(int sensorIndex);
}
| gpl-2.0 |
FauxFaux/jdk9-jaxws | src/java.xml.ws/share/classes/com/sun/xml/internal/messaging/saaj/soap/ver1_1/Header1_1Impl.java | 3584 | /*
* Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @author SAAJ RI Development Team
*/
package com.sun.xml.internal.messaging.saaj.soap.ver1_1;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import com.sun.xml.internal.messaging.saaj.soap.SOAPDocument;
import com.sun.xml.internal.messaging.saaj.soap.SOAPDocumentImpl;
import com.sun.xml.internal.messaging.saaj.soap.impl.HeaderImpl;
import com.sun.xml.internal.messaging.saaj.soap.name.NameImpl;
import com.sun.xml.internal.messaging.saaj.util.LogDomainConstants;
public class Header1_1Impl extends HeaderImpl {
protected static final Logger log =
Logger.getLogger(LogDomainConstants.SOAP_VER1_1_DOMAIN,
"com.sun.xml.internal.messaging.saaj.soap.ver1_1.LocalStrings");
public Header1_1Impl(SOAPDocumentImpl ownerDocument, String prefix) {
super(ownerDocument, NameImpl.createHeader1_1Name(prefix));
}
protected NameImpl getNotUnderstoodName() {
log.log(
Level.SEVERE,
"SAAJ0301.ver1_1.hdr.op.unsupported.in.SOAP1.1",
new String[] { "getNotUnderstoodName" });
throw new UnsupportedOperationException("Not supported by SOAP 1.1");
}
protected NameImpl getUpgradeName() {
return NameImpl.create(
"Upgrade",
getPrefix(),
SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE);
}
protected NameImpl getSupportedEnvelopeName() {
return NameImpl.create(
"SupportedEnvelope",
getPrefix(),
SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE);
}
public SOAPHeaderElement addNotUnderstoodHeaderElement(QName name)
throws SOAPException {
log.log(
Level.SEVERE,
"SAAJ0301.ver1_1.hdr.op.unsupported.in.SOAP1.1",
new String[] { "addNotUnderstoodHeaderElement" });
throw new UnsupportedOperationException("Not supported by SOAP 1.1");
}
protected SOAPHeaderElement createHeaderElement(Name name) {
return new HeaderElement1_1Impl(
((SOAPDocument) getOwnerDocument()).getDocument(),
name);
}
protected SOAPHeaderElement createHeaderElement(QName name) {
return new HeaderElement1_1Impl(
((SOAPDocument) getOwnerDocument()).getDocument(),
name);
}
}
| gpl-2.0 |
FireSight/GoonWars | src/server/campaign/commands/admin/AdminSetCommandLevelCommand.java | 2263 | /*
* MekWars - Copyright (C) 2004
*
* Derived from MegaMekNET (http://www.sourceforge.net/projects/megameknet)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package server.campaign.commands.admin;
import java.util.Hashtable;
import java.util.StringTokenizer;
import server.MWChatServer.auth.IAuthenticator;
import server.campaign.CampaignMain;
import server.campaign.commands.Command;
public class AdminSetCommandLevelCommand implements Command {
int accessLevel = IAuthenticator.ADMIN;
String syntax = "Command#Level";
public int getExecutionLevel(){return accessLevel;}
public void setExecutionLevel(int i) {accessLevel = i;}
public String getSyntax() { return syntax;}
public void process(StringTokenizer command,String Username) {
//access level check
int userLevel = CampaignMain.cm.getServer().getUserLevel(Username);
if(userLevel < getExecutionLevel()) {
CampaignMain.cm.toUser("AM:Insufficient access level for command. Level: " + userLevel + ". Required: " + accessLevel + ".",Username,true);
return;
}
Hashtable<String,Command> commandTable = CampaignMain.cm.getServerCommands();
String commandName = command.nextToken().toUpperCase();
int commandLevel = Integer.parseInt(command.nextToken());
if ( commandTable.containsKey(commandName) )
commandTable.get(commandName).setExecutionLevel(commandLevel);
else{
CampaignMain.cm.toUser("Command "+commandName+" not found!",Username,true);
return;
}
CampaignMain.cm.toUser("Command level changed on "+commandName.toLowerCase()+" to "+commandLevel,Username,true);
CampaignMain.cm.doSendModMail("NOTE",Username + " has changed the command level for "+commandName.toLowerCase()+" to "+commandLevel);
}
} | gpl-2.0 |
robymus/jabref | src/main/java/net/sf/jabref/groups/GroupTreeCellRenderer.java | 7365 | /* Copyright (C) 2003-2011 JabRef contributors.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package net.sf.jabref.groups;
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;
import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.model.entry.BibtexEntry;
import net.sf.jabref.Globals;
import net.sf.jabref.JabRef;
import net.sf.jabref.JabRefPreferences;
import net.sf.jabref.groups.structure.*;
import net.sf.jabref.logic.util.strings.StringUtil;
/**
* Renders a GroupTreeNode using its group's getName() method, rather that its
* toString() method.
*
* @author jzieren
*/
public class GroupTreeCellRenderer extends DefaultTreeCellRenderer {
private static final int MAX_DISPLAYED_LETTERS = 35;
/** The cell over which the user is currently dragging */
private Object highlight1Cell;
private Object[] highlight2Cells;
private Object[] highlight3Cells;
private Object highlightBorderCell;
private static final ImageIcon
groupRefiningIcon = IconTheme.getImage("groupRefining");
private static final ImageIcon groupIncludingIcon = IconTheme.getImage("groupIncluding");
private static final ImageIcon groupRegularIcon = null;
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if (value == highlight1Cell)
{
selected = true; // show as selected
}
Component c = super.getTreeCellRendererComponent(tree, value, selected,
expanded, leaf, row, hasFocus);
// this is sometimes called from deep within somewhere, with a dummy
// value (probably for layout etc.), so we've got to check here!
if (!(value instanceof GroupTreeNode)) {
return c;
}
AbstractGroup group = ((GroupTreeNode) value).getGroup();
if (group == null || !(c instanceof JLabel))
{
return c; // sanity check
}
JLabel label = (JLabel) c;
if (highlightBorderCell != null && highlightBorderCell == value) {
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
} else {
label.setBorder(BorderFactory.createEmptyBorder());
}
boolean italics = Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_DYNAMIC)
&& group.isDynamic();
boolean red = false;
if (highlight2Cells != null) {
for (Object highlight2Cell : highlight2Cells) {
if (highlight2Cell == value) {
// label.setForeground(Color.RED);
red = true;
break;
}
}
}
boolean underline = false;
if (highlight3Cells != null) {
for (Object highlight3Cell : highlight3Cells) {
if (highlight3Cell == value) {
underline = true;
break;
}
}
}
String name = group.getName();
if (name.length() > GroupTreeCellRenderer.MAX_DISPLAYED_LETTERS) {
name = name.substring(0, GroupTreeCellRenderer.MAX_DISPLAYED_LETTERS - 2) + "...";
}
StringBuilder sb = new StringBuilder();
sb.append("<html>");
if (red) {
sb.append("<font color=\"#FF0000\">");
}
if (underline) {
sb.append("<u>");
}
if (italics) {
sb.append("<i>");
}
sb.append(StringUtil.quoteForHTML(name));
if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_NUMBER_OF_ELEMENTS)) {
if (group instanceof ExplicitGroup) {
sb.append(" [").append(((ExplicitGroup) group).getNumEntries()).append("]");
} else if (group instanceof KeywordGroup || group instanceof SearchGroup) {
int hits = 0;
for (BibtexEntry entry : JabRef.jrf.basePanel().getDatabase().getEntries()) {
if (group.contains(entry)) {
hits++;
}
}
sb.append(" [").append(hits).append("]");
}
}
if (italics) {
sb.append("</i>");
}
if (underline) {
sb.append("</u>");
}
if (red) {
sb.append("</font>");
}
sb.append("</html>");
final String text = sb.toString();
if (!label.getText().equals(text)) {
label.setText(text);
}
label.setToolTipText("<html>" + group.getShortDescription() + "</html>");
if (Globals.prefs.getBoolean(JabRefPreferences.GROUP_SHOW_ICONS)) {
switch (group.getHierarchicalContext()) {
case REFINING:
if (label.getIcon() != GroupTreeCellRenderer.groupRefiningIcon) {
label.setIcon(GroupTreeCellRenderer.groupRefiningIcon);
}
break;
case INCLUDING:
if (label.getIcon() != GroupTreeCellRenderer.groupIncludingIcon) {
label.setIcon(GroupTreeCellRenderer.groupIncludingIcon);
}
break;
default:
if (label.getIcon() != GroupTreeCellRenderer.groupRegularIcon) {
label.setIcon(GroupTreeCellRenderer.groupRegularIcon);
}
break;
}
} else {
label.setIcon(null);
}
return c;
}
/**
* For use when dragging: The sepcified cell is always rendered as selected.
*
* @param cell
* The cell over which the user is currently dragging.
*/
void setHighlight1Cell(Object cell) {
this.highlight1Cell = cell;
}
/**
* Highlights the specified cells (in red), or disables highlight if cells ==
* null.
*/
void setHighlight2Cells(Object[] cells) {
this.highlight2Cells = cells;
}
/**
* Highlights the specified cells (by unterlining), or disables highlight if
* cells == null.
*/
void setHighlight3Cells(Object[] cells) {
this.highlight3Cells = cells;
}
/**
* Highlights the specified cells (by drawing a border around it),
* or disables highlight if highlightBorderCell == null.
*/
void setHighlightBorderCell(Object highlightBorderCell) {
this.highlightBorderCell = highlightBorderCell;
}
}
| gpl-2.0 |
universsky/openjdk | jdk/src/jdk.localedata/share/classes/sun/text/resources/en/AU/FormatData_en_AU.java | 2887 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package sun.text.resources.en.AU;
import sun.util.resources.ParallelListResourceBundle;
public class FormatData_en_AU extends ParallelListResourceBundle {
/**
* Overrides ParallelListResourceBundle
*/
protected final Object[][] getContents() {
return new Object[][] {
{ "TimePatterns",
new String[] {
"h:mm:ss a z", // full time pattern
"h:mm:ss a", // long time pattern
"h:mm:ss a", // medium time pattern
"h:mm a", // short time pattern
}
},
{ "DatePatterns",
new String[] {
"EEEE, d MMMM yyyy", // full date pattern
"d MMMM yyyy", // long date pattern
"dd/MM/yyyy", // medium date pattern
"d/MM/yy", // short date pattern
}
},
{ "DateTimePatterns",
new String[] {
"{1} {0}" // date-time pattern
}
},
};
}
}
| gpl-2.0 |
smarr/Truffle | compiler/src/org.graalvm.compiler.printer/src/org/graalvm/compiler/printer/NoDeadCodeVerifyHandler.java | 4104 | /*
* Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.printer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.graalvm.compiler.debug.DebugContext;
import org.graalvm.compiler.debug.DebugVerifyHandler;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.graph.Node;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.options.Option;
import org.graalvm.compiler.options.OptionKey;
import org.graalvm.compiler.options.OptionType;
import org.graalvm.compiler.options.OptionValues;
import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
/**
* Verifies that graphs have no dead code.
*/
public class NoDeadCodeVerifyHandler implements DebugVerifyHandler {
// The options below will be removed once all phases clean up their own dead code.
private static final int OFF = 0;
private static final int INFO = 1;
private static final int VERBOSE = 2;
private static final int FATAL = 3;
static class Options {
// @formatter:off
@Option(help = "Run level for NoDeadCodeVerifyHandler (0 = off, 1 = info, 2 = verbose, 3 = fatal)", type = OptionType.Debug)
public static final OptionKey<Integer> NDCV = new OptionKey<>(0);
// @formatter:on
}
/**
* Only the first instance of failure at any point is shown. This will also be removed once all
* phases clean up their own dead code.
*/
private static final Map<String, Boolean> discovered = new ConcurrentHashMap<>();
@Override
public void verify(DebugContext debug, Object object, String format, Object... args) {
OptionValues options = debug.getOptions();
if (Options.NDCV.getValue(options) != OFF && object instanceof StructuredGraph) {
StructuredGraph graph = (StructuredGraph) object;
List<Node> before = graph.getNodes().snapshot();
new DeadCodeEliminationPhase().run(graph);
List<Node> after = graph.getNodes().snapshot();
assert after.size() <= before.size();
if (before.size() != after.size()) {
if (discovered.put(format, Boolean.TRUE) == null) {
before.removeAll(after);
String prefix = format == null ? "" : format + ": ";
GraalError error = new GraalError("%sfound dead nodes in %s: %s", prefix, graph, before);
if (Options.NDCV.getValue(options) == INFO) {
System.out.println(error.getMessage());
} else if (Options.NDCV.getValue(options) == VERBOSE) {
error.printStackTrace(System.out);
} else {
assert Options.NDCV.getValue(options) == FATAL;
throw error;
}
}
}
}
}
}
| gpl-2.0 |
jeffgdotorg/opennms | core/ipc/rpc/kafka/src/test/java/org/opennms/core/ipc/rpc/kafka/MockMinionIdentity.java | 1793 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2018 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2018 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.core.ipc.rpc.kafka;
import org.opennms.distributed.core.api.MinionIdentity;
import org.opennms.distributed.core.api.SystemType;
public class MockMinionIdentity implements MinionIdentity {
private final String location;
public MockMinionIdentity(String location) {
this.location = location;
}
@Override
public String getId() {
return "minionId";
}
@Override
public String getLocation() {
return location;
}
@Override
public String getType() {
return SystemType.Minion.name();
}
}
| gpl-2.0 |
jesusrodrc/opencga | opencga-lib/src/main/java/org/opencb/opencga/lib/analysis/exec/SingleProcess.java | 3366 | package org.opencb.opencga.lib.analysis.exec;
import org.bioinfo.commons.log.Logger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleProcess {
private Logger logger;
private RunnableProcess runnableProcess;
private ExecutorService execSvc;
private int timeout;
public SingleProcess() {
logger = new Logger("org.bioinfo.exec");
timeout = 0;
}
public SingleProcess(RunnableProcess obj) {
this();
this.setRunnableProcess(obj);
getRunnableProcess().setStatus(RunnableProcess.Status.WAITING);
}
public void runSync() {
execSvc = Executors.newSingleThreadExecutor();
execSvc.execute(getRunnableProcess());
execSvc.shutdown();
waitFor();
}
public void runAsync() {
execSvc = Executors.newSingleThreadExecutor();
execSvc.execute(getRunnableProcess());
execSvc.shutdown();
}
public void kill() {
if (!execSvc.isTerminated()) {
getRunnableProcess().setStatus(RunnableProcess.Status.KILLED);
runnableProcess.destroy();
execSvc.shutdownNow();
getRunnableProcess().setEndTime(System.currentTimeMillis());
getRunnableProcess().setExitValue(-1);
getRunnableProcess().setError("Aborted by the user");
}
}
public void waitFor() {
long currentTime = 0;
try {
while (!execSvc.isTerminated()) {
Thread.sleep(500);
if (getTimeout() > 0 && currentTime > getTimeout()) {
kill();
getRunnableProcess().setStatus(RunnableProcess.Status.TIMEOUT);
getRunnableProcess().setError("Timeout error");
break;
}
currentTime = System.currentTimeMillis() - getRunnableProcess().getStartTime();
}
} catch (InterruptedException e) {
logger.error(e.toString());
}
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Execution time: ").append(getRunnableProcess().getDuration()).append(System.getProperty("line.separator"));
sb.append("Output: ").append(getRunnableProcess().getOutput()).append(System.getProperty("line.separator"));
sb.append("Error: ").append(getRunnableProcess().getError()).append(System.getProperty("line.separator"));
sb.append("ExitValue: ").append(getRunnableProcess().getExitValue()).append(System.getProperty("line.separator"));
sb.append("Status: ").append(getRunnableProcess().getStatus()).append(System.getProperty("line.separator"));
return sb.toString();
}
/**
* @param timeout the timeout to set
*/
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* @return the timeout
*/
public int getTimeout() {
return timeout;
}
/**
* @param runnableProcess the runnableProcess to set
*/
public void setRunnableProcess(RunnableProcess runnableProcess) {
this.runnableProcess = runnableProcess;
}
/**
* @return the runnableProcess
*/
public RunnableProcess getRunnableProcess() {
return runnableProcess;
}
}
| gpl-2.0 |
dwango/quercus | src/main/java/com/caucho/quercus/marshal/JavaMapMarshal.java | 2930 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.marshal;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.JavaListAdapter;
import com.caucho.quercus.env.JavaMapAdapter;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.program.JavaClassDef;
import com.caucho.util.L10N;
/**
* Code for marshalling arguments.
*/
public class JavaMapMarshal extends JavaMarshal {
private static final L10N L = new L10N(JavaMarshal.class);
public JavaMapMarshal(JavaClassDef def,
boolean isNotNull)
{
this(def, isNotNull, false);
}
public JavaMapMarshal(JavaClassDef def,
boolean isNotNull,
boolean isUnmarshalNullAsFalse)
{
super(def, isNotNull, isUnmarshalNullAsFalse);
}
public Object marshal(Env env, Value value, Class argClass)
{
if (! value.isset()) {
if (_isNotNull) {
env.warning(L.l("null is an unexpected argument, expected {0}",
shortName(argClass)));
}
return null;
}
Object obj = value.toJavaMap(env, argClass);
if (obj == null) {
if (_isNotNull) {
env.warning(L.l("null is an unexpected argument, expected {0}",
shortName(argClass)));
}
return null;
}
else if (! argClass.isAssignableFrom(obj.getClass())) {
env.warning(L.l(
"'{0}' of type '{1}' is an unexpected argument, expected {2}",
value,
shortName(value.getClass()),
shortName(argClass)));
return null;
}
return obj;
}
@Override
protected int getMarshalingCostImpl(Value argValue)
{
if (argValue instanceof JavaMapAdapter
&& getExpectedClass()
.isAssignableFrom(argValue.toJavaObject().getClass()))
return Marshal.ZERO;
else if (argValue.isArray())
return Marshal.THREE;
else
return Marshal.FOUR;
}
}
| gpl-2.0 |
smalyshev/blazegraph | bigdata/src/java/com/bigdata/striterator/Filter.java | 6913 | /*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Aug 7, 2008
*/
package com.bigdata.striterator;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import cutthecrap.utils.striterators.ICloseableIterator;
/**
* Element-at-a-time filter with generics.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
* @param <I>
* The generic type of the iterator.
* @param <E>
* The generic type of the elements visited by the iterator.
*/
abstract public class Filter<I extends Iterator<E>,E> implements IFilter<I,E,E> {
/**
*
*/
private static final long serialVersionUID = 1L;
private final int chunkSize;
protected Object state;
public Filter() {
this( null );
}
public Filter(Object state) {
this(IChunkedIterator.DEFAULT_CHUNK_SIZE, state);
}
public Filter(int chunkSize, Object state) {
this.chunkSize = chunkSize;
this.state = state;
}
// @SuppressWarnings("unchecked")
public IChunkedIterator<E> filter(I src) {
return new FilteredIterator<I, E>(chunkSize, src, this);
}
/**
* Return <code>true</code> iff the element should be visited.
*
* @param e
* The element.
*/
abstract protected boolean isValid(E e);
/**
* Applies filter to the source iterator.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
* @param <I>
* @param <E>
*/
private static class FilteredIterator<I extends Iterator<E>, E> implements
IChunkedIterator<E> {
/** The source iterator. */
private final I src;
/** The filter. */
private final Filter<I, E> filter;
/** One step lookahead. */
private E next;
/** The chunk size. */
private final int chunkSize;
/** <code>null</code> unless the source iterator is ordered. */
private final IKeyOrder<E> keyOrder;
/**
* @param chunkSize The chunk size.
* @param src
* The source iterator.
* @param filter
* The filter.
*/
public FilteredIterator(int chunkSize, I src, Filter<I, E> filter) {
this.chunkSize = chunkSize;
this.src = src;
this.filter = filter;
if(src instanceof IChunkedOrderedIterator<?>) {
keyOrder = ((IChunkedOrderedIterator<E>) src).getKeyOrder();
} else {
keyOrder = null;
}
}
public boolean hasNext() {
if (next != null)
return true;
while(src.hasNext()) {
final E e = src.next();
if(filter.isValid(e)) {
next = e;
return true;
}
}
return false;
}
public E next() {
if (!hasNext())
throw new NoSuchElementException();
final E tmp = next;
next = null;
return tmp;
}
/**
* Not supported since the one-step lookahead means that we would have
* to delete the previous element from the source.
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* The next chunk of elements in whatever order the were visited by
* {@link #next()}.
*/
@SuppressWarnings("unchecked")
public E[] nextChunk() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int n = 0;
E[] chunk = null;
while (hasNext() && n < chunkSize) {
E t = next();
if (chunk == null) {
/*
* Dynamically instantiation an array of the same component type
* as the objects that we are visiting.
*/
chunk = (E[]) java.lang.reflect.Array.newInstance(t.getClass(),
chunkSize);
}
// add to this chunk.
chunk[n++] = t;
}
if (n != chunkSize) {
// make it dense.
E[] tmp = (E[])java.lang.reflect.Array.newInstance(
// chunk[0].getClass(),
chunk.getClass().getComponentType(),//
n);
System.arraycopy(chunk, 0, tmp, 0, n);
chunk = tmp;
}
return chunk;
}
/**
* The {@link IKeyOrder} iff the source iterator implements
* {@link IChunkedOrderedIterator}.
*/
public IKeyOrder<E> getKeyOrder() {
return keyOrder;
}
public E[] nextChunk(IKeyOrder<E> keyOrder) {
if (keyOrder == null)
throw new IllegalArgumentException();
final E[] chunk = nextChunk();
if (!keyOrder.equals(getKeyOrder())) {
// sort into the required order.
Arrays.sort(chunk, 0, chunk.length, keyOrder.getComparator());
}
return chunk;
}
public void close() {
if(src instanceof ICloseableIterator<?>) {
((ICloseableIterator<E>)src).close();
}
}
}
}
| gpl-2.0 |
snavaneethan1/jaffa-framework | jaffa-core/source/java/org/jaffa/persistence/engines/jdbcengine/configservice/initdomain/ConfLocation.java | 2189 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.0 in JDK 1.6
// 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: 2007.12.07 at 12:13:37 PM PST
//
package org.jaffa.persistence.engines.jdbcengine.configservice.initdomain;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for conf-location complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="conf-location">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="dir-loc" type="{}dir-loc" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "conf-location", propOrder = {
"dirLoc"
})
public class ConfLocation {
@XmlElement(name = "dir-loc", required = true)
protected List<DirLoc> dirLoc;
/**
* Gets the value of the dirLoc property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dirLoc property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDirLoc().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DirLoc }
*
*
*/
public List<DirLoc> getDirLoc() {
if (dirLoc == null) {
dirLoc = new ArrayList<DirLoc>();
}
return this.dirLoc;
}
}
| gpl-3.0 |
morogoku/KernelAdiutor-MOD | app/src/main/java/com/moro/mtweaks/utils/tools/customcontrols/CustomControlException.java | 1003 | /*
* Copyright (C) 2015-2016 Willi Ye <williye97@gmail.com>
*
* This file is part of Kernel Adiutor.
*
* Kernel Adiutor 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.
*
* Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.moro.mtweaks.utils.tools.customcontrols;
/**
* Created by willi on 02.07.16.
*/
public class CustomControlException extends Exception {
public CustomControlException(String message) {
super(message);
}
}
| gpl-3.0 |
Sarius997/PD-ice | src/com/shatteredpixel/shatteredicepixeldungeon/Badges.java | 27397 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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 com.shatteredpixel.shatteredicepixeldungeon;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import com.shatteredpixel.shatteredicepixeldungeon.items.artifacts.Artifact;
import com.shatteredpixel.shatteredicepixeldungeon.items.bags.PotionBandolier;
import com.watabou.noosa.Game;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Acidic;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Albino;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Bandit;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Mob;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Senior;
import com.shatteredpixel.shatteredicepixeldungeon.actors.mobs.Shielded;
import com.shatteredpixel.shatteredicepixeldungeon.items.Item;
import com.shatteredpixel.shatteredicepixeldungeon.items.bags.ScrollHolder;
import com.shatteredpixel.shatteredicepixeldungeon.items.bags.SeedPouch;
import com.shatteredpixel.shatteredicepixeldungeon.items.bags.WandHolster;
import com.shatteredpixel.shatteredicepixeldungeon.items.potions.Potion;
import com.shatteredpixel.shatteredicepixeldungeon.items.rings.Ring;
import com.shatteredpixel.shatteredicepixeldungeon.items.scrolls.Scroll;
import com.shatteredpixel.shatteredicepixeldungeon.items.wands.Wand;
import com.shatteredpixel.shatteredicepixeldungeon.scenes.PixelScene;
import com.shatteredpixel.shatteredicepixeldungeon.utils.GLog;
import com.watabou.utils.Bundle;
import com.watabou.utils.Callback;
public class Badges {
public static enum Badge {
MONSTERS_SLAIN_1( "10 enemies slain", 0 ),
MONSTERS_SLAIN_2( "50 enemies slain", 1 ),
MONSTERS_SLAIN_3( "150 enemies slain", 2 ),
MONSTERS_SLAIN_4( "250 enemies slain", 3 ),
GOLD_COLLECTED_1( "100 gold collected", 4 ),
GOLD_COLLECTED_2( "500 gold collected", 5 ),
GOLD_COLLECTED_3( "2500 gold collected", 6 ),
GOLD_COLLECTED_4( "7500 gold collected", 7 ),
LEVEL_REACHED_1( "Level 6 reached", 8 ),
LEVEL_REACHED_2( "Level 12 reached", 9 ),
LEVEL_REACHED_3( "Level 18 reached", 10 ),
LEVEL_REACHED_4( "Level 24 reached", 11 ),
ALL_POTIONS_IDENTIFIED( "All potions identified", 16 ),
ALL_SCROLLS_IDENTIFIED( "All scrolls identified", 17 ),
ALL_RINGS_IDENTIFIED( "All rings identified", 18 ),
ALL_WANDS_IDENTIFIED( "All wands identified", 19 ),
ALL_ITEMS_IDENTIFIED( "All potions, scrolls, rings & wands identified", 35, true ),
BAG_BOUGHT_SEED_POUCH,
BAG_BOUGHT_SCROLL_HOLDER,
BAG_BOUGHT_POTION_BANDOLIER,
BAG_BOUGHT_WAND_HOLSTER,
ALL_BAGS_BOUGHT( "All bags bought", 23 ),
DEATH_FROM_FIRE( "Death from fire", 24 ),
DEATH_FROM_POISON( "Death from poison", 25 ),
DEATH_FROM_GAS( "Death from toxic gas", 26 ),
DEATH_FROM_HUNGER( "Death from hunger", 27 ),
DEATH_FROM_GLYPH( "Death from a glyph", 57 ),
DEATH_FROM_FALLING( "Death from falling down", 59 ),
YASD( "Death from fire, poison, toxic gas & hunger", 34, true ),
BOSS_SLAIN_1_WARRIOR,
BOSS_SLAIN_1_MAGE,
BOSS_SLAIN_1_ROGUE,
BOSS_SLAIN_1_HUNTRESS,
BOSS_SLAIN_1( "1st boss slain", 12 ),
BOSS_SLAIN_2( "2nd boss slain", 13 ),
BOSS_SLAIN_3( "3rd boss slain", 14 ),
BOSS_SLAIN_4( "4th boss slain", 15 ),
BOSS_SLAIN_1_ALL_CLASSES( "1st boss slain by Warrior, Mage, Rogue & Huntress", 32, true ),
BOSS_SLAIN_3_GLADIATOR,
BOSS_SLAIN_3_BERSERKER,
BOSS_SLAIN_3_WARLOCK,
BOSS_SLAIN_3_BATTLEMAGE,
BOSS_SLAIN_3_FREERUNNER,
BOSS_SLAIN_3_ASSASSIN,
BOSS_SLAIN_3_SNIPER,
BOSS_SLAIN_3_WARDEN,
BOSS_SLAIN_3_ALL_SUBCLASSES(
"3rd boss slain by Gladiator, Berserker, Warlock, Battlemage, " +
"Freerunner, Assassin, Sniper & Warden", 33, true ),
RING_OF_HAGGLER( "Ring of Haggler obtained", 20 ),
RING_OF_THORNS( "Ring of Thorns obtained", 21 ),
STRENGTH_ATTAINED_1( "13 points of Strength attained", 40 ),
STRENGTH_ATTAINED_2( "15 points of Strength attained", 41 ),
STRENGTH_ATTAINED_3( "17 points of Strength attained", 42 ),
STRENGTH_ATTAINED_4( "19 points of Strength attained", 43 ),
FOOD_EATEN_1( "10 pieces of food eaten", 44 ),
FOOD_EATEN_2( "20 pieces of food eaten", 45 ),
FOOD_EATEN_3( "30 pieces of food eaten", 46 ),
FOOD_EATEN_4( "40 pieces of food eaten", 47 ),
MASTERY_WARRIOR,
MASTERY_MAGE,
MASTERY_ROGUE,
MASTERY_HUNTRESS,
ITEM_LEVEL_1( "Item of level 3 acquired", 48 ),
ITEM_LEVEL_2( "Item of level 6 acquired", 49 ),
ITEM_LEVEL_3( "Item of level 9 acquired", 50 ),
ITEM_LEVEL_4( "Item of level 12 acquired", 51 ),
RARE_ALBINO,
RARE_BANDIT,
RARE_SHIELDED,
RARE_SENIOR,
RARE_ACIDIC,
RARE( "All rare monsters slain", 37, true ),
VICTORY_WARRIOR,
VICTORY_MAGE,
VICTORY_ROGUE,
VICTORY_HUNTRESS,
VICTORY( "Amulet of Yendor obtained", 22 ),
VICTORY_ALL_CLASSES( "Amulet of Yendor obtained by Warrior, Mage, Rogue & Huntress", 36, true ),
MASTERY_COMBO( "7-hit combo", 56 ),
POTIONS_COOKED_1( "3 potions cooked", 52 ),
POTIONS_COOKED_2( "6 potions cooked", 53 ),
POTIONS_COOKED_3( "9 potions cooked", 54 ),
POTIONS_COOKED_4( "12 potions cooked", 55 ),
NO_MONSTERS_SLAIN( "Level completed without killing any monsters", 28 ),
GRIM_WEAPON( "Monster killed by a Grim weapon", 29 ),
PIRANHAS( "6 piranhas killed", 30 ),
NIGHT_HUNTER( "15 monsters killed at nighttime", 58 ),
GAMES_PLAYED_1( "10 games played", 60, true ),
GAMES_PLAYED_2( "100 games played", 61, true ),
GAMES_PLAYED_3( "500 games played", 62, true ),
GAMES_PLAYED_4( "2000 games played", 63, true ),
HAPPY_END( "Happy end", 38 ),
CHAMPION( "Challenge won", 39, true ),
SUPPORTER( "Thanks for your support!", 31, true );
public boolean meta;
public String description;
public int image;
private Badge( String description, int image ) {
this( description, image, false );
}
private Badge( String description, int image, boolean meta ) {
this.description = description;
this.image = image;
this.meta = meta;
}
private Badge() {
this( "", -1 );
}
}
private static HashSet<Badge> global;
private static HashSet<Badge> local = new HashSet<Badges.Badge>();
private static boolean saveNeeded = false;
public static Callback loadingListener = null;
public static void reset() {
local.clear();
loadGlobal();
}
private static final String BADGES_FILE = "badges.dat";
private static final String BADGES = "badges";
private static HashSet<Badge> restore( Bundle bundle ) {
HashSet<Badge> badges = new HashSet<Badge>();
String[] names = bundle.getStringArray( BADGES );
for (int i=0; i < names.length; i++) {
try {
badges.add( Badge.valueOf( names[i] ) );
} catch (Exception e) {
}
}
return badges;
}
private static void store( Bundle bundle, HashSet<Badge> badges ) {
int count = 0;
String names[] = new String[badges.size()];
for (Badge badge:badges) {
names[count++] = badge.toString();
}
bundle.put( BADGES, names );
}
public static void loadLocal( Bundle bundle ) {
local = restore( bundle );
}
public static void saveLocal( Bundle bundle ) {
store( bundle, local );
}
public static void loadGlobal() {
if (global == null) {
try {
InputStream input = Game.instance.openFileInput( BADGES_FILE );
Bundle bundle = Bundle.read( input );
input.close();
global = restore( bundle );
} catch (Exception e) {
global = new HashSet<Badge>();
}
}
}
public static void saveGlobal() {
if (saveNeeded) {
Bundle bundle = new Bundle();
store( bundle, global );
try {
OutputStream output = Game.instance.openFileOutput( BADGES_FILE, Game.MODE_PRIVATE );
Bundle.write( bundle, output );
output.close();
saveNeeded = false;
} catch (IOException e) {
}
}
}
public static void validateMonstersSlain() {
Badge badge = null;
if (!local.contains( Badge.MONSTERS_SLAIN_1 ) && Statistics.enemiesSlain >= 10) {
badge = Badge.MONSTERS_SLAIN_1;
local.add( badge );
}
if (!local.contains( Badge.MONSTERS_SLAIN_2 ) && Statistics.enemiesSlain >= 50) {
badge = Badge.MONSTERS_SLAIN_2;
local.add( badge );
}
if (!local.contains( Badge.MONSTERS_SLAIN_3 ) && Statistics.enemiesSlain >= 150) {
badge = Badge.MONSTERS_SLAIN_3;
local.add( badge );
}
if (!local.contains( Badge.MONSTERS_SLAIN_4 ) && Statistics.enemiesSlain >= 250) {
badge = Badge.MONSTERS_SLAIN_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validateGoldCollected() {
Badge badge = null;
if (!local.contains( Badge.GOLD_COLLECTED_1 ) && Statistics.goldCollected >= 100) {
badge = Badge.GOLD_COLLECTED_1;
local.add( badge );
}
if (!local.contains( Badge.GOLD_COLLECTED_2 ) && Statistics.goldCollected >= 500) {
badge = Badge.GOLD_COLLECTED_2;
local.add( badge );
}
if (!local.contains( Badge.GOLD_COLLECTED_3 ) && Statistics.goldCollected >= 2500) {
badge = Badge.GOLD_COLLECTED_3;
local.add( badge );
}
if (!local.contains( Badge.GOLD_COLLECTED_4 ) && Statistics.goldCollected >= 7500) {
badge = Badge.GOLD_COLLECTED_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validateLevelReached() {
Badge badge = null;
if (!local.contains( Badge.LEVEL_REACHED_1 ) && Dungeon.hero.lvl >= 6) {
badge = Badge.LEVEL_REACHED_1;
local.add( badge );
}
if (!local.contains( Badge.LEVEL_REACHED_2 ) && Dungeon.hero.lvl >= 12) {
badge = Badge.LEVEL_REACHED_2;
local.add( badge );
}
if (!local.contains( Badge.LEVEL_REACHED_3 ) && Dungeon.hero.lvl >= 18) {
badge = Badge.LEVEL_REACHED_3;
local.add( badge );
}
if (!local.contains( Badge.LEVEL_REACHED_4 ) && Dungeon.hero.lvl >= 24) {
badge = Badge.LEVEL_REACHED_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validateStrengthAttained() {
Badge badge = null;
if (!local.contains( Badge.STRENGTH_ATTAINED_1 ) && Dungeon.hero.STR >= 13) {
badge = Badge.STRENGTH_ATTAINED_1;
local.add( badge );
}
if (!local.contains( Badge.STRENGTH_ATTAINED_2 ) && Dungeon.hero.STR >= 15) {
badge = Badge.STRENGTH_ATTAINED_2;
local.add( badge );
}
if (!local.contains( Badge.STRENGTH_ATTAINED_3 ) && Dungeon.hero.STR >= 17) {
badge = Badge.STRENGTH_ATTAINED_3;
local.add( badge );
}
if (!local.contains( Badge.STRENGTH_ATTAINED_4 ) && Dungeon.hero.STR >= 19) {
badge = Badge.STRENGTH_ATTAINED_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validateFoodEaten() {
Badge badge = null;
if (!local.contains( Badge.FOOD_EATEN_1 ) && Statistics.foodEaten >= 10) {
badge = Badge.FOOD_EATEN_1;
local.add( badge );
}
if (!local.contains( Badge.FOOD_EATEN_2 ) && Statistics.foodEaten >= 20) {
badge = Badge.FOOD_EATEN_2;
local.add( badge );
}
if (!local.contains( Badge.FOOD_EATEN_3 ) && Statistics.foodEaten >= 30) {
badge = Badge.FOOD_EATEN_3;
local.add( badge );
}
if (!local.contains( Badge.FOOD_EATEN_4 ) && Statistics.foodEaten >= 40) {
badge = Badge.FOOD_EATEN_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validatePotionsCooked() {
Badge badge = null;
if (!local.contains( Badge.POTIONS_COOKED_1 ) && Statistics.potionsCooked >= 3) {
badge = Badge.POTIONS_COOKED_1;
local.add( badge );
}
if (!local.contains( Badge.POTIONS_COOKED_2 ) && Statistics.potionsCooked >= 6) {
badge = Badge.POTIONS_COOKED_2;
local.add( badge );
}
if (!local.contains( Badge.POTIONS_COOKED_3 ) && Statistics.potionsCooked >= 9) {
badge = Badge.POTIONS_COOKED_3;
local.add( badge );
}
if (!local.contains( Badge.POTIONS_COOKED_4 ) && Statistics.potionsCooked >= 12) {
badge = Badge.POTIONS_COOKED_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validatePiranhasKilled() {
Badge badge = null;
if (!local.contains( Badge.PIRANHAS ) && Statistics.piranhasKilled >= 6) {
badge = Badge.PIRANHAS;
local.add( badge );
}
displayBadge( badge );
}
public static void validateItemLevelAquired( Item item ) {
// This method should be called:
// 1) When an item is obtained (Item.collect)
// 2) When an item is upgraded (ScrollOfUpgrade, ScrollOfWeaponUpgrade, ShortSword, WandOfMagicMissile)
// 3) When an item is identified
// Note that artifacts should never trigger this badge as they are alternatively upgraded
if (!item.levelKnown || item instanceof Artifact) {
return;
}
Badge badge = null;
if (!local.contains( Badge.ITEM_LEVEL_1 ) && item.level >= 3) {
badge = Badge.ITEM_LEVEL_1;
local.add( badge );
}
if (!local.contains( Badge.ITEM_LEVEL_2 ) && item.level >= 6) {
badge = Badge.ITEM_LEVEL_2;
local.add( badge );
}
if (!local.contains( Badge.ITEM_LEVEL_3 ) && item.level >= 9) {
badge = Badge.ITEM_LEVEL_3;
local.add( badge );
}
if (!local.contains( Badge.ITEM_LEVEL_4 ) && item.level >= 12) {
badge = Badge.ITEM_LEVEL_4;
local.add( badge );
}
displayBadge( badge );
}
public static void validateAllPotionsIdentified() {
if (Dungeon.hero != null && Dungeon.hero.isAlive() &&
!local.contains( Badge.ALL_POTIONS_IDENTIFIED ) && Potion.allKnown()) {
Badge badge = Badge.ALL_POTIONS_IDENTIFIED;
local.add( badge );
displayBadge( badge );
validateAllItemsIdentified();
}
}
public static void validateAllScrollsIdentified() {
if (Dungeon.hero != null && Dungeon.hero.isAlive() &&
!local.contains( Badge.ALL_SCROLLS_IDENTIFIED ) && Scroll.allKnown()) {
Badge badge = Badge.ALL_SCROLLS_IDENTIFIED;
local.add( badge );
displayBadge( badge );
validateAllItemsIdentified();
}
}
public static void validateAllRingsIdentified() {
if (Dungeon.hero != null && Dungeon.hero.isAlive() &&
!local.contains( Badge.ALL_RINGS_IDENTIFIED ) && Ring.allKnown()) {
Badge badge = Badge.ALL_RINGS_IDENTIFIED;
local.add( badge );
displayBadge( badge );
validateAllItemsIdentified();
}
}
public static void validateAllWandsIdentified() {
if (Dungeon.hero != null && Dungeon.hero.isAlive() &&
!local.contains( Badge.ALL_WANDS_IDENTIFIED ) && Wand.allKnown()) {
Badge badge = Badge.ALL_WANDS_IDENTIFIED;
local.add( badge );
displayBadge( badge );
validateAllItemsIdentified();
}
}
public static void validateAllBagsBought( Item bag ) {
Badge badge = null;
if (bag instanceof SeedPouch) {
badge = Badge.BAG_BOUGHT_SEED_POUCH;
} else if (bag instanceof ScrollHolder) {
badge = Badge.BAG_BOUGHT_SCROLL_HOLDER;
} else if (bag instanceof PotionBandolier) {
badge = Badge.BAG_BOUGHT_POTION_BANDOLIER;
} else if (bag instanceof WandHolster) {
badge = Badge.BAG_BOUGHT_WAND_HOLSTER;
}
if (badge != null) {
local.add( badge );
if (!local.contains( Badge.ALL_BAGS_BOUGHT ) &&
local.contains( Badge.BAG_BOUGHT_SEED_POUCH ) &&
local.contains( Badge.BAG_BOUGHT_SCROLL_HOLDER ) &&
local.contains( Badge.BAG_BOUGHT_POTION_BANDOLIER ) &&
local.contains( Badge.BAG_BOUGHT_WAND_HOLSTER )) {
badge = Badge.ALL_BAGS_BOUGHT;
local.add( badge );
displayBadge( badge );
}
}
}
public static void validateAllItemsIdentified() {
if (!global.contains( Badge.ALL_ITEMS_IDENTIFIED ) &&
global.contains( Badge.ALL_POTIONS_IDENTIFIED ) &&
global.contains( Badge.ALL_SCROLLS_IDENTIFIED ) &&
global.contains( Badge.ALL_RINGS_IDENTIFIED ) &&
global.contains( Badge.ALL_WANDS_IDENTIFIED )) {
Badge badge = Badge.ALL_ITEMS_IDENTIFIED;
displayBadge( badge );
}
}
public static void validateDeathFromFire() {
Badge badge = Badge.DEATH_FROM_FIRE;
local.add( badge );
displayBadge( badge );
validateYASD();
}
public static void validateDeathFromPoison() {
Badge badge = Badge.DEATH_FROM_POISON;
local.add( badge );
displayBadge( badge );
validateYASD();
}
public static void validateDeathFromGas() {
Badge badge = Badge.DEATH_FROM_GAS;
local.add( badge );
displayBadge( badge );
validateYASD();
}
public static void validateDeathFromHunger() {
Badge badge = Badge.DEATH_FROM_HUNGER;
local.add( badge );
displayBadge( badge );
validateYASD();
}
public static void validateDeathFromGlyph() {
Badge badge = Badge.DEATH_FROM_GLYPH;
local.add( badge );
displayBadge( badge );
}
public static void validateDeathFromFalling() {
Badge badge = Badge.DEATH_FROM_FALLING;
local.add( badge );
displayBadge( badge );
}
private static void validateYASD() {
if (global.contains( Badge.DEATH_FROM_FIRE ) &&
global.contains( Badge.DEATH_FROM_POISON ) &&
global.contains( Badge.DEATH_FROM_GAS ) &&
global.contains( Badge.DEATH_FROM_HUNGER)) {
Badge badge = Badge.YASD;
local.add( badge );
displayBadge( badge );
}
}
public static void validateBossSlain() {
Badge badge = null;
switch (Dungeon.depth) {
case 5:
badge = Badge.BOSS_SLAIN_1;
break;
case 10:
badge = Badge.BOSS_SLAIN_2;
break;
case 15:
badge = Badge.BOSS_SLAIN_3;
break;
case 20:
badge = Badge.BOSS_SLAIN_4;
break;
}
if (badge != null) {
local.add( badge );
displayBadge( badge );
if (badge == Badge.BOSS_SLAIN_1) {
switch (Dungeon.hero.heroClass) {
case WARRIOR:
badge = Badge.BOSS_SLAIN_1_WARRIOR;
break;
case MAGE:
badge = Badge.BOSS_SLAIN_1_MAGE;
break;
case ROGUE:
badge = Badge.BOSS_SLAIN_1_ROGUE;
break;
case HUNTRESS:
badge = Badge.BOSS_SLAIN_1_HUNTRESS;
break;
}
local.add( badge );
if (!global.contains( badge )) {
global.add( badge );
saveNeeded = true;
}
if (global.contains( Badge.BOSS_SLAIN_1_WARRIOR ) &&
global.contains( Badge.BOSS_SLAIN_1_MAGE ) &&
global.contains( Badge.BOSS_SLAIN_1_ROGUE ) &&
global.contains( Badge.BOSS_SLAIN_1_HUNTRESS)) {
badge = Badge.BOSS_SLAIN_1_ALL_CLASSES;
if (!global.contains( badge )) {
displayBadge( badge );
global.add( badge );
saveNeeded = true;
}
}
} else
if (badge == Badge.BOSS_SLAIN_3) {
switch (Dungeon.hero.subClass) {
case GLADIATOR:
badge = Badge.BOSS_SLAIN_3_GLADIATOR;
break;
case BERSERKER:
badge = Badge.BOSS_SLAIN_3_BERSERKER;
break;
case WARLOCK:
badge = Badge.BOSS_SLAIN_3_WARLOCK;
break;
case BATTLEMAGE:
badge = Badge.BOSS_SLAIN_3_BATTLEMAGE;
break;
case FREERUNNER:
badge = Badge.BOSS_SLAIN_3_FREERUNNER;
break;
case ASSASSIN:
badge = Badge.BOSS_SLAIN_3_ASSASSIN;
break;
case SNIPER:
badge = Badge.BOSS_SLAIN_3_SNIPER;
break;
case WARDEN:
badge = Badge.BOSS_SLAIN_3_WARDEN;
break;
default:
return;
}
local.add( badge );
if (!global.contains( badge )) {
global.add( badge );
saveNeeded = true;
}
if (global.contains( Badge.BOSS_SLAIN_3_GLADIATOR ) &&
global.contains( Badge.BOSS_SLAIN_3_BERSERKER ) &&
global.contains( Badge.BOSS_SLAIN_3_WARLOCK ) &&
global.contains( Badge.BOSS_SLAIN_3_BATTLEMAGE ) &&
global.contains( Badge.BOSS_SLAIN_3_FREERUNNER ) &&
global.contains( Badge.BOSS_SLAIN_3_ASSASSIN ) &&
global.contains( Badge.BOSS_SLAIN_3_SNIPER ) &&
global.contains( Badge.BOSS_SLAIN_3_WARDEN )) {
badge = Badge.BOSS_SLAIN_3_ALL_SUBCLASSES;
if (!global.contains( badge )) {
displayBadge( badge );
global.add( badge );
saveNeeded = true;
}
}
}
}
}
public static void validateMastery() {
Badge badge = null;
switch (Dungeon.hero.heroClass) {
case WARRIOR:
badge = Badge.MASTERY_WARRIOR;
break;
case MAGE:
badge = Badge.MASTERY_MAGE;
break;
case ROGUE:
badge = Badge.MASTERY_ROGUE;
break;
case HUNTRESS:
badge = Badge.MASTERY_HUNTRESS;
break;
}
if (!global.contains( badge )) {
global.add( badge );
saveNeeded = true;
}
}
public static void validateMasteryCombo( int n ) {
if (!local.contains( Badge.MASTERY_COMBO ) && n == 7) {
Badge badge = Badge.MASTERY_COMBO;
local.add( badge );
displayBadge( badge );
}
}
//TODO: Replace this badge, delayed until an eventual badge rework
public static void validateRingOfHaggler() {
if (!local.contains( Badge.RING_OF_HAGGLER )/* && new RingOfThorns().isKnown()*/) {
Badge badge = Badge.RING_OF_HAGGLER;
local.add( badge );
displayBadge( badge );
}
}
//TODO: Replace this badge, delayed until an eventual badge rework
public static void validateRingOfThorns() {
if (!local.contains( Badge.RING_OF_THORNS )/* && new RingOfThorns().isKnown()*/) {
Badge badge = Badge.RING_OF_THORNS;
local.add( badge );
displayBadge( badge );
}
}
public static void validateRare( Mob mob ) {
Badge badge = null;
if (mob instanceof Albino) {
badge = Badge.RARE_ALBINO;
} else if (mob instanceof Bandit) {
badge = Badge.RARE_BANDIT;
} else if (mob instanceof Shielded) {
badge = Badge.RARE_SHIELDED;
} else if (mob instanceof Senior) {
badge = Badge.RARE_SENIOR;
} else if (mob instanceof Acidic) {
badge = Badge.RARE_ACIDIC;
}
if (!global.contains( badge )) {
global.add( badge );
saveNeeded = true;
}
if (global.contains( Badge.RARE_ALBINO ) &&
global.contains( Badge.RARE_BANDIT ) &&
global.contains( Badge.RARE_SHIELDED ) &&
global.contains( Badge.RARE_SENIOR ) &&
global.contains( Badge.RARE_ACIDIC )) {
badge = Badge.RARE;
displayBadge( badge );
}
}
public static void validateVictory() {
Badge badge = Badge.VICTORY;
displayBadge( badge );
switch (Dungeon.hero.heroClass) {
case WARRIOR:
badge = Badge.VICTORY_WARRIOR;
break;
case MAGE:
badge = Badge.VICTORY_MAGE;
break;
case ROGUE:
badge = Badge.VICTORY_ROGUE;
break;
case HUNTRESS:
badge = Badge.VICTORY_HUNTRESS;
break;
}
local.add( badge );
if (!global.contains( badge )) {
global.add( badge );
saveNeeded = true;
}
if (global.contains( Badge.VICTORY_WARRIOR ) &&
global.contains( Badge.VICTORY_MAGE ) &&
global.contains( Badge.VICTORY_ROGUE ) &&
global.contains( Badge.VICTORY_HUNTRESS )) {
badge = Badge.VICTORY_ALL_CLASSES;
displayBadge( badge );
}
}
public static void validateNoKilling() {
if (!local.contains( Badge.NO_MONSTERS_SLAIN ) && Statistics.completedWithNoKilling) {
Badge badge = Badge.NO_MONSTERS_SLAIN;
local.add( badge );
displayBadge( badge );
}
}
public static void validateGrimWeapon() {
if (!local.contains( Badge.GRIM_WEAPON )) {
Badge badge = Badge.GRIM_WEAPON;
local.add( badge );
displayBadge( badge );
}
}
public static void validateNightHunter() {
if (!local.contains( Badge.NIGHT_HUNTER ) && Statistics.nightHunt >= 15) {
Badge badge = Badge.NIGHT_HUNTER;
local.add( badge );
displayBadge( badge );
}
}
public static void validateSupporter() {
global.add( Badge.SUPPORTER );
saveNeeded = true;
PixelScene.showBadge( Badge.SUPPORTER );
}
public static void validateGamesPlayed() {
Badge badge = null;
if (Rankings.INSTANCE.totalNumber >= 10) {
badge = Badge.GAMES_PLAYED_1;
}
if (Rankings.INSTANCE.totalNumber >= 100) {
badge = Badge.GAMES_PLAYED_2;
}
if (Rankings.INSTANCE.totalNumber >= 500) {
badge = Badge.GAMES_PLAYED_3;
}
if (Rankings.INSTANCE.totalNumber >= 2000) {
badge = Badge.GAMES_PLAYED_4;
}
displayBadge( badge );
}
public static void validateHappyEnd() {
displayBadge( Badge.HAPPY_END );
}
public static void validateChampion() {
displayBadge(Badge.CHAMPION);
}
private static void displayBadge( Badge badge ) {
if (badge == null) {
return;
}
if (global.contains( badge )) {
if (!badge.meta) {
GLog.h( "Badge endorsed: %s", badge.description );
}
} else {
global.add( badge );
saveNeeded = true;
if (badge.meta) {
GLog.h( "New super badge: %s", badge.description );
} else {
GLog.h( "New badge: %s", badge.description );
}
PixelScene.showBadge( badge );
}
}
public static boolean isUnlocked( Badge badge ) {
return global.contains( badge );
}
public static void disown( Badge badge ) {
loadGlobal();
global.remove( badge );
saveNeeded = true;
}
public static List<Badge> filtered( boolean global ) {
HashSet<Badge> filtered = new HashSet<Badge>( global ? Badges.global : Badges.local );
if (!global) {
Iterator<Badge> iterator = filtered.iterator();
while (iterator.hasNext()) {
Badge badge = iterator.next();
if (badge.meta) {
iterator.remove();
}
}
}
leaveBest( filtered, Badge.MONSTERS_SLAIN_1, Badge.MONSTERS_SLAIN_2, Badge.MONSTERS_SLAIN_3, Badge.MONSTERS_SLAIN_4 );
leaveBest( filtered, Badge.GOLD_COLLECTED_1, Badge.GOLD_COLLECTED_2, Badge.GOLD_COLLECTED_3, Badge.GOLD_COLLECTED_4 );
leaveBest( filtered, Badge.BOSS_SLAIN_1, Badge.BOSS_SLAIN_2, Badge.BOSS_SLAIN_3, Badge.BOSS_SLAIN_4 );
leaveBest( filtered, Badge.LEVEL_REACHED_1, Badge.LEVEL_REACHED_2, Badge.LEVEL_REACHED_3, Badge.LEVEL_REACHED_4 );
leaveBest( filtered, Badge.STRENGTH_ATTAINED_1, Badge.STRENGTH_ATTAINED_2, Badge.STRENGTH_ATTAINED_3, Badge.STRENGTH_ATTAINED_4 );
leaveBest( filtered, Badge.FOOD_EATEN_1, Badge.FOOD_EATEN_2, Badge.FOOD_EATEN_3, Badge.FOOD_EATEN_4 );
leaveBest( filtered, Badge.ITEM_LEVEL_1, Badge.ITEM_LEVEL_2, Badge.ITEM_LEVEL_3, Badge.ITEM_LEVEL_4 );
leaveBest( filtered, Badge.POTIONS_COOKED_1, Badge.POTIONS_COOKED_2, Badge.POTIONS_COOKED_3, Badge.POTIONS_COOKED_4 );
leaveBest( filtered, Badge.BOSS_SLAIN_1_ALL_CLASSES, Badge.BOSS_SLAIN_3_ALL_SUBCLASSES );
leaveBest( filtered, Badge.DEATH_FROM_FIRE, Badge.YASD );
leaveBest( filtered, Badge.DEATH_FROM_GAS, Badge.YASD );
leaveBest( filtered, Badge.DEATH_FROM_HUNGER, Badge.YASD );
leaveBest( filtered, Badge.DEATH_FROM_POISON, Badge.YASD );
leaveBest( filtered, Badge.VICTORY, Badge.VICTORY_ALL_CLASSES );
leaveBest( filtered, Badge.GAMES_PLAYED_1, Badge.GAMES_PLAYED_2, Badge.GAMES_PLAYED_3, Badge.GAMES_PLAYED_4 );
ArrayList<Badge> list = new ArrayList<Badge>( filtered );
Collections.sort( list );
return list;
}
private static void leaveBest( HashSet<Badge> list, Badge...badges ) {
for (int i=badges.length-1; i > 0; i--) {
if (list.contains( badges[i])) {
for (int j=0; j < i; j++) {
list.remove( badges[j] );
}
break;
}
}
}
}
| gpl-3.0 |
KevinSeroux/DI3_ProjetTSP | src/polytech/tours/di/parallel/tsp/western_sahara/WesternSahara.java | 1844 | package polytech.tours.di.parallel.tsp.western_sahara;
import polytech.tours.di.parallel.tsp.EuclideanCalculator;
import polytech.tours.di.parallel.tsp.Instance;
/**
* Implements a TSP mock builder that builds the Western Sahara instance reported at:
* http://www.math.uwaterloo.ca/tsp/world/countries.html
*
* @author Jorge E. Mendoza (dev@jorge-mendoza.com)
* @version %I%, %G%
*
*/
public class WesternSahara{
public static Instance buildMock() {
double[][] coordinates= {
{20833.3333,17100.0000},
{20900.0000,17066.6667},
{21300.0000,13016.6667},
{21600.0000,14150.0000},
{21600.0000,14966.6667},
{21600.0000,16500.0000},
{22183.3333,13133.3333},
{22583.3333,14300.0000},
{22683.3333,12716.6667},
{23616.6667,15866.6667},
{23700.0000,15933.3333},
{23883.3333,14533.3333},
{24166.6667,13250.0000},
{25149.1667,12365.8333},
{26133.3333,14500.0000},
{26150.0000,10550.0000},
{26283.3333,12766.6667},
{26433.3333,13433.3333},
{26550.0000,13850.0000},
{26733.3333,11683.3333},
{27026.1111,13051.9444},
{27096.1111,13415.8333},
{27153.6111,13203.3333},
{27166.6667,9833.3333},
{27233.3333,10450.0000},
{27233.3333,11783.3333},
{27266.6667,10383.3333},
{27433.3333,12400.0000},
{27462.5000,12992.2222},
};
return buildEuclideanInstanceFromCoordinates(29, coordinates);
}
/**
* Builds a TSP instance from a coordinates matrix
* @param n the number of nodes in the instance
* @param coordinates the matrix holding the coordinates of the nodes
* @return the TSP instance
*/
public static Instance buildEuclideanInstanceFromCoordinates(int n, double[][] coordinates){
double[][] matrix=EuclideanCalculator.calc(coordinates);
Instance instance=new Instance(matrix);
return instance;
}
}
| gpl-3.0 |
snavaneethan1/jaffa-framework | jaffa-components-printing/source/java/org/jaffa/modules/printing/components/printeroutputtypefinder/ui/PrinterOutputTypeFinderAction.java | 12566 | // .//GEN-BEGIN:_1_be
/******************************************************
* Code Generated From JAFFA Framework Default Pattern
*
* The JAFFA Project can be found at http://jaffa.sourceforge.net
* and is available under the Lesser GNU Public License
******************************************************/
package org.jaffa.modules.printing.components.printeroutputtypefinder.ui;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessages;
import org.jaffa.presentation.portlet.ActionBase;
import org.jaffa.presentation.portlet.FormKey;
import org.jaffa.presentation.portlet.HistoryNav;
import org.jaffa.exceptions.FrameworkException;
import org.jaffa.exceptions.ApplicationExceptions;
import org.jaffa.exceptions.ApplicationException;
import org.jaffa.components.finder.*;
import org.jaffa.presentation.portlet.widgets.model.GridModel;
import org.jaffa.presentation.portlet.widgets.model.GridModelRow;
import org.jaffa.modules.printing.components.printeroutputtypefinder.dto.PrinterOutputTypeFinderInDto;
// .//GEN-END:_1_be
// Add additional imports//GEN-FIRST:_imports
// .//GEN-LAST:_imports
// .//GEN-BEGIN:_2_be
/** The Action class for handling events related to PrinterOutputTypeFinder.
*/
public class PrinterOutputTypeFinderAction extends FinderAction {
private static final Logger log = Logger.getLogger(PrinterOutputTypeFinderAction.class);
/** Invokes the do_Rows_View_Clicked() method.
* @param rowNum The selected row on the Results screen.
* @return The FormKey for the View screen.
*/
public FormKey do_Rows_Clicked(String rowNum) {
return do_Rows_View_Clicked(rowNum);
}
// .//GEN-END:_2_be
// .//GEN-BEGIN:_do_CreateFromCriteria_Clicked_1_be
/** Invokes the createFromCriteria() method on the component.
* @return The FormKey for the Create screen.
*/
public FormKey do_CreateFromCriteria_Clicked() {
FormKey fk = null;
// .//GEN-END:_do_CreateFromCriteria_Clicked_1_be
// Add custom code before processing the action //GEN-FIRST:_do_CreateFromCriteria_Clicked_1
// .//GEN-LAST:_do_CreateFromCriteria_Clicked_1
// .//GEN-BEGIN:_do_CreateFromCriteria_Clicked_2_be
PrinterOutputTypeFinderForm myForm = (PrinterOutputTypeFinderForm) form;
PrinterOutputTypeFinderComponent myComp = (PrinterOutputTypeFinderComponent) myForm.getComponent();
if (myForm.doValidate(request)) {
try {
// .//GEN-END:_do_CreateFromCriteria_Clicked_2_be
// Add custom code before invoking the component //GEN-FIRST:_do_CreateFromCriteria_Clicked_2
// .//GEN-LAST:_do_CreateFromCriteria_Clicked_2
// .//GEN-BEGIN:_do_CreateFromCriteria_Clicked_3_be
fk = myComp.createFromCriteria();
} catch (ApplicationExceptions e){
if (log.isDebugEnabled())
log.debug("Create Failed");
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, e);
} catch (FrameworkException e) {
log.error(null, e);
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, "error.framework.general" );
}
}
// .//GEN-END:_do_CreateFromCriteria_Clicked_3_be
// Add custom code after returning from the component //GEN-FIRST:_do_CreateFromCriteria_Clicked_3
// .//GEN-LAST:_do_CreateFromCriteria_Clicked_3
// .//GEN-BEGIN:_do_CreateFromCriteria_Clicked_4_be
// Direct User back to current form
if (fk == null)
fk = myComp.getCriteriaFormKey();
return fk;
}
// .//GEN-END:_do_CreateFromCriteria_Clicked_4_be
// .//GEN-BEGIN:_do_CreateFromResults_Clicked_1_be
/** Invokes the createFromResults() method on the component.
* @return The FormKey for the Create screen.
*/
public FormKey do_CreateFromResults_Clicked() {
FormKey fk = null;
// .//GEN-END:_do_CreateFromResults_Clicked_1_be
// Add custom code before processing the action //GEN-FIRST:_do_CreateFromResults_Clicked_1
// .//GEN-LAST:_do_CreateFromResults_Clicked_1
// .//GEN-BEGIN:_do_CreateFromResults_Clicked_2_be
PrinterOutputTypeFinderForm myForm = (PrinterOutputTypeFinderForm) form;
PrinterOutputTypeFinderComponent myComp = (PrinterOutputTypeFinderComponent) myForm.getComponent();
try {
// .//GEN-END:_do_CreateFromResults_Clicked_2_be
// Add custom code before invoking the component //GEN-FIRST:_do_CreateFromResults_Clicked_2
// .//GEN-LAST:_do_CreateFromResults_Clicked_2
// .//GEN-BEGIN:_do_CreateFromResults_Clicked_3_be
fk = myComp.createFromResults();
} catch (ApplicationExceptions e){
if (log.isDebugEnabled())
log.debug("Create Failed");
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, e);
} catch (FrameworkException e) {
log.error(null, e);
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, "error.framework.general" );
}
// .//GEN-END:_do_CreateFromResults_Clicked_3_be
// Add custom code after returning from the component //GEN-FIRST:_do_CreateFromResults_Clicked_3
// .//GEN-LAST:_do_CreateFromResults_Clicked_3
// .//GEN-BEGIN:_do_CreateFromResults_Clicked_4_be
// Direct User back to current form
if (fk == null)
fk = myComp.getResultsFormKey();
return fk;
}
// .//GEN-END:_do_CreateFromResults_Clicked_4_be
// .//GEN-BEGIN:_do_Rows_View_Clicked_1_be
/** Invokes the viewObject() method on the component.
* @param rowNum The selected row on the Results screen.
* @return The FormKey for the View screen.
*/
public FormKey do_Rows_View_Clicked(String rowNum) {
FormKey fk = null;
// .//GEN-END:_do_Rows_View_Clicked_1_be
// Add custom code before processing the action //GEN-FIRST:_do_Rows_View_Clicked_1
// .//GEN-LAST:_do_Rows_View_Clicked_1
// .//GEN-BEGIN:_do_Rows_View_Clicked_2_be
PrinterOutputTypeFinderForm myForm = (PrinterOutputTypeFinderForm) form;
PrinterOutputTypeFinderComponent myComp = (PrinterOutputTypeFinderComponent) myForm.getComponent();
GridModel model = (GridModel) myForm.getRowsWM();
GridModelRow selectedRow = model.getRow(Integer.parseInt(rowNum));
if (selectedRow != null) {
try {
// .//GEN-END:_do_Rows_View_Clicked_2_be
// Add custom code before invoking the component //GEN-FIRST:_do_Rows_View_Clicked_2
// .//GEN-LAST:_do_Rows_View_Clicked_2
// .//GEN-BEGIN:_do_Rows_View_Clicked_3_be
fk = myComp.viewObject((java.lang.String) selectedRow.get("outputType"));
} catch (ApplicationExceptions e){
if (log.isDebugEnabled())
log.debug("Viewer Failed");
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, e);
} catch (FrameworkException e) {
log.error(null, e);
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, "error.framework.general" );
}
}
// .//GEN-END:_do_Rows_View_Clicked_3_be
// Add custom code after returning from the component //GEN-FIRST:_do_Rows_View_Clicked_3
// .//GEN-LAST:_do_Rows_View_Clicked_3
// .//GEN-BEGIN:_do_Rows_View_Clicked_4_be
// The Viewer will be rendered in a new window
// We don't want to see the existing HistoryNav in that window
// Hence, initialize the HistoryNav
HistoryNav.initializeHistoryNav(request);
// Direct User back to current form
if (fk == null)
fk = myComp.getResultsFormKey();
return fk;
}
// .//GEN-END:_do_Rows_View_Clicked_4_be
// .//GEN-BEGIN:_do_Rows_Update_Clicked_1_be
/** Invokes the updateObject() method on the component.
* @param rowNum The selected row on the Results screen.
* @return The FormKey for the Update screen.
*/
public FormKey do_Rows_Update_Clicked(String rowNum) {
FormKey fk = null;
// .//GEN-END:_do_Rows_Update_Clicked_1_be
// Add custom code before processing the action //GEN-FIRST:_do_Rows_Update_Clicked_1
// .//GEN-LAST:_do_Rows_Update_Clicked_1
// .//GEN-BEGIN:_do_Rows_Update_Clicked_2_be
PrinterOutputTypeFinderForm myForm = (PrinterOutputTypeFinderForm) form;
PrinterOutputTypeFinderComponent myComp = (PrinterOutputTypeFinderComponent) myForm.getComponent();
GridModel model = (GridModel) myForm.getRowsWM();
GridModelRow selectedRow = model.getRow(Integer.parseInt(rowNum));
if (selectedRow != null) {
try {
// .//GEN-END:_do_Rows_Update_Clicked_2_be
// Add custom code before invoking the component //GEN-FIRST:_do_Rows_Update_Clicked_2
// .//GEN-LAST:_do_Rows_Update_Clicked_2
// .//GEN-BEGIN:_do_Rows_Update_Clicked_3_be
fk = myComp.updateObject((java.lang.String) selectedRow.get("outputType"));
} catch (ApplicationExceptions e){
if (log.isDebugEnabled())
log.debug("Update Failed");
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, e);
} catch (FrameworkException e) {
log.error(null, e);
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, "error.framework.general" );
}
}
// .//GEN-END:_do_Rows_Update_Clicked_3_be
// Add custom code after returning from the component //GEN-FIRST:_do_Rows_Update_Clicked_3
// .//GEN-LAST:_do_Rows_Update_Clicked_3
// .//GEN-BEGIN:_do_Rows_Update_Clicked_4_be
// Direct User back to current form
if (fk == null)
fk = myComp.getResultsFormKey();
return fk;
}
// .//GEN-END:_do_Rows_Update_Clicked_4_be
// .//GEN-BEGIN:_do_Rows_Delete_Clicked_1_be
/** Invokes the deleteObject() method on the component.
* @param rowNum The selected row on the Results screen.
* @return The FormKey for the Delete screen.
*/
public FormKey do_Rows_Delete_Clicked(String rowNum) {
FormKey fk = null;
// .//GEN-END:_do_Rows_Delete_Clicked_1_be
// Add custom code before processing the action //GEN-FIRST:_do_Rows_Delete_Clicked_1
// .//GEN-LAST:_do_Rows_Delete_Clicked_1
// .//GEN-BEGIN:_do_Rows_Delete_Clicked_2_be
PrinterOutputTypeFinderForm myForm = (PrinterOutputTypeFinderForm) form;
PrinterOutputTypeFinderComponent myComp = (PrinterOutputTypeFinderComponent) myForm.getComponent();
try {
// This will stop double submits
performTokenValidation(request);
GridModel model = (GridModel) myForm.getRowsWM();
GridModelRow selectedRow = model.getRow(Integer.parseInt(rowNum));
if (selectedRow != null) {
// .//GEN-END:_do_Rows_Delete_Clicked_2_be
// Add custom code before invoking the component //GEN-FIRST:_do_Rows_Delete_Clicked_2
// .//GEN-LAST:_do_Rows_Delete_Clicked_2
// .//GEN-BEGIN:_do_Rows_Delete_Clicked_3_be
fk = myComp.deleteObject((java.lang.String) selectedRow.get("outputType"));
}
} catch (ApplicationExceptions e){
if (log.isDebugEnabled())
log.debug("Delete Failed");
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, e);
} catch (FrameworkException e) {
log.error(null, e);
myForm.raiseError(request, ActionMessages.GLOBAL_MESSAGE, "error.framework.general" );
}
// .//GEN-END:_do_Rows_Delete_Clicked_3_be
// Add custom code after returning from the component //GEN-FIRST:_do_Rows_Delete_Clicked_3
// .//GEN-LAST:_do_Rows_Delete_Clicked_3
// .//GEN-BEGIN:_do_Rows_Delete_Clicked_4_be
// Direct User back to current form
if (fk == null)
fk = myComp.getResultsFormKey();
return fk;
}
// .//GEN-END:_do_Rows_Delete_Clicked_4_be
// All the custom code goes here //GEN-FIRST:_custom
// .//GEN-LAST:_custom
}
| gpl-3.0 |
saikrishna321/AppiumTestDistribution | src/test/java/com/appium/executor/OtherTests1.java | 176 | package com.appium.executor;
import org.testng.annotations.Test;
public class OtherTests1 {
@Test public void test1() {
}
@Test public void test2() {
}
}
| gpl-3.0 |
Shappiro/GEOFRAME | PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/src/cern/jet/random/tdouble/Binomial.java | 13848 | /*
Copyright (C) 1999 CERN - European Organization for Nuclear Research.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose
is hereby granted without fee, provided that the above copyright notice appear in all copies and
that both that copyright notice and this permission notice appear in supporting documentation.
CERN makes no representations about the suitability of this software for any purpose.
It is provided "as is" without expressed or implied warranty.
*/
package cern.jet.random.tdouble;
import cern.jet.math.tdouble.DoubleArithmetic;
import cern.jet.random.tdouble.engine.DoubleRandomEngine;
import cern.jet.stat.tdouble.Probability;
/**
* Binomial distribution; See the <A HREF=
* "http://www.cern.ch/RD11/rkb/AN16pp/node19.html#SECTION000190000000000000000"
* > math definition</A> and <A
* HREF="http://www.statsoft.com/textbook/glosb.html#Binomial Distribution">
* animated definition</A>.
* <p>
* <tt>p(x) = k * p^k * (1-p)^(n-k)</tt> with <tt>k = n! / (k! * (n-k)!)</tt>.
* <p>
* Instance methods operate on a user supplied uniform random number generator;
* they are unsynchronized.
* <dt>Static methods operate on a default uniform random number generator; they
* are synchronized.
* <p>
* <b>Implementation:</b> High performance implementation. Acceptance
* Rejection/Inversion method. This is a port of <A HREF="http://wwwinfo.cern.ch/asd/lhc++/clhep/manual/RefGuide/Random/RandBinomial.html"
* >RandBinomial</A> used in <A
* HREF="http://wwwinfo.cern.ch/asd/lhc++/clhep">CLHEP 1.4.0</A> (C++). CLHEP's
* implementation is, in turn, based on
* <p>
* V. Kachitvichyanukul, B.W. Schmeiser (1988): Binomial random variate
* generation, Communications of the ACM 31, 216-222.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
public class Binomial extends AbstractDiscreteDistribution {
/**
*
*/
private static final long serialVersionUID = 1L;
protected int n;
protected double p;
// cache vars for method generateBinomial(...)
private int n_last = -1, n_prev = -1;
private double par, np, p0, q, p_last = -1.0, p_prev = -1.0;
private int b, m, nm;
private double pq, rc, ss, xm, xl, xr, ll, lr, c, p1, p2, p3, p4, ch;
// cache vars for method pdf(...)
private double log_p, log_q, log_n;
// The uniform random number generated shared by all <b>static</b> methods.
protected static Binomial shared = new Binomial(1, 0.5, makeDefaultGenerator());
/**
* Constructs a binomial distribution. Example: n=1, p=0.5.
*
* @param n
* the number of trials (also known as <i>sample size</i>).
* @param p
* the probability of success.
* @param randomGenerator
* a uniform random number generator.
* @throws IllegalArgumentException
* if <tt>n*Math.min(p,1-p) <= 0.0</tt>
*/
public Binomial(int n, double p, DoubleRandomEngine randomGenerator) {
setRandomGenerator(randomGenerator);
setNandP(n, p);
}
/**
* Returns the cumulative distribution function.
*/
public double cdf(int k) {
return Probability.binomial(k, n, p);
}
/**
* Returns the cumulative distribution function.
*/
private double cdfSlow(int k) {
if (k < 0)
throw new IllegalArgumentException();
double sum = 0.0;
for (int r = 0; r <= k; r++)
sum += pdf(r);
return sum;
}
/***************************************************************************
* * Binomial-Distribution - Acceptance Rejection/Inversion * *
* ***************************************************************** *
* Acceptance Rejection method combined with Inversion for * generating
* Binomial random numbers with parameters * n (number of trials) and p
* (probability of success). * For min(n*p,n*(1-p)) < 10 the Inversion
* method is applied: * The random numbers are generated via sequential
* search, * starting at the lowest index k=0. The cumulative probabilities
* * are avoided by using the technique of chop-down. * For min(n*p,n*(1-p))
* >= 10 Acceptance Rejection is used: * The algorithm is based on a
* hat-function which is uniform in * the centre region and exponential in
* the tails. * A triangular immediate acceptance region in the centre
* speeds * up the generation of binomial variates. * If candidate k is near
* the mode, f(k) is computed recursively * starting at the mode m. * The
* acceptance test by Stirling's formula is modified * according to W.
* Hoermann (1992): The generation of binomial * random variates, to appear
* in J. Statist. Comput. Simul. * If p < .5 the algorithm is applied to
* parameters n, p. * Otherwise p is replaced by 1-p, and k is replaced by n
* - k. * *
* ***************************************************************** *
* FUNCTION: - samples a random number from the binomial * distribution with
* parameters n and p and is * valid for n*min(p,1-p) > 0. * REFERENCE: - V.
* Kachitvichyanukul, B.W. Schmeiser (1988): * Binomial random variate
* generation, * Communications of the ACM 31, 216-222. * SUBPROGRAMS: -
* StirlingCorrection() * ... Correction term of the Stirling *
* approximation for log(k!) * (series in 1/k or table values * for small k)
* with long int k * - randomGenerator ... (0,1)-Uniform engine * *
**************************************************************************/
protected int generateBinomial(int n, double p) {
final double C1_3 = 0.33333333333333333;
final double C5_8 = 0.62500000000000000;
final double C1_6 = 0.16666666666666667;
final int DMAX_KM = 20;
int bh, i, K, Km, nK;
double f, rm, U, V, X, T, E;
if (n != n_last || p != p_last) { // set-up
n_last = n;
p_last = p;
par = Math.min(p, 1.0 - p);
q = 1.0 - par;
np = n * par;
// Check for invalid input values
if (np <= 0.0)
return -1;
rm = np + par;
m = (int) rm; // mode, integer
if (np < 10) {
p0 = Math.exp(n * Math.log(q)); // Chop-down
bh = (int) (np + 10.0 * Math.sqrt(np * q));
b = Math.min(n, bh);
} else {
rc = (n + 1.0) * (pq = par / q); // recurr. relat.
ss = np * q; // variance
i = (int) (2.195 * Math.sqrt(ss) - 4.6 * q); // i = p1 - 0.5
xm = m + 0.5;
xl = (m - i); // limit left
xr = (m + i + 1L); // limit right
f = (rm - xl) / (rm - xl * par);
ll = f * (1.0 + 0.5 * f);
f = (xr - rm) / (xr * q);
lr = f * (1.0 + 0.5 * f);
c = 0.134 + 20.5 / (15.3 + m); // parallelogram
// height
p1 = i + 0.5;
p2 = p1 * (1.0 + c + c); // probabilities
p3 = p2 + c / ll; // of regions 1-4
p4 = p3 + c / lr;
}
}
if (np < 10) { // Inversion Chop-down
double pk;
K = 0;
pk = p0;
U = randomGenerator.raw();
while (U > pk) {
++K;
if (K > b) {
U = randomGenerator.raw();
K = 0;
pk = p0;
} else {
U -= pk;
pk = (((n - K + 1) * par * pk) / (K * q));
}
}
return ((p > 0.5) ? (n - K) : K);
}
for (;;) {
V = randomGenerator.raw();
if ((U = randomGenerator.raw() * p4) <= p1) { // triangular region
K = (int) (xm - U + p1 * V);
return (p > 0.5) ? (n - K) : K; // immediate accept
}
if (U <= p2) { // parallelogram
X = xl + (U - p1) / c;
if ((V = V * c + 1.0 - Math.abs(xm - X) / p1) >= 1.0)
continue;
K = (int) X;
} else if (U <= p3) { // left tail
if ((X = xl + Math.log(V) / ll) < 0.0)
continue;
K = (int) X;
V *= (U - p2) * ll;
} else { // right tail
if ((K = (int) (xr - Math.log(V) / lr)) > n)
continue;
V *= (U - p3) * lr;
}
// acceptance test : two cases, depending on |K - m|
if ((Km = Math.abs(K - m)) <= DMAX_KM || Km + Km + 2L >= ss) {
// computation of p(K) via recurrence relationship from the mode
f = 1.0; // f(m)
if (m < K) {
for (i = m; i < K;) {
if ((f *= (rc / ++i - pq)) < V)
break; // multiply f
}
} else {
for (i = K; i < m;) {
if ((V *= (rc / ++i - pq)) > f)
break; // multiply V
}
}
if (V <= f)
break; // acceptance test
} else {
// lower and upper squeeze tests, based on lower bounds for log
// p(K)
V = Math.log(V);
T = -Km * Km / (ss + ss);
E = (Km / ss) * ((Km * (Km * C1_3 + C5_8) + C1_6) / ss + 0.5);
if (V <= T - E)
break;
if (V <= T + E) {
if (n != n_prev || par != p_prev) {
n_prev = n;
p_prev = par;
nm = n - m + 1;
ch = xm * Math.log((m + 1.0) / (pq * nm)) + DoubleArithmetic.stirlingCorrection(m + 1)
+ DoubleArithmetic.stirlingCorrection(nm);
}
nK = n - K + 1;
// computation of log f(K) via Stirling's formula
// final acceptance-rejection test
if (V <= ch + (n + 1.0) * Math.log((double) nm / (double) nK) + (K + 0.5)
* Math.log(nK * pq / (K + 1.0)) - DoubleArithmetic.stirlingCorrection(K + 1)
- DoubleArithmetic.stirlingCorrection(nK))
break;
}
}
}
return (p > 0.5) ? (n - K) : K;
}
/**
* Returns a random number from the distribution.
*/
public int nextInt() {
return generateBinomial(n, p);
}
/**
* Returns a random number from the distribution with the given parameters n
* and p; bypasses the internal state.
*
* @param n
* the number of trials
* @param p
* the probability of success.
* @throws IllegalArgumentException
* if <tt>n*Math.min(p,1-p) <= 0.0</tt>
*/
public int nextInt(int n, double p) {
if (n * Math.min(p, 1 - p) <= 0.0)
throw new IllegalArgumentException();
return generateBinomial(n, p);
}
/**
* Returns the probability distribution function.
*/
public double pdf(int k) {
if (k < 0)
throw new IllegalArgumentException();
int r = this.n - k;
return Math.exp(this.log_n - DoubleArithmetic.logFactorial(k) - DoubleArithmetic.logFactorial(r) + this.log_p
* k + this.log_q * r);
}
/**
* Sets the parameters number of trials and the probability of success.
*
* @param n
* the number of trials
* @param p
* the probability of success.
* @throws IllegalArgumentException
* if <tt>n*Math.min(p,1-p) <= 0.0</tt>
*/
public void setNandP(int n, double p) {
if (n * Math.min(p, 1 - p) <= 0.0)
throw new IllegalArgumentException();
this.n = n;
this.p = p;
this.log_p = Math.log(p);
this.log_q = Math.log(1.0 - p);
this.log_n = DoubleArithmetic.logFactorial(n);
}
/**
* Returns a random number from the distribution with the given parameters n
* and p.
*
* @param n
* the number of trials
* @param p
* the probability of success.
* @throws IllegalArgumentException
* if <tt>n*Math.min(p,1-p) <= 0.0</tt>
*/
public static int staticNextInt(int n, double p) {
synchronized (shared) {
return shared.nextInt(n, p);
}
}
/**
* Returns a String representation of the receiver.
*/
public String toString() {
return this.getClass().getName() + "(" + n + "," + p + ")";
}
/**
* Sets the uniform random number generated shared by all <b>static</b>
* methods.
*
* @param randomGenerator
* the new uniform random number generator to be shared.
*/
private static void xstaticSetRandomGenerator(DoubleRandomEngine randomGenerator) {
synchronized (shared) {
shared.setRandomGenerator(randomGenerator);
}
}
}
| gpl-3.0 |
UOC/PeLP | src/main/java/edu/uoc/pelp/model/vo/admin/PelpActiveSubjects.java | 4234 | /*
Copyright 2011-2012 Fundació per a la Universitat Oberta de Catalunya
This file is part of PeLP (Programming eLearning Plaform).
PeLP 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.
PeLP 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 edu.uoc.pelp.model.vo.admin;
import java.io.Serializable;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Entity class for table pelp_activeSubjects
* @author Xavier Baró
*/
@Entity
@Table(name = "PELP_activeSubjects")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PelpActiveSubjects.findAll", query = "SELECT p FROM PelpActiveSubjects p"),
@NamedQuery(name = "PelpActiveSubjects.findBySemester", query = "SELECT p FROM PelpActiveSubjects p WHERE p.pelpActiveSubjectsPK.semester = :semester"),
@NamedQuery(name = "PelpActiveSubjects.findBySubject", query = "SELECT p FROM PelpActiveSubjects p WHERE p.pelpActiveSubjectsPK.subject = :subject"),
@NamedQuery(name = "PelpActiveSubjects.findByActive", query = "SELECT p FROM PelpActiveSubjects p WHERE p.active = :active"),
@NamedQuery(name = "PelpActiveSubjects.findAllActive", query = "SELECT p FROM PelpActiveSubjects p WHERE p.active = 1"),
@NamedQuery(name = "PelpActiveSubjects.findActiveBySemesterSubject", query = "SELECT p FROM PelpActiveSubjects p WHERE p.pelpActiveSubjectsPK.semester = :semester AND p.pelpActiveSubjectsPK.subject = :subject AND p.active = 1"),
@NamedQuery(name = "PelpActiveSubjects.findActiveBySemester", query = "SELECT p FROM PelpActiveSubjects p WHERE p.pelpActiveSubjectsPK.semester = :semester AND p.active = 1"),
@NamedQuery(name = "PelpActiveSubjects.findByPK", query = "SELECT p FROM PelpActiveSubjects p WHERE p.pelpActiveSubjectsPK.semester = :semester AND p.pelpActiveSubjectsPK.subject = :subject")})
public class PelpActiveSubjects implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected PelpActiveSubjectsPK pelpActiveSubjectsPK;
@Column(name = "active")
private Boolean active;
public PelpActiveSubjects() {
}
public PelpActiveSubjects(PelpActiveSubjectsPK pelpActiveSubjectsPK) {
this.pelpActiveSubjectsPK = pelpActiveSubjectsPK;
}
public PelpActiveSubjects(String semester, String subject) {
this.pelpActiveSubjectsPK = new PelpActiveSubjectsPK(semester, subject);
}
public PelpActiveSubjectsPK getPelpActiveSubjectsPK() {
return pelpActiveSubjectsPK;
}
public void setPelpActiveSubjectsPK(PelpActiveSubjectsPK pelpActiveSubjectsPK) {
this.pelpActiveSubjectsPK = pelpActiveSubjectsPK;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
@Override
public int hashCode() {
int hash = 0;
hash += (pelpActiveSubjectsPK != null ? pelpActiveSubjectsPK.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 PelpActiveSubjects)) {
return false;
}
PelpActiveSubjects other = (PelpActiveSubjects) object;
if ((this.pelpActiveSubjectsPK == null && other.pelpActiveSubjectsPK != null) || (this.pelpActiveSubjectsPK != null && !this.pelpActiveSubjectsPK.equals(other.pelpActiveSubjectsPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "edu.uoc.pelp.model.vo.PelpActiveSubjects[ pelpActiveSubjectsPK=" + pelpActiveSubjectsPK + " ]";
}
}
| gpl-3.0 |
ImagoTrigger/sdrtrunk | src/main/java/io/github/dsheirer/audio/convert/thumbdv/message/response/AmbeResponse.java | 1842 | /*
*
* * ******************************************************************************
* * Copyright (C) 2014-2019 Dennis Sheirer
* *
* * 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 io.github.dsheirer.audio.convert.thumbdv.message.response;
import io.github.dsheirer.audio.convert.thumbdv.message.AmbeMessage;
import io.github.dsheirer.audio.convert.thumbdv.message.PacketField;
import java.util.Arrays;
/**
* AMBE-3000R Response Packet
*/
public abstract class AmbeResponse extends AmbeMessage
{
protected static final int PAYLOAD_START_INDEX = 5;
private byte[] mMessage;
protected AmbeResponse(byte[] message)
{
mMessage = message;
}
/**
* Control packet type
*/
public abstract PacketField getType();
/**
* Received message bytes
*/
protected byte[] getMessage()
{
return mMessage;
}
/**
* Payload of the packet (does not include the packet header)
*/
protected byte[] getPayload()
{
return Arrays.copyOfRange(getMessage(), PAYLOAD_START_INDEX, getMessage().length);
}
}
| gpl-3.0 |
cloudeecn/fiscevm | fiscevm-runtime/src/main/java/java/net/URLStreamHandler.java | 13483 | /*
* 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 java.net;
import java.io.IOException;
import org.apache.harmony.luni.util.URLUtil;
/**
* The abstract class {@code URLStreamHandler} is the base for all classes which
* can handle the communication with a URL object over a particular protocol
* type.
*/
public abstract class URLStreamHandler {
/**
* Establishes a new connection to the resource specified by the URL
* {@code u}. Since different protocols also have unique ways of connecting,
* it must be overwritten by the subclass.
*
* @param u
* the URL to the resource where a connection has to be opened.
* @return the opened URLConnection to the specified resource.
* @throws IOException
* if an I/O error occurs during opening the connection.
*/
protected abstract URLConnection openConnection(URL u) throws IOException;
/**
* Establishes a new connection to the resource specified by the URL
* {@code u} using the given {@code proxy}. Since different protocols also
* have unique ways of connecting, it must be overwritten by the subclass.
*
* @param u
* the URL to the resource where a connection has to be opened.
* @param proxy
* the proxy that is used to make the connection.
* @return the opened URLConnection to the specified resource.
* @throws IOException
* if an I/O error occurs during opening the connection.
* @throws IllegalArgumentException
* if any argument is {@code null} or the type of proxy is
* wrong.
* @throws UnsupportedOperationException
* if the protocol handler doesn't support this method.
*/
protected URLConnection openConnection(URL u, Proxy proxy)
throws IOException {
throw new UnsupportedOperationException(); //$NON-NLS-1$
}
/**
* Parses the clear text URL in {@code str} into a URL object. URL strings
* generally have the following format:
* <p>
* http://www.company.com/java/file1.java#reference
* <p>
* The string is parsed in HTTP format. If the protocol has a different URL
* format this method must be overridden.
*
* @param u
* the URL to fill in the parsed clear text URL parts.
* @param str
* the URL string that is to be parsed.
* @param start
* the string position from where to begin parsing.
* @param end
* the string position to stop parsing.
* @see #toExternalForm
* @see URL
*/
protected void parseURL(URL u, String str, int start, int end) {
if (end < start || end < 0) {
// Checks to ensure string index exception ahead of
// security exception for compatibility.
if (end <= Integer.MIN_VALUE + 1
&& (start >= str.length() || start < 0)
|| str.startsWith("//", start) && str.indexOf('/', start + 2) == -1) { //$NON-NLS-1$
throw new StringIndexOutOfBoundsException(end);
}
if (this != u.strmHandler) {
throw new RuntimeException();
}
return;
}
String parseString = str.substring(start, end);
end -= start;
int fileIdx = 0;
// Default is to use info from context
String host = u.getHost();
int port = u.getPort();
String ref = u.getRef();
String file = u.getPath();
String query = u.getQuery();
String authority = u.getAuthority();
String userInfo = u.getUserInfo();
int refIdx = parseString.indexOf('#', 0);
if (parseString.startsWith("//") && !parseString.startsWith("////")) { //$NON-NLS-1$
int hostIdx = 2, portIdx = -1;
port = -1;
fileIdx = parseString.indexOf('/', hostIdx);
int questionMarkIndex = parseString.indexOf('?', hostIdx);
if ((questionMarkIndex != -1)
&& ((fileIdx == -1) || (fileIdx > questionMarkIndex))) {
fileIdx = questionMarkIndex;
}
if (fileIdx == -1) {
fileIdx = end;
// Use default
file = ""; //$NON-NLS-1$
}
int hostEnd = fileIdx;
if (refIdx != -1 && refIdx < fileIdx) {
hostEnd = refIdx;
}
int userIdx = parseString.lastIndexOf('@', hostEnd);
authority = parseString.substring(hostIdx, hostEnd);
if (userIdx > -1) {
userInfo = parseString.substring(hostIdx, userIdx);
hostIdx = userIdx + 1;
}
portIdx = parseString.indexOf(':', userIdx == -1 ? hostIdx
: userIdx);
int endOfIPv6Addr = parseString.indexOf(']');
// if there are square braces, ie. IPv6 address, use last ':'
if (endOfIPv6Addr != -1) {
try {
if (parseString.length() > endOfIPv6Addr + 1) {
char c = parseString.charAt(endOfIPv6Addr + 1);
if (c == ':') {
portIdx = endOfIPv6Addr + 1;
} else {
portIdx = -1;
}
} else {
portIdx = -1;
}
} catch (Exception e) {
// Ignored
}
}
if (portIdx == -1 || portIdx > fileIdx) {
host = parseString.substring(hostIdx, hostEnd);
} else {
host = parseString.substring(hostIdx, portIdx);
String portString = parseString.substring(portIdx + 1, hostEnd);
if (portString.length() == 0) {
port = -1;
} else {
port = Integer.parseInt(portString);
}
}
}
if (refIdx > -1) {
ref = parseString.substring(refIdx + 1, end);
}
int fileEnd = (refIdx == -1 ? end : refIdx);
int queryIdx = parseString.lastIndexOf('?', fileEnd);
boolean canonicalize = false;
if (queryIdx > -1) {
query = parseString.substring(queryIdx + 1, fileEnd);
if (queryIdx == 0 && file != null) {
if (file.equals("")) { //$NON-NLS-1$
file = "/"; //$NON-NLS-1$
} else if (file.startsWith("/")) { //$NON-NLS-1$
canonicalize = true;
}
int last = file.lastIndexOf('/') + 1;
file = file.substring(0, last);
}
fileEnd = queryIdx;
} else
// Don't inherit query unless only the ref is changed
if (refIdx != 0) {
query = null;
}
if (fileIdx > -1) {
if (fileIdx < end && parseString.charAt(fileIdx) == '/') {
file = parseString.substring(fileIdx, fileEnd);
} else if (fileEnd > fileIdx) {
if (file == null) {
file = ""; //$NON-NLS-1$
} else if (file.equals("")) { //$NON-NLS-1$
file = "/"; //$NON-NLS-1$
} else if (file.startsWith("/")) { //$NON-NLS-1$
canonicalize = true;
}
int last = file.lastIndexOf('/') + 1;
if (last == 0) {
file = parseString.substring(fileIdx, fileEnd);
} else {
file = file.substring(0, last)
+ parseString.substring(fileIdx, fileEnd);
}
}
}
if (file == null) {
file = ""; //$NON-NLS-1$
}
if (host == null) {
host = ""; //$NON-NLS-1$
}
if (canonicalize) {
// modify file if there's any relative referencing
file = URLUtil.canonicalizePath(file);
}
setURL(u, u.getProtocol(), host, port, authority, userInfo, file,
query, ref);
}
/**
* Sets the fields of the URL {@code u} to the values of the supplied
* arguments.
*
* @param u
* the non-null URL object to be set.
* @param protocol
* the protocol.
* @param host
* the host name.
* @param port
* the port number.
* @param file
* the file component.
* @param ref
* the reference.
* @deprecated use setURL(URL, String String, int, String, String, String,
* String, String) instead.
*/
protected void setURL(URL u, String protocol, String host, int port,
String file, String ref) {
if (this != u.strmHandler) {
throw new RuntimeException();
}
u.set(protocol, host, port, file, ref);
}
/**
* Sets the fields of the URL {@code u} to the values of the supplied
* arguments.
*
* @param u
* the non-null URL object to be set.
* @param protocol
* the protocol.
* @param host
* the host name.
* @param port
* the port number.
* @param authority
* the authority.
* @param userInfo
* the user info.
* @param file
* the file component.
* @param query
* the query.
* @param ref
* the reference.
*/
protected void setURL(URL u, String protocol, String host, int port,
String authority, String userInfo, String file, String query,
String ref) {
if (this != u.strmHandler) {
throw new RuntimeException();
}
u.set(protocol, host, port, authority, userInfo, file, query, ref);
}
/**
* Returns the clear text representation of a given URL using HTTP format.
*
* @param url
* the URL object to be converted.
* @return the clear text representation of the specified URL.
* @see #parseURL
* @see URL#toExternalForm()
*/
protected String toExternalForm(URL url) {
StringBuilder answer = new StringBuilder();
answer.append(url.getProtocol());
answer.append(':');
String authority = url.getAuthority();
if (authority != null && authority.length() > 0) {
answer.append("//"); //$NON-NLS-1$
answer.append(url.getAuthority());
}
String file = url.getFile();
String ref = url.getRef();
if (file != null) {
answer.append(file);
}
if (ref != null) {
answer.append('#');
answer.append(ref);
}
return answer.toString();
}
/**
* Compares two URL objects whether they represent the same URL. Two URLs
* are equal if they have the same file, host, port, protocol, query, and
* reference components.
*
* @param url1
* the first URL to compare.
* @param url2
* the second URL to compare.
* @return {@code true} if the URLs are the same, {@code false} otherwise.
* @see #hashCode
*/
protected boolean equals(URL url1, URL url2) {
if (!sameFile(url1, url2)) {
return false;
}
String s1 = url1.getRef(), s2 = url2.getRef();
if (s1 != s2 && (s1 == null || !s1.equals(s2))) {
return false;
}
s1 = url1.getQuery();
s2 = url2.getQuery();
return s1 == s2 || (s1 != null && s1.equals(s2));
}
/**
* Returns the default port of the protocol used by the handled URL. The
* current implementation returns always {@code -1}.
*
* @return the appropriate default port number of the protocol.
*/
protected int getDefaultPort() {
return -1;
}
/**
* Returns the host address of the given URL.
*
* @param url
* the URL object where to read the host address from.
* @return the host address of the specified URL.
*/
protected Object getHostAddress(URL url) {
return null;
}
/**
* Returns the hashcode value for the given URL object.
*
* @param url
* the URL to determine the hashcode.
* @return the hashcode of the given URL.
*/
protected int hashCode(URL url) {
return toExternalForm(url).hashCode();
}
/**
* Compares two URL objects whether they refer to the same host.
*
* @param url1
* the first URL to be compared.
* @param url2
* the second URL to be compared.
* @return {@code true} if both URLs refer to the same host, {@code false}
* otherwise.
*/
protected boolean hostsEqual(URL url1, URL url2) {
// Compare by addresses if known.
return url1.equals(url2);
}
/**
* Compares two URL objects whether they refer to the same file. In the
* comparison included are the URL components protocol, host, port and file.
*
* @param url1
* the first URL to be compared.
* @param url2
* the second URL to be compared.
* @return {@code true} if both URLs refer to the same file, {@code false}
* otherwise.
*/
protected boolean sameFile(URL url1, URL url2) {
String s1 = url1.getProtocol();
String s2 = url2.getProtocol();
if (s1 != s2 && (s1 == null || !s1.equals(s2))) {
return false;
}
s1 = url1.getFile();
s2 = url2.getFile();
if (s1 != s2 && (s1 == null || !s1.equals(s2))) {
return false;
}
if (!hostsEqual(url1, url2)) {
return false;
}
int p1 = url1.getPort();
if (p1 == -1) {
p1 = getDefaultPort();
}
int p2 = url2.getPort();
if (p2 == -1) {
p2 = getDefaultPort();
}
return p1 == p2;
}
/*
* If the URL host is empty while protocol is file, the host is regarded as
* localhost.
*/
private static String getHost(URL url) {
String host = url.getHost();
if ("file".equals(url.getProtocol()) //$NON-NLS-1$
&& "".equals(host)) { //$NON-NLS-1$
host = "localhost"; //$NON-NLS-1$
}
return host;
}
}
| gpl-3.0 |