repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Apelon-VA/va-isaac-gui | import-export/src/main/java/org/hl7/vmr/r2/ObjectFactory.java | 17884 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.09.30 at 06:15:10 PM PDT
//
package org.hl7.vmr.r2;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.hl7.vmr.r2 package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _VMR_QNAME = new QName("urn:hl7-org:vmr:r2", "vMR");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.hl7.vmr.r2
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link VMR }
*
*/
public VMR createVMR() {
return new VMR();
}
/**
* Create an instance of {@link SubstanceAdministrationOrder }
*
*/
public SubstanceAdministrationOrder createSubstanceAdministrationOrder() {
return new SubstanceAdministrationOrder();
}
/**
* Create an instance of {@link Qualification }
*
*/
public Qualification createQualification() {
return new Qualification();
}
/**
* Create an instance of {@link SubstanceDispenseEvent }
*
*/
public SubstanceDispenseEvent createSubstanceDispenseEvent() {
return new SubstanceDispenseEvent();
}
/**
* Create an instance of {@link EnteralFeedingDispenseProposal }
*
*/
public EnteralFeedingDispenseProposal createEnteralFeedingDispenseProposal() {
return new EnteralFeedingDispenseProposal();
}
/**
* Create an instance of {@link ObservationResult }
*
*/
public ObservationResult createObservationResult() {
return new ObservationResult();
}
/**
* Create an instance of {@link RadiotherapyOrder }
*
*/
public RadiotherapyOrder createRadiotherapyOrder() {
return new RadiotherapyOrder();
}
/**
* Create an instance of {@link RelatedClinicalStatement }
*
*/
public RelatedClinicalStatement createRelatedClinicalStatement() {
return new RelatedClinicalStatement();
}
/**
* Create an instance of {@link ImagingOrder }
*
*/
public ImagingOrder createImagingOrder() {
return new ImagingOrder();
}
/**
* Create an instance of {@link SubstanceDispenseOrder }
*
*/
public SubstanceDispenseOrder createSubstanceDispenseOrder() {
return new SubstanceDispenseOrder();
}
/**
* Create an instance of {@link ClinicalStatement }
*
*/
public ClinicalStatement createClinicalStatement() {
return new ClinicalStatement();
}
/**
* Create an instance of {@link ScheduledAppointment }
*
*/
public ScheduledAppointment createScheduledAppointment() {
return new ScheduledAppointment();
}
/**
* Create an instance of {@link LaboratoryProposal }
*
*/
public LaboratoryProposal createLaboratoryProposal() {
return new LaboratoryProposal();
}
/**
* Create an instance of {@link SubstanceDispenseProposal }
*
*/
public SubstanceDispenseProposal createSubstanceDispenseProposal() {
return new SubstanceDispenseProposal();
}
/**
* Create an instance of {@link ProcedureEvent }
*
*/
public ProcedureEvent createProcedureEvent() {
return new ProcedureEvent();
}
/**
* Create an instance of {@link DoseRestriction }
*
*/
public DoseRestriction createDoseRestriction() {
return new DoseRestriction();
}
/**
* Create an instance of {@link AdverseEvent }
*
*/
public AdverseEvent createAdverseEvent() {
return new AdverseEvent();
}
/**
* Create an instance of {@link CompositeSubstanceOrder }
*
*/
public CompositeSubstanceOrder createCompositeSubstanceOrder() {
return new CompositeSubstanceOrder();
}
/**
* Create an instance of {@link TextureModification }
*
*/
public TextureModification createTextureModification() {
return new TextureModification();
}
/**
* Create an instance of {@link GoalProposal }
*
*/
public GoalProposal createGoalProposal() {
return new GoalProposal();
}
/**
* Create an instance of {@link RadiotherapyProposal }
*
*/
public RadiotherapyProposal createRadiotherapyProposal() {
return new RadiotherapyProposal();
}
/**
* Create an instance of {@link CodedRecurringEvent }
*
*/
public CodedRecurringEvent createCodedRecurringEvent() {
return new CodedRecurringEvent();
}
/**
* Create an instance of {@link ProcedureProposal }
*
*/
public ProcedureProposal createProcedureProposal() {
return new ProcedureProposal();
}
/**
* Create an instance of {@link Cycle }
*
*/
public Cycle createCycle() {
return new Cycle();
}
/**
* Create an instance of {@link PCAProposal }
*
*/
public PCAProposal createPCAProposal() {
return new PCAProposal();
}
/**
* Create an instance of {@link Practitioner }
*
*/
public Practitioner createPractitioner() {
return new Practitioner();
}
/**
* Create an instance of {@link StringNameValuePair }
*
*/
public StringNameValuePair createStringNameValuePair() {
return new StringNameValuePair();
}
/**
* Create an instance of {@link UndeliveredProcedure }
*
*/
public UndeliveredProcedure createUndeliveredProcedure() {
return new UndeliveredProcedure();
}
/**
* Create an instance of {@link EvaluatedPerson }
*
*/
public EvaluatedPerson createEvaluatedPerson() {
return new EvaluatedPerson();
}
/**
* Create an instance of {@link Schedule }
*
*/
public Schedule createSchedule() {
return new Schedule();
}
/**
* Create an instance of {@link AdministrableSubstance }
*
*/
public AdministrableSubstance createAdministrableSubstance() {
return new AdministrableSubstance();
}
/**
* Create an instance of {@link MissedAppointment }
*
*/
public MissedAppointment createMissedAppointment() {
return new MissedAppointment();
}
/**
* Create an instance of {@link SupplyEvent }
*
*/
public SupplyEvent createSupplyEvent() {
return new SupplyEvent();
}
/**
* Create an instance of {@link DeniedAllergyOrIntolerance }
*
*/
public DeniedAllergyOrIntolerance createDeniedAllergyOrIntolerance() {
return new DeniedAllergyOrIntolerance();
}
/**
* Create an instance of {@link ProcedureOrder }
*
*/
public ProcedureOrder createProcedureOrder() {
return new ProcedureOrder();
}
/**
* Create an instance of {@link EnteralFeedingDispenseOrder }
*
*/
public EnteralFeedingDispenseOrder createEnteralFeedingDispenseOrder() {
return new EnteralFeedingDispenseOrder();
}
/**
* Create an instance of {@link BodySite }
*
*/
public BodySite createBodySite() {
return new BodySite();
}
/**
* Create an instance of {@link RelatedEvaluatedPerson }
*
*/
public RelatedEvaluatedPerson createRelatedEvaluatedPerson() {
return new RelatedEvaluatedPerson();
}
/**
* Create an instance of {@link AllergyOrIntolerance }
*
*/
public AllergyOrIntolerance createAllergyOrIntolerance() {
return new AllergyOrIntolerance();
}
/**
* Create an instance of {@link DeniedAdverseEvent }
*
*/
public DeniedAdverseEvent createDeniedAdverseEvent() {
return new DeniedAdverseEvent();
}
/**
* Create an instance of {@link NoKnownAllergy }
*
*/
public NoKnownAllergy createNoKnownAllergy() {
return new NoKnownAllergy();
}
/**
* Create an instance of {@link RespiratoryCareOrder }
*
*/
public RespiratoryCareOrder createRespiratoryCareOrder() {
return new RespiratoryCareOrder();
}
/**
* Create an instance of {@link AppointmentRequest }
*
*/
public AppointmentRequest createAppointmentRequest() {
return new AppointmentRequest();
}
/**
* Create an instance of {@link SupplyProposal }
*
*/
public SupplyProposal createSupplyProposal() {
return new SupplyProposal();
}
/**
* Create an instance of {@link DeniedProblem }
*
*/
public DeniedProblem createDeniedProblem() {
return new DeniedProblem();
}
/**
* Create an instance of {@link Constituent }
*
*/
public Constituent createConstituent() {
return new Constituent();
}
/**
* Create an instance of {@link Facility }
*
*/
public Facility createFacility() {
return new Facility();
}
/**
* Create an instance of {@link OralDietOrder }
*
*/
public OralDietOrder createOralDietOrder() {
return new OralDietOrder();
}
/**
* Create an instance of {@link EnteralFeedingOrder }
*
*/
public EnteralFeedingOrder createEnteralFeedingOrder() {
return new EnteralFeedingOrder();
}
/**
* Create an instance of {@link Person }
*
*/
public Person createPerson() {
return new Person();
}
/**
* Create an instance of {@link ScheduledProcedure }
*
*/
public ScheduledProcedure createScheduledProcedure() {
return new ScheduledProcedure();
}
/**
* Create an instance of {@link UndeliveredSupply }
*
*/
public UndeliveredSupply createUndeliveredSupply() {
return new UndeliveredSupply();
}
/**
* Create an instance of {@link Organization }
*
*/
public Organization createOrganization() {
return new Organization();
}
/**
* Create an instance of {@link OralDietProposal }
*
*/
public OralDietProposal createOralDietProposal() {
return new OralDietProposal();
}
/**
* Create an instance of {@link CommunicationOrder }
*
*/
public CommunicationOrder createCommunicationOrder() {
return new CommunicationOrder();
}
/**
* Create an instance of {@link SupplyOrder }
*
*/
public SupplyOrder createSupplyOrder() {
return new SupplyOrder();
}
/**
* Create an instance of {@link CommunicationProposal }
*
*/
public CommunicationProposal createCommunicationProposal() {
return new CommunicationProposal();
}
/**
* Create an instance of {@link SubstanceAdministrationEvent }
*
*/
public SubstanceAdministrationEvent createSubstanceAdministrationEvent() {
return new SubstanceAdministrationEvent();
}
/**
* Create an instance of {@link Dose }
*
*/
public Dose createDose() {
return new Dose();
}
/**
* Create an instance of {@link Value }
*
*/
public Value createValue() {
return new Value();
}
/**
* Create an instance of {@link AnchoredEvent }
*
*/
public AnchoredEvent createAnchoredEvent() {
return new AnchoredEvent();
}
/**
* Create an instance of {@link CommunicationEvent }
*
*/
public CommunicationEvent createCommunicationEvent() {
return new CommunicationEvent();
}
/**
* Create an instance of {@link CompositeObservationResult }
*
*/
public CompositeObservationResult createCompositeObservationResult() {
return new CompositeObservationResult();
}
/**
* Create an instance of {@link RecurringEvent }
*
*/
public RecurringEvent createRecurringEvent() {
return new RecurringEvent();
}
/**
* Create an instance of {@link RelatedEntity }
*
*/
public RelatedEntity createRelatedEntity() {
return new RelatedEntity();
}
/**
* Create an instance of {@link Problem }
*
*/
public Problem createProblem() {
return new Problem();
}
/**
* Create an instance of {@link ImagingProposal }
*
*/
public ImagingProposal createImagingProposal() {
return new ImagingProposal();
}
/**
* Create an instance of {@link NutrientModification }
*
*/
public NutrientModification createNutrientModification() {
return new NutrientModification();
}
/**
* Create an instance of {@link RespiratoryCareProposal }
*
*/
public RespiratoryCareProposal createRespiratoryCareProposal() {
return new RespiratoryCareProposal();
}
/**
* Create an instance of {@link EnteralFeedingProposal }
*
*/
public EnteralFeedingProposal createEnteralFeedingProposal() {
return new EnteralFeedingProposal();
}
/**
* Create an instance of {@link PCAOrder }
*
*/
public PCAOrder createPCAOrder() {
return new PCAOrder();
}
/**
* Create an instance of {@link SubstanceAdministrationProposal }
*
*/
public SubstanceAdministrationProposal createSubstanceAdministrationProposal() {
return new SubstanceAdministrationProposal();
}
/**
* Create an instance of {@link Entity }
*
*/
public Entity createEntity() {
return new Entity();
}
/**
* Create an instance of {@link Documentation }
*
*/
public Documentation createDocumentation() {
return new Documentation();
}
/**
* Create an instance of {@link Device }
*
*/
public Device createDevice() {
return new Device();
}
/**
* Create an instance of {@link MotionManagement }
*
*/
public MotionManagement createMotionManagement() {
return new MotionManagement();
}
/**
* Create an instance of {@link EncounterEvent }
*
*/
public EncounterEvent createEncounterEvent() {
return new EncounterEvent();
}
/**
* Create an instance of {@link RadiotherapySimulation }
*
*/
public RadiotherapySimulation createRadiotherapySimulation() {
return new RadiotherapySimulation();
}
/**
* Create an instance of {@link LocalizationMethod }
*
*/
public LocalizationMethod createLocalizationMethod() {
return new LocalizationMethod();
}
/**
* Create an instance of {@link VaccinationProtocol }
*
*/
public VaccinationProtocol createVaccinationProtocol() {
return new VaccinationProtocol();
}
/**
* Create an instance of {@link Goal }
*
*/
public Goal createGoal() {
return new Goal();
}
/**
* Create an instance of {@link LaboratoryOrder }
*
*/
public LaboratoryOrder createLaboratoryOrder() {
return new LaboratoryOrder();
}
/**
* Create an instance of {@link NameValuePair }
*
*/
public NameValuePair createNameValuePair() {
return new NameValuePair();
}
/**
* Create an instance of {@link GroupingClinicalStatement }
*
*/
public GroupingClinicalStatement createGroupingClinicalStatement() {
return new GroupingClinicalStatement();
}
/**
* Create an instance of {@link CompositeSubstanceProposal }
*
*/
public CompositeSubstanceProposal createCompositeSubstanceProposal() {
return new CompositeSubstanceProposal();
}
/**
* Create an instance of {@link UndeliveredSubstanceAdministration }
*
*/
public UndeliveredSubstanceAdministration createUndeliveredSubstanceAdministration() {
return new UndeliveredSubstanceAdministration();
}
/**
* Create an instance of {@link Specimen }
*
*/
public Specimen createSpecimen() {
return new Specimen();
}
/**
* Create an instance of {@link CodedIdentifier }
*
*/
public CodedIdentifier createCodedIdentifier() {
return new CodedIdentifier();
}
/**
* Create an instance of {@link AppointmentProposal }
*
*/
public AppointmentProposal createAppointmentProposal() {
return new AppointmentProposal();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link VMR }{@code >}}
*
*/
@XmlElementDecl(namespace = "urn:hl7-org:vmr:r2", name = "vMR")
public JAXBElement<VMR> createVMR(VMR value) {
return new JAXBElement<VMR>(_VMR_QNAME, VMR.class, null, value);
}
}
| apache-2.0 |
guozhangwang/kafka | clients/src/main/java/org/apache/kafka/common/protocol/DataInputStreamReadable.java | 3514 | /*
* 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.kafka.common.protocol;
import org.apache.kafka.common.utils.ByteUtils;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class DataInputStreamReadable implements Readable, Closeable {
protected final DataInputStream input;
public DataInputStreamReadable(DataInputStream input) {
this.input = input;
}
@Override
public byte readByte() {
try {
return input.readByte();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public short readShort() {
try {
return input.readShort();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public int readInt() {
try {
return input.readInt();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public long readLong() {
try {
return input.readLong();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public double readDouble() {
try {
return input.readDouble();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void readArray(byte[] arr) {
try {
input.readFully(arr);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public int readUnsignedVarint() {
try {
return ByteUtils.readUnsignedVarint(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public ByteBuffer readByteBuffer(int length) {
byte[] arr = new byte[length];
readArray(arr);
return ByteBuffer.wrap(arr);
}
@Override
public int readVarint() {
try {
return ByteUtils.readVarint(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public long readVarlong() {
try {
return ByteUtils.readVarlong(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public int remaining() {
try {
return input.available();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
try {
input.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| apache-2.0 |
tufangorel/hazelcast | hazelcast/src/main/java/com/hazelcast/multimap/impl/txn/TxnCommitBackupOperation.java | 2826 | /*
* Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.hazelcast.multimap.impl.txn;
import com.hazelcast.multimap.impl.MultiMapDataSerializerHook;
import com.hazelcast.multimap.impl.operations.AbstractKeyBasedMultiMapOperation;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.BackupOperation;
import com.hazelcast.spi.Operation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TxnCommitBackupOperation extends AbstractKeyBasedMultiMapOperation implements BackupOperation {
private List<Operation> opList;
private String caller;
public TxnCommitBackupOperation() {
}
public TxnCommitBackupOperation(String name, Data dataKey, List<Operation> opList, String caller, long threadId) {
super(name, dataKey);
this.opList = opList;
this.caller = caller;
this.threadId = threadId;
}
@Override
public void run() throws Exception {
for (Operation op : opList) {
op.setNodeEngine(getNodeEngine()).setServiceName(getServiceName()).setPartitionId(getPartitionId());
op.beforeRun();
op.run();
op.afterRun();
}
// changed to forceUnlock because replica-sync of lock causes problems, same as IMap
// real solution is to make 'lock-and-get' backup-aware
getOrCreateContainerWithoutAccess().forceUnlock(dataKey);
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(opList.size());
for (Operation op : opList) {
out.writeObject(op);
}
out.writeUTF(caller);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
int size = in.readInt();
opList = new ArrayList<Operation>(size);
for (int i = 0; i < size; i++) {
opList.add((Operation) in.readObject());
}
caller = in.readUTF();
}
@Override
public int getId() {
return MultiMapDataSerializerHook.TXN_COMMIT_BACKUP;
}
}
| apache-2.0 |
ascrutae/sky-walking | oap-server/server-core/src/main/java/org/apache/skywalking/oap/server/core/analysis/metrics/expression/NumberMatch.java | 1186 | /*
* 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.skywalking.oap.server.core.analysis.metrics.expression;
import org.apache.skywalking.oap.server.core.analysis.metrics.annotation.FilterMatcher;
@FilterMatcher
public class NumberMatch {
public boolean match(int left, int right) {
return left == right;
}
public boolean match(long left, long right) {
return left == right;
}
}
| apache-2.0 |
heriram/incubator-asterixdb | hyracks-fullstack/hyracks/hyracks-tests/hyracks-storage-am-rtree-test/src/test/java/org/apache/hyracks/storage/am/rtree/RTreeExamplesTest.java | 2568 | /*
* 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.hyracks.storage.am.rtree;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.storage.am.common.api.IPrimitiveValueProviderFactory;
import org.apache.hyracks.storage.am.common.api.ITreeIndex;
import org.apache.hyracks.storage.am.rtree.frames.RTreePolicyType;
import org.apache.hyracks.storage.am.rtree.util.RTreeUtils;
import org.apache.hyracks.storage.am.rtree.utils.RTreeTestHarness;
import org.junit.After;
import org.junit.Before;
public class RTreeExamplesTest extends AbstractRTreeExamplesTest {
private final RTreeTestHarness harness = new RTreeTestHarness();
public RTreeExamplesTest() {
super();
this.rTreeType = RTreeType.RTREE;
}
@Before
public void setUp() throws HyracksDataException {
harness.setUp();
}
@After
public void tearDown() throws HyracksDataException {
harness.tearDown();
}
@Override
protected ITreeIndex createTreeIndex(ITypeTraits[] typeTraits, IBinaryComparatorFactory[] rtreeCmpFactories,
IBinaryComparatorFactory[] btreeCmpFactories, IPrimitiveValueProviderFactory[] valueProviderFactories,
RTreePolicyType rtreePolicyType, int[] rtreeFields, int[] btreeFields, ITypeTraits[] filterTypeTraits,
IBinaryComparatorFactory[] filterCmpFactories, int[] filterFields) throws HyracksDataException {
return RTreeUtils.createRTree(harness.getBufferCache(), typeTraits, valueProviderFactories, rtreeCmpFactories,
rtreePolicyType, harness.getFileReference(), false, harness.getMetadataManagerFactory());
}
}
| apache-2.0 |
cdjackson/zigbee4java | zigbee-common/src/main/java/org/bubblecloud/zigbee/util/Cie.java | 2314 | package org.bubblecloud.zigbee.util;
/**
* Provides methods to convert colours from RGB to CIE colour space.
* <p>
* The CIE XYZ color space encompasses all color sensations that an average
* person can experience. It serves as a standard reference against which many
* other color spaces are defined.
*/
public class Cie {
public double x;
public double y;
public double Y;
public static Cie rgb2cie2(double R, double G, double B) {
double X = 0.412315f*R + 0.357600f*G + 0.180500f*B;
double Y = 0.212600f*R + 0.715200f*G + 0.072200f*B;
double Z = 0.019327f*R + 0.119200f*G + 0.950633f*B;
Cie cie = new Cie();
cie.x = X / (X + Y + Z);
cie.y = Y / (X + Y + Z);
cie.Y = Y;
return cie;
}
public static Cie rgb2cie(double r, double g, double b) {
double X, Y, Z;
if (r <= 0.04045)
r = r/12;
else
r = (float) Math.pow((r+0.055)/1.055,2.4);
if (g <= 0.04045)
g = g/12;
else
g = (float) Math.pow((g+0.055)/1.055,2.4);
if (b <= 0.04045)
b = b/12;
else
b = (float) Math.pow((b+0.055)/1.055,2.4);
X = 0.436052025f*r + 0.385081593f*g + 0.143087414f *b;
Y = 0.222491598f*r + 0.71688606f *g + 0.060621486f *b;
Z = 0.013929122f*r + 0.097097002f*g + 0.71418547f *b;
double x;
double y;
double sum = X + Y + Z;
if (sum != 0) {
x = X / sum;
y = Y / sum;
}
else {
float Xr = 0.964221f; // reference white
float Yr = 1.0f;
float Zr = 0.825211f;
x = Xr / (Xr + Yr + Zr);
y = Yr / (Xr + Yr + Zr);
}
Cie cie = new Cie();
cie.x = x;
cie.y = y;
cie.Y = Y;
return cie;
}
public static Cie rgb2cie3(double R, double G, double B) {
double X = 0.436052025f*R + 0.385081593f*G + 0.143087414f*B;
double Y = 0.222491598f*R + 0.71688606f*G + 0.060621486f*B;
double Z = 0.013929122f*R + 0.097097002f*G + 0.71418547f*B;
Cie cie = new Cie();
cie.x = X / (X + Y + Z);
cie.y = Y / (X + Y + Z);
cie.Y = Y;
return cie;
}
}
| apache-2.0 |
camunda/camunda-dmn-model | src/test/java/org/camunda/bpm/model/dmn/instance/InputClauseTest.java | 1590 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.model.dmn.instance;
import static org.camunda.bpm.model.dmn.impl.DmnModelConstants.CAMUNDA_NS;
import java.util.Arrays;
import java.util.Collection;
public class InputClauseTest extends DmnModelElementInstanceTest {
public TypeAssumption getTypeAssumption() {
return new TypeAssumption(DmnElement.class, false);
}
public Collection<ChildElementAssumption> getChildElementAssumptions() {
return Arrays.asList(
new ChildElementAssumption(InputExpression.class, 1, 1),
new ChildElementAssumption(InputValues.class, 0, 1)
);
}
public Collection<AttributeAssumption> getAttributesAssumptions() {
return Arrays.asList(
// camunda extensions
new AttributeAssumption(CAMUNDA_NS, "inputVariable")
);
}
}
| apache-2.0 |
ern/elasticsearch | server/src/main/java/org/elasticsearch/index/translog/TruncateTranslogAction.java | 11123 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.index.translog;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.store.Directory;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.seqno.SequenceNumbers;
import org.elasticsearch.index.shard.RemoveCorruptedShardDataCommand;
import org.elasticsearch.index.shard.ShardPath;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class TruncateTranslogAction {
protected static final Logger logger = LogManager.getLogger(TruncateTranslogAction.class);
private final NamedXContentRegistry namedXContentRegistry;
public TruncateTranslogAction(NamedXContentRegistry namedXContentRegistry) {
this.namedXContentRegistry = namedXContentRegistry;
}
public Tuple<RemoveCorruptedShardDataCommand.CleanStatus, String> getCleanStatus(ShardPath shardPath,
ClusterState clusterState,
Directory indexDirectory) throws IOException {
final Path indexPath = shardPath.resolveIndex();
final Path translogPath = shardPath.resolveTranslog();
final List<IndexCommit> commits;
try {
commits = DirectoryReader.listCommits(indexDirectory);
} catch (IndexNotFoundException infe) {
throw new ElasticsearchException("unable to find a valid shard at [" + indexPath + "]", infe);
} catch (IOException e) {
throw new ElasticsearchException("unable to list commits at [" + indexPath + "]", e);
}
// Retrieve the generation and UUID from the existing data
final Map<String, String> commitData = new HashMap<>(commits.get(commits.size() - 1).getUserData());
final String translogUUID = commitData.get(Translog.TRANSLOG_UUID_KEY);
if (translogUUID == null) {
throw new ElasticsearchException("shard must have a valid translog UUID but got: [null]");
}
final boolean clean = isTranslogClean(shardPath, clusterState, translogUUID);
if (clean) {
return Tuple.tuple(RemoveCorruptedShardDataCommand.CleanStatus.CLEAN, null);
}
// Hold the lock open for the duration of the tool running
Set<Path> translogFiles;
try {
translogFiles = filesInDirectory(translogPath);
} catch (IOException e) {
throw new ElasticsearchException("failed to find existing translog files", e);
}
final String details = deletingFilesDetails(translogPath, translogFiles);
return Tuple.tuple(RemoveCorruptedShardDataCommand.CleanStatus.CORRUPTED, details);
}
public void execute(Terminal terminal, ShardPath shardPath, Directory indexDirectory) throws IOException {
final Path indexPath = shardPath.resolveIndex();
final Path translogPath = shardPath.resolveTranslog();
final String historyUUID = UUIDs.randomBase64UUID();
final Map<String, String> commitData;
// Hold the lock open for the duration of the tool running
Set<Path> translogFiles;
try {
terminal.println("Checking existing translog files");
translogFiles = filesInDirectory(translogPath);
} catch (IOException e) {
terminal.println("encountered IOException while listing directory, aborting...");
throw new ElasticsearchException("failed to find existing translog files", e);
}
List<IndexCommit> commits;
try {
terminal.println("Reading translog UUID information from Lucene commit from shard at [" + indexPath + "]");
commits = DirectoryReader.listCommits(indexDirectory);
} catch (IndexNotFoundException infe) {
throw new ElasticsearchException("unable to find a valid shard at [" + indexPath + "]", infe);
}
// Retrieve the generation and UUID from the existing data
commitData = commits.get(commits.size() - 1).getUserData();
final String translogUUID = commitData.get(Translog.TRANSLOG_UUID_KEY);
if (translogUUID == null) {
throw new ElasticsearchException("shard must have a valid translog UUID");
}
final long globalCheckpoint = commitData.containsKey(SequenceNumbers.MAX_SEQ_NO)
? Long.parseLong(commitData.get(SequenceNumbers.MAX_SEQ_NO))
: SequenceNumbers.UNASSIGNED_SEQ_NO;
terminal.println("Translog UUID : " + translogUUID);
terminal.println("History UUID : " + historyUUID);
Path tempEmptyCheckpoint = translogPath.resolve("temp-" + Translog.CHECKPOINT_FILE_NAME);
Path realEmptyCheckpoint = translogPath.resolve(Translog.CHECKPOINT_FILE_NAME);
final long gen = 1;
Path tempEmptyTranslog = translogPath.resolve("temp-" + Translog.TRANSLOG_FILE_PREFIX + gen + Translog.TRANSLOG_FILE_SUFFIX);
Path realEmptyTranslog = translogPath.resolve(Translog.TRANSLOG_FILE_PREFIX + gen + Translog.TRANSLOG_FILE_SUFFIX);
// Write empty checkpoint and translog to empty files
int translogLen = writeEmptyTranslog(tempEmptyTranslog, translogUUID);
writeEmptyCheckpoint(tempEmptyCheckpoint, translogLen, gen, globalCheckpoint);
terminal.println("Removing existing translog files");
IOUtils.rm(translogFiles.toArray(new Path[]{}));
terminal.println("Creating new empty checkpoint at [" + realEmptyCheckpoint + "]");
Files.move(tempEmptyCheckpoint, realEmptyCheckpoint, StandardCopyOption.ATOMIC_MOVE);
terminal.println("Creating new empty translog at [" + realEmptyTranslog + "]");
Files.move(tempEmptyTranslog, realEmptyTranslog, StandardCopyOption.ATOMIC_MOVE);
// Fsync the translog directory after rename
IOUtils.fsync(translogPath, true);
}
private boolean isTranslogClean(ShardPath shardPath, ClusterState clusterState, String translogUUID) throws IOException {
// perform clean check of translog instead of corrupted marker file
try {
final Path translogPath = shardPath.resolveTranslog();
final long translogGlobalCheckpoint = Translog.readGlobalCheckpoint(translogPath, translogUUID);
final IndexMetadata indexMetadata = clusterState.metadata().getIndexSafe(shardPath.getShardId().getIndex());
final IndexSettings indexSettings = new IndexSettings(indexMetadata, Settings.EMPTY);
final TranslogConfig translogConfig = new TranslogConfig(shardPath.getShardId(), translogPath,
indexSettings, BigArrays.NON_RECYCLING_INSTANCE);
long primaryTerm = indexSettings.getIndexMetadata().primaryTerm(shardPath.getShardId().id());
final TranslogDeletionPolicy translogDeletionPolicy = new TranslogDeletionPolicy();
try (Translog translog = new Translog(translogConfig, translogUUID,
translogDeletionPolicy, () -> translogGlobalCheckpoint, () -> primaryTerm, seqNo -> {});
Translog.Snapshot snapshot = translog.newSnapshot(0, Long.MAX_VALUE)) {
//noinspection StatementWithEmptyBody we are just checking that we can iterate through the whole snapshot
while (snapshot.next() != null) {
}
}
return true;
} catch (TranslogCorruptedException e) {
return false;
}
}
/** Write a checkpoint file to the given location with the given generation */
private static void writeEmptyCheckpoint(Path filename, int translogLength, long translogGeneration, long globalCheckpoint)
throws IOException {
Checkpoint emptyCheckpoint = Checkpoint.emptyTranslogCheckpoint(translogLength, translogGeneration,
globalCheckpoint, translogGeneration);
Checkpoint.write(FileChannel::open, filename, emptyCheckpoint,
StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE_NEW);
}
/**
* Write a translog containing the given translog UUID to the given location. Returns the number of bytes written.
*/
private static int writeEmptyTranslog(Path filename, String translogUUID) throws IOException {
try (FileChannel fc = FileChannel.open(filename, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) {
TranslogHeader header = new TranslogHeader(translogUUID, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
header.write(fc);
return header.sizeInBytes();
}
}
/** Show a warning about deleting files, asking for a confirmation if {@code batchMode} is false */
private String deletingFilesDetails(Path translogPath, Set<Path> files) {
StringBuilder builder = new StringBuilder();
builder
.append("Documents inside of translog files will be lost.\n")
.append(" The following files will be DELETED at ")
.append(translogPath)
.append("\n\n");
for(Iterator<Path> it = files.iterator();it.hasNext();) {
builder.append(" --> ").append(it.next().getFileName());
if (it.hasNext()) {
builder.append("\n");
}
}
return builder.toString();
}
/** Return a Set of all files in a given directory */
private static Set<Path> filesInDirectory(Path directory) throws IOException {
Set<Path> files = new TreeSet<>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path file : stream) {
files.add(file);
}
}
return files;
}
}
| apache-2.0 |
guozhangwang/kafka | streams/src/main/java/org/apache/kafka/streams/kstream/internals/graph/BaseJoinProcessorNode.java | 3617 | /*
* 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.kafka.streams.kstream.internals.graph;
import org.apache.kafka.streams.kstream.ValueJoinerWithKey;
/**
* Utility base class containing the common fields between
* a Stream-Stream join and a Table-Table join
*/
abstract class BaseJoinProcessorNode<K, V1, V2, VR> extends GraphNode {
private final ProcessorParameters<K, V1, ?, ?> joinThisProcessorParameters;
private final ProcessorParameters<K, V2, ?, ?> joinOtherProcessorParameters;
private final ProcessorParameters<K, VR, ?, ?> joinMergeProcessorParameters;
private final ValueJoinerWithKey<? super K, ? super V1, ? super V2, ? extends VR> valueJoiner;
private final String thisJoinSideNodeName;
private final String otherJoinSideNodeName;
BaseJoinProcessorNode(final String nodeName,
final ValueJoinerWithKey<? super K, ? super V1, ? super V2, ? extends VR> valueJoiner,
final ProcessorParameters<K, V1, ?, ?> joinThisProcessorParameters,
final ProcessorParameters<K, V2, ?, ?> joinOtherProcessorParameters,
final ProcessorParameters<K, VR, ?, ?> joinMergeProcessorParameters,
final String thisJoinSideNodeName,
final String otherJoinSideNodeName) {
super(nodeName);
this.valueJoiner = valueJoiner;
this.joinThisProcessorParameters = joinThisProcessorParameters;
this.joinOtherProcessorParameters = joinOtherProcessorParameters;
this.joinMergeProcessorParameters = joinMergeProcessorParameters;
this.thisJoinSideNodeName = thisJoinSideNodeName;
this.otherJoinSideNodeName = otherJoinSideNodeName;
}
ProcessorParameters<K, V1, ?, ?> thisProcessorParameters() {
return joinThisProcessorParameters;
}
ProcessorParameters<K, V2, ?, ?> otherProcessorParameters() {
return joinOtherProcessorParameters;
}
ProcessorParameters<K, VR, ?, ?> mergeProcessorParameters() {
return joinMergeProcessorParameters;
}
String thisJoinSideNodeName() {
return thisJoinSideNodeName;
}
String otherJoinSideNodeName() {
return otherJoinSideNodeName;
}
@Override
public String toString() {
return "BaseJoinProcessorNode{" +
"joinThisProcessorParameters=" + joinThisProcessorParameters +
", joinOtherProcessorParameters=" + joinOtherProcessorParameters +
", joinMergeProcessorParameters=" + joinMergeProcessorParameters +
", valueJoiner=" + valueJoiner +
", thisJoinSideNodeName='" + thisJoinSideNodeName + '\'' +
", otherJoinSideNodeName='" + otherJoinSideNodeName + '\'' +
"} " + super.toString();
}
}
| apache-2.0 |
briandealwis/getting-started-java | bookshelf/2-structured-data/src/main/java/com/example/getstarted/daos/CloudSqlDao.java | 6867 | /* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.getstarted.daos;
import com.example.getstarted.objects.Book;
import com.example.getstarted.objects.Result;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
// [START example]
public class CloudSqlDao implements BookDao {
// [START constructor]
private static final BasicDataSource dataSource = new BasicDataSource();
/**
* A data access object for Bookshelf using a Google Cloud SQL server for storage.
*/
public CloudSqlDao(final String url) throws SQLException {
dataSource.setUrl(url);
final String createTableSql = "CREATE TABLE IF NOT EXISTS books2 ( id INT NOT NULL "
+ "AUTO_INCREMENT, author VARCHAR(255), createdBy VARCHAR(255), createdById VARCHAR(255), "
+ "description VARCHAR(255), publishedDate VARCHAR(255), title VARCHAR(255), imageUrl "
+ "VARCHAR(255), PRIMARY KEY (id))";
try (Connection conn = dataSource.getConnection()) {
conn.createStatement().executeUpdate(createTableSql);
}
}
// [END constructor]
// [START create]
@Override
public Long createBook(Book book) throws SQLException {
final String createBookString = "INSERT INTO books2 "
+ "(author, createdBy, createdById, description, publishedDate, title, imageUrl) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (Connection conn = dataSource.getConnection();
final PreparedStatement createBookStmt = conn.prepareStatement(createBookString,
Statement.RETURN_GENERATED_KEYS)) {
createBookStmt.setString(1, book.getAuthor());
createBookStmt.setString(2, book.getCreatedBy());
createBookStmt.setString(3, book.getCreatedById());
createBookStmt.setString(4, book.getDescription());
createBookStmt.setString(5, book.getPublishedDate());
createBookStmt.setString(6, book.getTitle());
createBookStmt.setString(7, book.getImageUrl());
createBookStmt.executeUpdate();
try (ResultSet keys = createBookStmt.getGeneratedKeys()) {
keys.next();
return keys.getLong(1);
}
}
}
// [END create]
// [START read]
@Override
public Book readBook(Long bookId) throws SQLException {
final String readBookString = "SELECT * FROM books2 WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement readBookStmt = conn.prepareStatement(readBookString)) {
readBookStmt.setLong(1, bookId);
try (ResultSet keys = readBookStmt.executeQuery()) {
keys.next();
return new Book.Builder()
.author(keys.getString(Book.AUTHOR))
.createdBy(keys.getString(Book.CREATED_BY))
.createdById(keys.getString(Book.CREATED_BY_ID))
.description(keys.getString(Book.DESCRIPTION))
.id(keys.getLong(Book.ID))
.publishedDate(keys.getString(Book.PUBLISHED_DATE))
.title(keys.getString(Book.TITLE))
.imageUrl(keys.getString(Book.IMAGE_URL))
.build();
}
}
}
// [END read]
// [START update]
@Override
public void updateBook(Book book) throws SQLException {
final String updateBookString = "UPDATE books2 SET author = ?, createdBy = ?, createdById = ?, "
+ "description = ?, publishedDate = ?, title = ?, imageUrl = ? WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement updateBookStmt = conn.prepareStatement(updateBookString)) {
updateBookStmt.setString(1, book.getAuthor());
updateBookStmt.setString(2, book.getCreatedBy());
updateBookStmt.setString(3, book.getCreatedById());
updateBookStmt.setString(4, book.getDescription());
updateBookStmt.setString(5, book.getPublishedDate());
updateBookStmt.setString(6, book.getTitle());
updateBookStmt.setString(7, book.getImageUrl());
updateBookStmt.setLong(8, book.getId());
updateBookStmt.executeUpdate();
}
}
// [END update]
// [START delete]
@Override
public void deleteBook(Long bookId) throws SQLException {
final String deleteBookString = "DELETE FROM books2 WHERE id = ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement deleteBookStmt = conn.prepareStatement(deleteBookString)) {
deleteBookStmt.setLong(1, bookId);
deleteBookStmt.executeUpdate();
}
}
// [END delete]
// [START listbooks]
@Override
public Result<Book> listBooks(String cursor) throws SQLException {
int offset = 0;
if (cursor != null && !cursor.equals("")) {
offset = Integer.parseInt(cursor);
}
final String listBooksString = "SELECT SQL_CALC_FOUND_ROWS author, createdBy, createdById, "
+ "description, id, publishedDate, title, imageUrl FROM books2 ORDER BY title ASC "
+ "LIMIT 10 OFFSET ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement listBooksStmt = conn.prepareStatement(listBooksString)) {
listBooksStmt.setInt(1, offset);
List<Book> resultBooks = new ArrayList<>();
try (ResultSet rs = listBooksStmt.executeQuery()) {
while (rs.next()) {
Book book = new Book.Builder()
.author(rs.getString(Book.AUTHOR))
.createdBy(rs.getString(Book.CREATED_BY))
.createdById(rs.getString(Book.CREATED_BY_ID))
.description(rs.getString(Book.DESCRIPTION))
.id(rs.getLong(Book.ID))
.publishedDate(rs.getString(Book.PUBLISHED_DATE))
.title(rs.getString(Book.TITLE))
.imageUrl(rs.getString(Book.IMAGE_URL))
.build();
resultBooks.add(book);
}
}
try (ResultSet rs = conn.createStatement().executeQuery("SELECT FOUND_ROWS()")) {
int totalNumRows = 0;
if (rs.next()) {
totalNumRows = rs.getInt(1);
}
if (totalNumRows > offset + 10) {
return new Result<>(resultBooks, Integer.toString(offset + 10));
} else {
return new Result<>(resultBooks);
}
}
}
}
// [END listbooks]
}
// [END example]
| apache-2.0 |
antlr/codebuff | output/java_guava/1.4.19/DirectedNodeConnections.java | 2105 | /*
* Copyright (C) 2016 The Guava 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 com.google.common.graph;
import static com.google.common.graph.GraphConstants.EXPECTED_DEGREE;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
/**
* An implementation of {@link NodeConnections} for directed networks.
*
* @author James Sexton
* @param <N> Node parameter type
* @param <E> Edge parameter type
*/
final class DirectedNodeConnections<N, E> extends AbstractDirectedNodeConnections<N, E> {
protected DirectedNodeConnections(Map<E, N> inEdgeMap, Map<E, N> outEdgeMap) {
super(inEdgeMap, outEdgeMap);
}
static <N, E> DirectedNodeConnections<N, E> of() {
return new DirectedNodeConnections<N, E>(HashBiMap.<E, N>create(EXPECTED_DEGREE), HashBiMap.<E, N>create(EXPECTED_DEGREE));
}
static <N, E> DirectedNodeConnections<N, E> ofImmutable(Map<E, N> inEdges, Map<E, N> outEdges) {
return new DirectedNodeConnections<N, E>(ImmutableBiMap.copyOf(inEdges), ImmutableBiMap.copyOf(outEdges));
}
@Override
public Set<N> predecessors() {
return Collections.unmodifiableSet(((BiMap<E, N>) inEdgeMap).values());
}
@Override
public Set<N> successors() {
return Collections.unmodifiableSet(((BiMap<E, N>) outEdgeMap).values());
}
@Override
public Set<E> edgesConnecting(Object node) {
return new SimpleEdgesConnecting<E>(((BiMap<E, N>) outEdgeMap).inverse(), node);
}
} | bsd-2-clause |
zloster/FrameworkBenchmarks | frameworks/Java/quarkus/src/main/java/io/quarkus/benchmark/repository/FortuneRepository.java | 598 | package io.quarkus.benchmark.repository;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.transaction.Transactional;
import io.quarkus.benchmark.model.Fortune;
import io.quarkus.benchmark.model.World;
@ApplicationScoped
public class FortuneRepository {
@Inject
EntityManager em;
@Transactional
public List<Fortune> findAll() {
Query query = em.createQuery("SELECT f FROM Fortune f");
return query.getResultList();
}
}
| bsd-3-clause |
bhav0904/eclipse-collections | eclipse-collections/src/main/java/org/eclipse/collections/impl/parallel/ObjectIntProcedureFactory.java | 810 | /*
* Copyright (c) 2015 Goldman Sachs.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v. 1.0 which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
package org.eclipse.collections.impl.parallel;
import org.eclipse.collections.api.block.procedure.primitive.ObjectIntProcedure;
/**
* ObjectIntProcedureFactory is used by parallel iterators as a factory for stateful ObjectIntProcedure instances.
*/
public interface ObjectIntProcedureFactory<T extends ObjectIntProcedure<?>>
{
T create();
}
| bsd-3-clause |
mtCarto/geogig | src/geotools/src/main/java/org/locationtech/geogig/geotools/cli/oracle/OracleImport.java | 1444 | /* Copyright (c) 2013-2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Juan Marin (Boundless) - initial implementation
*/
package org.locationtech.geogig.geotools.cli.oracle;
import org.geotools.data.DataStore;
import org.locationtech.geogig.cli.CLICommand;
import org.locationtech.geogig.geotools.cli.DataStoreImport;
import org.locationtech.geogig.geotools.plumbing.ImportOp;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;
/**
* Imports one or more tables from an Oracle database.
*
* Oracle CLI proxy for {@link ImportOp}
*
* @see ImportOp
*/
@Parameters(commandNames = "import", commandDescription = "Import Oracle database")
public class OracleImport extends DataStoreImport implements CLICommand {
/**
* Common arguments for Oracle commands.
*/
@ParametersDelegate
public OracleCommonArgs commonArgs = new OracleCommonArgs();
final OracleSupport support = new OracleSupport();
@Override
protected DataStore getDataStore() {
return support.getDataStore(commonArgs);
}
@Override
protected String getSourceDatabaseName() {
return commonArgs.database;
}
}
| bsd-3-clause |
steffeli/inf5750-tracker-capture | dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/help/HelpContent.java | 2201 | package org.hisp.dhis.system.help;
/*
* Copyright (c) 2004-2015, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @author Murodillo Latifov Abdusamadovich
* @version $Id: PopupHelpAction.java 08-04-2009 $
*/
public class HelpContent
{
private String header;
private String content;
public HelpContent()
{
}
public String getHeader()
{
return header;
}
public void setHeader( String header )
{
this.header = header;
}
public String getContent()
{
return content;
}
public void setContent( String content )
{
this.content = content;
}
}
| bsd-3-clause |
recena/warnings-plugin | src/test/java/hudson/plugins/warnings/parser/GnuFortranParserTest.java | 5271 | package hudson.plugins.warnings.parser;
import static org.junit.Assert.*;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.analysis.util.model.Priority;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import org.junit.Test;
/**
* Tests the class {@link GnuFortranParser}.
*/
public class GnuFortranParserTest extends ParserTester {
private static final String TYPE = new GnuFortranParser().getGroup();
/**
* Test parsing of a file containing a Warning message
* output by the GNU Fortran Compiler.
*
* @throws IOException if the file could not be read.
*/
@Test
public void testWarningParser() throws IOException {
Collection<FileAnnotation> warnings =
new GnuFortranParser().parse(openFile("GnuFortranWarning.txt"));
assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 1, warnings.size());
Iterator<FileAnnotation> iterator = warnings.iterator();
checkWarning(iterator.next(),
318,
"Inequality comparison for REAL(8)",
"C:/zlaror.f",
TYPE,
"Warning",
Priority.NORMAL);
}
/**
* Test parsing of a file containing an Error message
* output by the GNU Fortran Compiler.
*
* @throws IOException if the file could not be read.
*/
@Test
public void testErrorParser() throws IOException {
Collection<FileAnnotation> warnings =
new GnuFortranParser().parse(openFile("GnuFortranError.txt"));
assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 1, warnings.size());
Iterator<FileAnnotation> iterator = warnings.iterator();
checkWarning(iterator.next(),
81, 24,
"Interface mismatch in dummy procedure 'f': Shape mismatch in dimension 1 of argument 'y'",
"generic2.f90",
TYPE,
"Error",
Priority.HIGH);
}
/**
* Test parsing of a file containing a Fatal Error message
* output by the GNU Fortran Compiler.
*
* @throws IOException if the file could not be read.
*/
@Test
public void testFatalErrorParser() throws IOException {
Collection<FileAnnotation> warnings =
new GnuFortranParser().parse(openFile("GnuFortranFatalError.txt"));
assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 1, warnings.size());
Iterator<FileAnnotation> iterator = warnings.iterator();
checkWarning(iterator.next(),
7, 10,
"Can't open module file 'ieee_arithmetic.mod' for reading: No such file or directory",
"/path/to/file.f90",
TYPE,
"Fatal Error",
Priority.HIGH);
}
/**
* Test parsing of a file containing an Internal Error message
* output by the GNU Fortran Compiler.
*
* @throws IOException if the file could not be read.
*/
@Test
public void testInternalErrorParser() throws IOException {
Collection<FileAnnotation> warnings =
new GnuFortranParser().parse(openFile("GnuFortranInternalError.txt"));
assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 1, warnings.size());
Iterator<FileAnnotation> iterator = warnings.iterator();
checkWarning(iterator.next(),
5, 8,
"free_pi_tree(): Unresolved fixup",
"linear_algebra_mod.f90",
TYPE,
"Internal Error",
Priority.HIGH);
}
/**
* Test parsing of a file containing all categories of message
* output by the GNU Fortran Compiler.
*
* @throws IOException if the file could not be read.
*/
@Test
public void testMessageParser() throws IOException {
Collection<FileAnnotation> warnings =
new GnuFortranParser().parse(openFile());
assertEquals(WRONG_NUMBER_OF_WARNINGS_DETECTED, 4, warnings.size());
Iterator<FileAnnotation> iterator = warnings.iterator();
checkWarning(iterator.next(),
318,
"Inequality comparison for REAL(8)",
"C:/zlaror.f",
TYPE,
"Warning",
Priority.NORMAL);
checkWarning(iterator.next(),
7, 10,
"Can't open module file 'ieee_arithmetic.mod' for reading: No such file or directory",
"/path/to/file.f90",
TYPE,
"Fatal Error",
Priority.HIGH);
checkWarning(iterator.next(),
81, 24,
"Interface mismatch in dummy procedure 'f': Shape mismatch in dimension 1 of argument 'y'",
"generic2.f90",
TYPE,
"Error",
Priority.HIGH);
checkWarning(iterator.next(),
5, 8,
"free_pi_tree(): Unresolved fixup",
"linear_algebra_mod.f90",
TYPE,
"Internal Error",
Priority.HIGH);
}
@Override
protected String getWarningsFile() {
return "GnuFortran.txt";
}
}
| mit |
brunyuriy/quick-fix-scout | org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/ui/text/CombinedWordRule.java | 10463 | /*******************************************************************************
* Copyright (c) 2000, 2011 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 org.eclipse.jdt.internal.ui.text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.Token;
/**
* An implementation of <code>IRule</code> capable of detecting words.
* <p>
* Word rules also allow for the association of tokens with specific words.
* That is, not only can the rule be used to provide tokens for exact matches,
* but also for the generalized notion of a word in the context in which it is used.
* A word rules uses a word detector to determine what a word is.</p>
* <p>
* This word rule allows a word detector to be shared among different word matchers.
* Its up to the word matchers to decide if a word matches and, in this a case, which
* token is associated with that word.
* </p>
*
* @see IWordDetector
* @since 3.0
*/
public class CombinedWordRule implements IRule {
/**
* Word matcher, that associates matched words with tokens.
*/
public static class WordMatcher {
/** The table of predefined words and token for this matcher */
private Map<CharacterBuffer, IToken> fWords= new HashMap<CharacterBuffer, IToken>();
/**
* Adds a word and the token to be returned if it is detected.
*
* @param word the word this rule will search for, may not be <code>null</code>
* @param token the token to be returned if the word has been found, may not be <code>null</code>
*/
public void addWord(String word, IToken token) {
Assert.isNotNull(word);
Assert.isNotNull(token);
fWords.put(new CharacterBuffer(word), token);
}
/**
* Returns the token associated to the given word and the scanner state.
*
* @param scanner the scanner
* @param word the word
* @return the token or <code>null</code> if none is associated by this matcher
*/
public IToken evaluate(ICharacterScanner scanner, CharacterBuffer word) {
IToken token= fWords.get(word);
if (token != null)
return token;
return Token.UNDEFINED;
}
/**
* Removes all words.
*/
public void clearWords() {
fWords.clear();
}
}
/**
* Character buffer, mutable <b>or</b> suitable for use as key in hash maps.
*/
public static class CharacterBuffer {
/** Buffer content */
private char[] fContent;
/** Buffer content size */
private int fLength= 0;
/** Is hash code cached? */
private boolean fIsHashCached= false;
/** The hash code */
private int fHashCode;
/**
* Initialize with the given capacity.
*
* @param capacity the initial capacity
*/
public CharacterBuffer(int capacity) {
fContent= new char[capacity];
}
/**
* Initialize with the given content.
*
* @param content the initial content
*/
public CharacterBuffer(String content) {
fContent= content.toCharArray();
fLength= content.length();
}
/**
* Empties this buffer.
*/
public void clear() {
fIsHashCached= false;
fLength= 0;
}
/**
* Appends the given character to the buffer.
*
* @param c the character
*/
public void append(char c) {
fIsHashCached= false;
if (fLength == fContent.length) {
char[] old= fContent;
fContent= new char[old.length << 1];
System.arraycopy(old, 0, fContent, 0, old.length);
}
fContent[fLength++]= c;
}
/**
* Returns the length of the content.
*
* @return the length
*/
public int length() {
return fLength;
}
/**
* Returns the content as string.
*
* @return the content
*/
@Override
public String toString() {
return new String(fContent, 0, fLength);
}
/**
* Returns the character at the given position.
*
* @param i the position
* @return the character at position <code>i</code>
*/
public char charAt(int i) {
return fContent[i];
}
/*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
if (fIsHashCached)
return fHashCode;
int hash= 0;
for (int i= 0, n= fLength; i < n; i++)
hash= 29*hash + fContent[i];
fHashCode= hash;
fIsHashCached= true;
return hash;
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof CharacterBuffer))
return false;
CharacterBuffer buffer= (CharacterBuffer) obj;
int length= buffer.length();
if (length != fLength)
return false;
for (int i= 0; i < length; i++)
if (buffer.charAt(i) != fContent[i])
return false;
return true;
}
/**
* Is the content equal to the given string?
*
* @param string the string
* @return <code>true</code> iff the content is the same character sequence as in the string
*/
public boolean equals(String string) {
int length= string.length();
if (length != fLength)
return false;
for (int i= 0; i < length; i++)
if (string.charAt(i) != fContent[i])
return false;
return true;
}
}
/** Internal setting for the uninitialized column constraint */
private static final int UNDEFINED= -1;
/** The word detector used by this rule */
private IWordDetector fDetector;
/** The default token to be returned on success and if nothing else has been specified. */
private IToken fDefaultToken;
/** The column constraint */
private int fColumn= UNDEFINED;
/** Buffer used for pattern detection */
private CharacterBuffer fBuffer= new CharacterBuffer(16);
/** List of word matchers */
private List<WordMatcher> fMatchers= new ArrayList<WordMatcher>();
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the scanner
* will be rolled back and an undefined token will be returned in order to allow
* any subsequent rules to analyze the characters.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
*
* @see WordMatcher#addWord(String, IToken)
*/
public CombinedWordRule(IWordDetector detector) {
this(detector, null, Token.UNDEFINED);
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
*
* @see WordMatcher#addWord(String, IToken)
*/
public CombinedWordRule(IWordDetector detector, IToken defaultToken) {
this(detector, null, defaultToken);
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the scanner
* will be rolled back and an undefined token will be returned in order to allow
* any subsequent rules to analyze the characters.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param matcher the initial word matcher
*
* @see WordMatcher#addWord(String, IToken)
*/
public CombinedWordRule(IWordDetector detector, WordMatcher matcher) {
this(detector, matcher, Token.UNDEFINED);
}
/**
* Creates a rule which, with the help of an word detector, will return the token
* associated with the detected word. If no token has been associated, the
* specified default token will be returned.
*
* @param detector the word detector to be used by this rule, may not be <code>null</code>
* @param matcher the initial word matcher
* @param defaultToken the default token to be returned on success
* if nothing else is specified, may not be <code>null</code>
*
* @see WordMatcher#addWord(String, IToken)
*/
public CombinedWordRule(IWordDetector detector, WordMatcher matcher, IToken defaultToken) {
Assert.isNotNull(detector);
Assert.isNotNull(defaultToken);
fDetector= detector;
fDefaultToken= defaultToken;
if (matcher != null)
addWordMatcher(matcher);
}
/**
* Adds the given matcher.
*
* @param matcher the matcher
*/
public void addWordMatcher(WordMatcher matcher) {
fMatchers.add(matcher);
}
/**
* Sets a column constraint for this rule. If set, the rule's token
* will only be returned if the pattern is detected starting at the
* specified column. If the column is smaller then 0, the column
* constraint is considered removed.
*
* @param column the column in which the pattern starts
*/
public void setColumnConstraint(int column) {
if (column < 0)
column= UNDEFINED;
fColumn= column;
}
/*
* @see IRule#evaluate(ICharacterScanner)
*/
public IToken evaluate(ICharacterScanner scanner) {
int c= scanner.read();
if (fDetector.isWordStart((char) c)) {
if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {
fBuffer.clear();
do {
fBuffer.append((char) c);
c= scanner.read();
} while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c));
scanner.unread();
for (int i= 0, n= fMatchers.size(); i < n; i++) {
IToken token= fMatchers.get(i).evaluate(scanner, fBuffer);
if (!token.isUndefined())
return token;
}
if (fDefaultToken.isUndefined())
unreadBuffer(scanner);
return fDefaultToken;
}
}
scanner.unread();
return Token.UNDEFINED;
}
/**
* Returns the characters in the buffer to the scanner.
*
* @param scanner the scanner to be used
*/
private void unreadBuffer(ICharacterScanner scanner) {
for (int i= fBuffer.length() - 1; i >= 0; i--)
scanner.unread();
}
}
| mit |
brunyuriy/quick-fix-scout | org.eclipse.jdt.ui_3.7.1.r371_v20110824-0800/src/org/eclipse/jdt/internal/corext/refactoring/scripting/CopyRefactoringContribution.java | 2253 | /*******************************************************************************
* Copyright (c) 2006, 2011 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 org.eclipse.jdt.internal.corext.refactoring.scripting;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.participants.CopyRefactoring;
import org.eclipse.jdt.core.refactoring.descriptors.JavaRefactoringDescriptor;
import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory;
import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments;
import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaCopyProcessor;
/**
* Refactoring contribution for the copy refactoring.
*
* @since 3.2
*/
public final class CopyRefactoringContribution extends JavaUIRefactoringContribution {
/**
* {@inheritDoc}
*/
@Override
public final Refactoring createRefactoring(final JavaRefactoringDescriptor descriptor, RefactoringStatus status) throws CoreException {
JavaRefactoringArguments arguments= new JavaRefactoringArguments(descriptor.getProject(), retrieveArgumentMap(descriptor));
JavaCopyProcessor processor= new JavaCopyProcessor(arguments, status);
return new CopyRefactoring(processor);
}
@Override
public RefactoringDescriptor createDescriptor() {
return RefactoringSignatureDescriptorFactory.createCopyDescriptor();
}
@Override
public RefactoringDescriptor createDescriptor(String id, String project, String description, String comment, Map arguments, int flags) {
return RefactoringSignatureDescriptorFactory.createCopyDescriptor(project, description, comment, arguments, flags);
}
}
| mit |
idserda/openhab | bundles/binding/org.openhab.binding.digitalstrom/src/main/java/org/openhab/binding/digitalstrom/internal/client/entity/Apartment.java | 539 | /**
* Copyright (c) 2010-2019 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.digitalstrom.internal.client.entity;
import java.util.Map;
/**
* @author Alexander Betker
* @since 1.3.0
*/
public interface Apartment {
public Map<Integer, Zone> getZoneMap();
}
| epl-1.0 |
computergeek1507/openhab | bundles/action/org.openhab.action.dscalarm/src/main/java/org/openhab/action/dscalarm/internal/DSCAlarmAction.java | 2829 | /**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.action.dscalarm.internal;
import org.openhab.binding.dscalarm1.DSCAlarmActionProvider;
import org.openhab.core.scriptengine.action.ActionDoc;
import org.openhab.core.scriptengine.action.ParamDoc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides static methods, for the DSC Alarm, that can be used in automation rules.
*
* @author Russell Stephens
* @since 1.8.0
*/
public class DSCAlarmAction {
private static Logger logger = LoggerFactory.getLogger(DSCAlarmAction.class);
/**
* Sends a string that is equivalent to a key sequence on an existing keypad.
*/
@ActionDoc(text = "Sends a DSC Alarm command that required no extra data.")
public static boolean sendDSCAlarmCommand(
@ParamDoc(name = "command", text = "The command to be sent to the DSC Alarm.") String command) {
return sendDSCAlarmCommandInternal(command, "");
}
@ActionDoc(text = "Sends a DSC Alarm command along with required data.")
public static boolean sendDSCAlarmCommand(
@ParamDoc(name = "command", text = "The command to be sent to the DSC Alarm.") String command,
@ParamDoc(name = "data", text = "The data string for the command.") String data) {
return sendDSCAlarmCommandInternal(command, data);
}
private static DSCAlarmActionProvider getDSCAlarmActionProvider() throws Exception {
DSCAlarmActionService actionService = DSCAlarmActionService.getDSCAlarmActionService();
if (actionService == null) {
throw new Exception(String.format("DSC Alarm Action Service is not configured!"));
}
DSCAlarmActionProvider actionProvider = actionService.getDSCAlarmActionProvider();
if (actionProvider == null) {
throw new Exception(String.format("DSC Alarm Action Service is not configured!"));
}
return actionProvider;
}
private static boolean sendDSCAlarmCommandInternal(String command, String data) {
try {
logger.debug("sendDSCAlarmCommandInternal(): Sending DSC Alarm command!");
DSCAlarmActionProvider actionProvider = getDSCAlarmActionProvider();
return actionProvider.sendDSCAlarmCommand(command, data);
} catch (Exception e) {
logger.error("sendDSCAlarmCommandInternal(): Error Sending DSC Alarm Command: {}", e);
}
return false;
}
}
| epl-1.0 |
AdmireTheDistance/android_libcore | luni/src/main/java/android/system/StructGroupSourceReq.java | 1223 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.system;
import java.net.InetAddress;
import libcore.util.Objects;
/**
* Corresponds to C's {@code struct group_source_req}.
*
* @hide
*/
public final class StructGroupSourceReq {
public final int gsr_interface;
public final InetAddress gsr_group;
public final InetAddress gsr_source;
public StructGroupSourceReq(int gsr_interface, InetAddress gsr_group, InetAddress gsr_source) {
this.gsr_interface = gsr_interface;
this.gsr_group = gsr_group;
this.gsr_source = gsr_source;
}
@Override public String toString() {
return Objects.toString(this);
}
}
| gpl-2.0 |
ndcriswe/a-mp-droid | src/com/mediaportal/ampdroid/quickactions/CustomPopupWindow.java | 6372 | /*******************************************************************************
* Copyright (c) 2011 Benjamin Gmeiner.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Benjamin Gmeiner - Project Owner
******************************************************************************/
package com.mediaportal.ampdroid.quickactions;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;
import com.mediaportal.ampdroid.R;
/**
* This class does most of the work of wrapping the {@link PopupWindow} so it's simpler to use.
* Edited by Lorensius. W. L. T
*
* @author qberticus
*
*/
public class CustomPopupWindow {
protected final View mAnchor;
protected final PopupWindow mWindow;
private View mRoot;
private Drawable mBackground = null;
protected final WindowManager mWindowManager;
/**
* Create a QuickAction
*
* @param _anchor
* the view that the QuickAction will be displaying 'from'
*/
public CustomPopupWindow(View _anchor) {
this.mAnchor = _anchor;
this.mWindow = new PopupWindow(_anchor.getContext());
// when a touch even happens outside of the window
// make the window go away
mWindow.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
CustomPopupWindow.this.mWindow.dismiss();
return true;
}
return false;
}
});
mWindowManager = (WindowManager) _anchor.getContext().getSystemService(Context.WINDOW_SERVICE);
onCreate();
}
/**
* Anything you want to have happen when created. Probably should create a view and setup the event listeners on
* child views.
*/
protected void onCreate() {}
/**
* In case there is stuff to do right before displaying.
*/
protected void onShow() {}
protected void preShow() {
if (mRoot == null) {
throw new IllegalStateException("setContentView was not called with a view to display.");
}
onShow();
if (mBackground == null) {
mWindow.setBackgroundDrawable(new BitmapDrawable());
} else {
mWindow.setBackgroundDrawable(mBackground);
}
// if using PopupWindow#setBackgroundDrawable this is the only values of the width and hight that make it work
// otherwise you need to set the background of the root viewgroup
// and set the popupwindow background to an empty BitmapDrawable
mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setTouchable(true);
mWindow.setFocusable(true);
mWindow.setOutsideTouchable(true);
mWindow.setContentView(mRoot);
}
public void setBackgroundDrawable(Drawable _background) {
this.mBackground = _background;
}
/**
* Sets the content view. Probably should be called from {@link onCreate}
*
* @param _root
* the view the popup will display
*/
public void setContentView(View _root) {
this.mRoot = _root;
mWindow.setContentView(_root);
}
/**
* Will inflate and set the view from a resource id
*
* @param _layoutResID
*/
public void setContentView(int _layoutResID) {
LayoutInflater inflator =
(LayoutInflater) mAnchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setContentView(inflator.inflate(_layoutResID, null));
}
/**
* If you want to do anything when {@link dismiss} is called
*
* @param _listener
*/
public void setOnDismissListener(PopupWindow.OnDismissListener _listener) {
mWindow.setOnDismissListener(_listener);
}
/**
* Displays like a popdown menu from the anchor view
*/
public void showDropDown() {
showDropDown(0, 0);
}
/**
* Displays like a popdown menu from the anchor view.
*
* @param _xOffset
* offset in X direction
* @param _yOffset
* offset in Y direction
*/
public void showDropDown(int _xOffset, int _yOffset) {
preShow();
mWindow.setAnimationStyle(R.style.Animations_PopDownMenu_Left);
mWindow.showAsDropDown(mAnchor, _xOffset, _yOffset);
}
/**
* Displays like a QuickAction from the anchor view.
*/
public void showLikeQuickAction() {
showLikeQuickAction(0, 0);
}
/**
* Displays like a QuickAction from the anchor view.
*
* @param _xOffset
* offset in the X direction
* @param _yOffset
* offset in the Y direction
*/
public void showLikeQuickAction(int _xOffset, int _yOffset) {
preShow();
mWindow.setAnimationStyle(R.style.Animations_PopUpMenu_Center);
int[] location = new int[2];
mAnchor.getLocationOnScreen(location);
Rect anchorRect =
new Rect(location[0], location[1], location[0] + mAnchor.getWidth(), location[1]
+ mAnchor.getHeight());
mRoot.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mRoot.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int rootWidth = mRoot.getMeasuredWidth();
int rootHeight = mRoot.getMeasuredHeight();
int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
//int screenHeight = windowManager.getDefaultDisplay().getHeight();
int xPos = ((screenWidth - rootWidth) / 2) + _xOffset;
int yPos = anchorRect.top - rootHeight + _yOffset;
// display on bottom
if (rootHeight > anchorRect.top) {
yPos = anchorRect.bottom + _yOffset;
mWindow.setAnimationStyle(R.style.Animations_PopDownMenu_Center);
}
mWindow.showAtLocation(mAnchor, Gravity.NO_GRAVITY, xPos, yPos);
}
public void dismiss() {
mWindow.dismiss();
}
}
| gpl-2.0 |
md-5/jdk10 | make/jdk/src/classes/build/tools/blacklistedcertsconverter/BlacklistedCertsConverter.java | 4117 | /*
* Copyright (c) 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.
*/
package build.tools.blacklistedcertsconverter;
import java.security.MessageDigest;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
/**
* Converts blacklisted.certs.pem from System.in to blacklisted.certs in
* System.out. The input must start with a #! line including the fingerprint
* algorithm. The output is sorted and unique.
*/
public class BlacklistedCertsConverter {
public static void main(String[] args) throws Exception {
byte[] pattern = "#! java BlacklistedCertsConverter ".getBytes();
String mdAlg = "";
for (int i=0; ; i++) {
int n = System.in.read();
if (n < 0) {
throw new Exception("Unexpected EOF");
}
if (i < pattern.length) {
if (n != pattern[i]) {
throw new Exception("The first line must start with \""
+ new String(pattern) + "\"");
}
} else if (i < pattern.length + 100) {
if (n < 32) {
break;
} else {
mdAlg = mdAlg + String.format("%c", n);
}
}
}
mdAlg = mdAlg.trim();
System.out.println("Algorithm=" + mdAlg);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certs
= cf.generateCertificates(System.in);
// Output sorted so that it's easy to locate an entry.
Set<String> fingerprints = new TreeSet<>();
for (Certificate cert: certs) {
fingerprints.add(
getCertificateFingerPrint(mdAlg, (X509Certificate)cert));
}
for (String s: fingerprints) {
System.out.println(s);
}
}
/**
* Converts a byte to hex digit and writes to the supplied buffer
*/
private static void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F' };
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
/**
* Gets the requested finger print of the certificate.
*/
private static String getCertificateFingerPrint(
String mdAlg, X509Certificate cert) throws Exception {
byte[] encCertInfo = cert.getEncoded();
MessageDigest md = MessageDigest.getInstance(mdAlg);
byte[] digest = md.digest(encCertInfo);
StringBuffer buf = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
byte2hex(digest[i], buf);
}
return buf.toString();
}
}
| gpl-2.0 |
saimoom/phyml | gui/src/main/java/phyml/PhymlFrame.java | 1772 | package phyml;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Highly customisable standard frame for graphical user interface.
*
* @author Christoph Knapp
* @date 29/06/12
*/
public class PhymlFrame extends JFrame {
/**
* default id
*/
private static final long serialVersionUID = 1L;
/**
* Highly customisable standard JFrame for graphical user interface.
*
* @param title
* title of the gui displayed on the bar on top of the gui
* @param x
* : The initial y position of the gui on the screen (upper left
* corner)
* @param y
* : The initial y position of the gui on the screen (upper left
* corner)
* @param width
* : The initial width of the JPanel frameContent
* @param height
* : The initial height of the JPanel frameContent
* @param closOP
* : Integer specifying what to do when the gui is closed i.e.
* JFrame.EXIT_ON_CLOSE
* @param frameContent
* : JPanel to be added to the JFrame
* @param vis
* : boolean specifying wether the gui is visible or not
* @param resize
* : booloean value specifying wether the gui is resizable or not
*
*/
public PhymlFrame(String title, int x, int y, int width, int height,
int closeOP, JPanel frameContent, boolean vis, boolean resize) {
setTitle(title);
setLocation(x, y);
setDefaultCloseOperation(closeOP);
this.setResizable(resize);
Container visibleArea = getContentPane();
visibleArea.add(frameContent);
frameContent.setPreferredSize(new Dimension(width, height));
pack();
frameContent.requestFocusInWindow();
setVisible(vis);
}
}
| gpl-2.0 |
yterauchi/primecloud-controller | auto-project/auto-data/src/main/java/jp/primecloud/auto/entity/crud/ZabbixInstance.java | 1092 | /*
* Copyright 2014 by SCSK Corporation.
*
* This file is part of PrimeCloud Controller(TM).
*
* PrimeCloud Controller(TM) 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.
*
* PrimeCloud Controller(TM) 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 PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>.
*/
package jp.primecloud.auto.entity.crud;
/**
* <p>
* ZABBIX_INSTANCEに対応したエンティティです。
* </p>
*
*/
public class ZabbixInstance extends jp.primecloud.auto.entity.crud.BaseZabbixInstance {
/** SerialVersionUID */
private static final long serialVersionUID = 1L;
}
| gpl-2.0 |
lizhekang/TCJDK | sources/openjdk8/jdk/src/share/classes/sun/security/x509/X509CRLImpl.java | 47576 | /*
* 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.
*/
package sun.security.x509;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.Principal;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Signature;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.security.cert.X509CRLEntry;
import java.security.cert.CRLException;
import java.util.*;
import javax.security.auth.x500.X500Principal;
import sun.security.provider.X509Factory;
import sun.security.util.*;
import sun.misc.HexDumpEncoder;
/**
* <p>
* An implementation for X509 CRL (Certificate Revocation List).
* <p>
* The X.509 v2 CRL format is described below in ASN.1:
* <pre>
* CertificateList ::= SEQUENCE {
* tbsCertList TBSCertList,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING }
* </pre>
* More information can be found in
* <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
* Public Key Infrastructure Certificate and CRL Profile</a>.
* <p>
* The ASN.1 definition of <code>tbsCertList</code> is:
* <pre>
* TBSCertList ::= SEQUENCE {
* version Version OPTIONAL,
* -- if present, must be v2
* signature AlgorithmIdentifier,
* issuer Name,
* thisUpdate ChoiceOfTime,
* nextUpdate ChoiceOfTime OPTIONAL,
* revokedCertificates SEQUENCE OF SEQUENCE {
* userCertificate CertificateSerialNumber,
* revocationDate ChoiceOfTime,
* crlEntryExtensions Extensions OPTIONAL
* -- if present, must be v2
* } OPTIONAL,
* crlExtensions [0] EXPLICIT Extensions OPTIONAL
* -- if present, must be v2
* }
* </pre>
*
* @author Hemma Prafullchandra
* @see X509CRL
*/
public class X509CRLImpl extends X509CRL implements DerEncoder {
// CRL data, and its envelope
private byte[] signedCRL = null; // DER encoded crl
private byte[] signature = null; // raw signature bits
private byte[] tbsCertList = null; // DER encoded "to-be-signed" CRL
private AlgorithmId sigAlgId = null; // sig alg in CRL
// crl information
private int version;
private AlgorithmId infoSigAlgId; // sig alg in "to-be-signed" crl
private X500Name issuer = null;
private X500Principal issuerPrincipal = null;
private Date thisUpdate = null;
private Date nextUpdate = null;
private Map<X509IssuerSerial,X509CRLEntry> revokedMap = new TreeMap<>();
private List<X509CRLEntry> revokedList = new LinkedList<>();
private CRLExtensions extensions = null;
private final static boolean isExplicit = true;
private static final long YR_2050 = 2524636800000L;
private boolean readOnly = false;
/**
* PublicKey that has previously been used to successfully verify
* the signature of this CRL. Null if the CRL has not
* yet been verified (successfully).
*/
private PublicKey verifiedPublicKey;
/**
* If verifiedPublicKey is not null, name of the provider used to
* successfully verify the signature of this CRL, or the
* empty String if no provider was explicitly specified.
*/
private String verifiedProvider;
/**
* Not to be used. As it would lead to cases of uninitialized
* CRL objects.
*/
private X509CRLImpl() { }
/**
* Unmarshals an X.509 CRL from its encoded form, parsing the encoded
* bytes. This form of constructor is used by agents which
* need to examine and use CRL contents. Note that the buffer
* must include only one CRL, and no "garbage" may be left at
* the end.
*
* @param crlData the encoded bytes, with no trailing padding.
* @exception CRLException on parsing errors.
*/
public X509CRLImpl(byte[] crlData) throws CRLException {
try {
parse(new DerValue(crlData));
} catch (IOException e) {
signedCRL = null;
throw new CRLException("Parsing error: " + e.getMessage());
}
}
/**
* Unmarshals an X.509 CRL from an DER value.
*
* @param val a DER value holding at least one CRL
* @exception CRLException on parsing errors.
*/
public X509CRLImpl(DerValue val) throws CRLException {
try {
parse(val);
} catch (IOException e) {
signedCRL = null;
throw new CRLException("Parsing error: " + e.getMessage());
}
}
/**
* Unmarshals an X.509 CRL from an input stream. Only one CRL
* is expected at the end of the input stream.
*
* @param inStrm an input stream holding at least one CRL
* @exception CRLException on parsing errors.
*/
public X509CRLImpl(InputStream inStrm) throws CRLException {
try {
parse(new DerValue(inStrm));
} catch (IOException e) {
signedCRL = null;
throw new CRLException("Parsing error: " + e.getMessage());
}
}
/**
* Initial CRL constructor, no revoked certs, and no extensions.
*
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
*/
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate) {
this.issuer = issuer;
this.thisUpdate = thisDate;
this.nextUpdate = nextDate;
}
/**
* CRL constructor, revoked certs, no extensions.
*
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
* @param badCerts the array of CRL entries.
*
* @exception CRLException on parsing/construction errors.
*/
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate,
X509CRLEntry[] badCerts)
throws CRLException
{
this.issuer = issuer;
this.thisUpdate = thisDate;
this.nextUpdate = nextDate;
if (badCerts != null) {
X500Principal crlIssuer = getIssuerX500Principal();
X500Principal badCertIssuer = crlIssuer;
for (int i = 0; i < badCerts.length; i++) {
X509CRLEntryImpl badCert = (X509CRLEntryImpl)badCerts[i];
try {
badCertIssuer = getCertIssuer(badCert, badCertIssuer);
} catch (IOException ioe) {
throw new CRLException(ioe);
}
badCert.setCertificateIssuer(crlIssuer, badCertIssuer);
X509IssuerSerial issuerSerial = new X509IssuerSerial
(badCertIssuer, badCert.getSerialNumber());
this.revokedMap.put(issuerSerial, badCert);
this.revokedList.add(badCert);
if (badCert.hasExtensions()) {
this.version = 1;
}
}
}
}
/**
* CRL constructor, revoked certs and extensions.
*
* @param issuer the name of the CA issuing this CRL.
* @param thisUpdate the Date of this issue.
* @param nextUpdate the Date of the next CRL.
* @param badCerts the array of CRL entries.
* @param crlExts the CRL extensions.
*
* @exception CRLException on parsing/construction errors.
*/
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate,
X509CRLEntry[] badCerts, CRLExtensions crlExts)
throws CRLException
{
this(issuer, thisDate, nextDate, badCerts);
if (crlExts != null) {
this.extensions = crlExts;
this.version = 1;
}
}
/**
* Returned the encoding as an uncloned byte array. Callers must
* guarantee that they neither modify it nor expose it to untrusted
* code.
*/
public byte[] getEncodedInternal() throws CRLException {
if (signedCRL == null) {
throw new CRLException("Null CRL to encode");
}
return signedCRL;
}
/**
* Returns the ASN.1 DER encoded form of this CRL.
*
* @exception CRLException if an encoding error occurs.
*/
public byte[] getEncoded() throws CRLException {
return getEncodedInternal().clone();
}
/**
* Encodes the "to-be-signed" CRL to the OutputStream.
*
* @param out the OutputStream to write to.
* @exception CRLException on encoding errors.
*/
public void encodeInfo(OutputStream out) throws CRLException {
try {
DerOutputStream tmp = new DerOutputStream();
DerOutputStream rCerts = new DerOutputStream();
DerOutputStream seq = new DerOutputStream();
if (version != 0) // v2 crl encode version
tmp.putInteger(version);
infoSigAlgId.encode(tmp);
if ((version == 0) && (issuer.toString() == null))
throw new CRLException("Null Issuer DN not allowed in v1 CRL");
issuer.encode(tmp);
if (thisUpdate.getTime() < YR_2050)
tmp.putUTCTime(thisUpdate);
else
tmp.putGeneralizedTime(thisUpdate);
if (nextUpdate != null) {
if (nextUpdate.getTime() < YR_2050)
tmp.putUTCTime(nextUpdate);
else
tmp.putGeneralizedTime(nextUpdate);
}
if (!revokedList.isEmpty()) {
for (X509CRLEntry entry : revokedList) {
((X509CRLEntryImpl)entry).encode(rCerts);
}
tmp.write(DerValue.tag_Sequence, rCerts);
}
if (extensions != null)
extensions.encode(tmp, isExplicit);
seq.write(DerValue.tag_Sequence, tmp);
tbsCertList = seq.toByteArray();
out.write(tbsCertList);
} catch (IOException e) {
throw new CRLException("Encoding error: " + e.getMessage());
}
}
/**
* Verifies that this CRL was signed using the
* private key that corresponds to the given public key.
*
* @param key the PublicKey used to carry out the verification.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException if there's no default provider.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public void verify(PublicKey key)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
verify(key, "");
}
/**
* Verifies that this CRL was signed using the
* private key that corresponds to the given public key,
* and that the signature verification was computed by
* the given provider.
*
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the name of the signature provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public synchronized void verify(PublicKey key, String sigProvider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
if (sigProvider == null) {
sigProvider = "";
}
if ((verifiedPublicKey != null) && verifiedPublicKey.equals(key)) {
// this CRL has already been successfully verified using
// this public key. Make sure providers match, too.
if (sigProvider.equals(verifiedProvider)) {
return;
}
}
if (signedCRL == null) {
throw new CRLException("Uninitialized CRL");
}
Signature sigVerf = null;
if (sigProvider.length() == 0) {
sigVerf = Signature.getInstance(sigAlgId.getName());
} else {
sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
}
sigVerf.initVerify(key);
if (tbsCertList == null) {
throw new CRLException("Uninitialized CRL");
}
sigVerf.update(tbsCertList, 0, tbsCertList.length);
if (!sigVerf.verify(signature)) {
throw new SignatureException("Signature does not match.");
}
verifiedPublicKey = key;
verifiedProvider = sigProvider;
}
/**
* Verifies that this CRL was signed using the
* private key that corresponds to the given public key,
* and that the signature verification was computed by
* the given provider. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param key the PublicKey used to carry out the verification.
* @param sigProvider the signature provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception SignatureException on signature errors.
* @exception CRLException on encoding errors.
*/
public synchronized void verify(PublicKey key, Provider sigProvider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
SignatureException {
if (signedCRL == null) {
throw new CRLException("Uninitialized CRL");
}
Signature sigVerf = null;
if (sigProvider == null) {
sigVerf = Signature.getInstance(sigAlgId.getName());
} else {
sigVerf = Signature.getInstance(sigAlgId.getName(), sigProvider);
}
sigVerf.initVerify(key);
if (tbsCertList == null) {
throw new CRLException("Uninitialized CRL");
}
sigVerf.update(tbsCertList, 0, tbsCertList.length);
if (!sigVerf.verify(signature)) {
throw new SignatureException("Signature does not match.");
}
verifiedPublicKey = key;
}
/**
* This static method is the default implementation of the
* verify(PublicKey key, Provider sigProvider) method in X509CRL.
* Called from java.security.cert.X509CRL.verify(PublicKey key,
* Provider sigProvider)
*/
public static void verify(X509CRL crl, PublicKey key,
Provider sigProvider) throws CRLException,
NoSuchAlgorithmException, InvalidKeyException, SignatureException {
crl.verify(key, sigProvider);
}
/**
* Encodes an X.509 CRL, and signs it using the given key.
*
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException if any mandatory data was omitted.
*/
public void sign(PrivateKey key, String algorithm)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
sign(key, algorithm, null);
}
/**
* Encodes an X.509 CRL, and signs it using the given key.
*
* @param key the private key used for signing.
* @param algorithm the name of the signature algorithm used.
* @param provider the name of the provider.
*
* @exception NoSuchAlgorithmException on unsupported signature
* algorithms.
* @exception InvalidKeyException on incorrect key.
* @exception NoSuchProviderException on incorrect provider.
* @exception SignatureException on signature errors.
* @exception CRLException if any mandatory data was omitted.
*/
public void sign(PrivateKey key, String algorithm, String provider)
throws CRLException, NoSuchAlgorithmException, InvalidKeyException,
NoSuchProviderException, SignatureException {
try {
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
Signature sigEngine = null;
if ((provider == null) || (provider.length() == 0))
sigEngine = Signature.getInstance(algorithm);
else
sigEngine = Signature.getInstance(algorithm, provider);
sigEngine.initSign(key);
// in case the name is reset
sigAlgId = AlgorithmId.get(sigEngine.getAlgorithm());
infoSigAlgId = sigAlgId;
DerOutputStream out = new DerOutputStream();
DerOutputStream tmp = new DerOutputStream();
// encode crl info
encodeInfo(tmp);
// encode algorithm identifier
sigAlgId.encode(tmp);
// Create and encode the signature itself.
sigEngine.update(tbsCertList, 0, tbsCertList.length);
signature = sigEngine.sign();
tmp.putBitString(signature);
// Wrap the signed data in a SEQUENCE { data, algorithm, sig }
out.write(DerValue.tag_Sequence, tmp);
signedCRL = out.toByteArray();
readOnly = true;
} catch (IOException e) {
throw new CRLException("Error while encoding data: " +
e.getMessage());
}
}
/**
* Returns a printable string of this CRL.
*
* @return value of this CRL in a printable form.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("X.509 CRL v" + (version+1) + "\n");
if (sigAlgId != null)
sb.append("Signature Algorithm: " + sigAlgId.toString() +
", OID=" + (sigAlgId.getOID()).toString() + "\n");
if (issuer != null)
sb.append("Issuer: " + issuer.toString() + "\n");
if (thisUpdate != null)
sb.append("\nThis Update: " + thisUpdate.toString() + "\n");
if (nextUpdate != null)
sb.append("Next Update: " + nextUpdate.toString() + "\n");
if (revokedList.isEmpty())
sb.append("\nNO certificates have been revoked\n");
else {
sb.append("\nRevoked Certificates: " + revokedList.size());
int i = 1;
for (X509CRLEntry entry: revokedList) {
sb.append("\n[" + i++ + "] " + entry.toString());
}
}
if (extensions != null) {
Collection<Extension> allExts = extensions.getAllExtensions();
Object[] objs = allExts.toArray();
sb.append("\nCRL Extensions: " + objs.length);
for (int i = 0; i < objs.length; i++) {
sb.append("\n[" + (i+1) + "]: ");
Extension ext = (Extension)objs[i];
try {
if (OIDMap.getClass(ext.getExtensionId()) == null) {
sb.append(ext.toString());
byte[] extValue = ext.getExtensionValue();
if (extValue != null) {
DerOutputStream out = new DerOutputStream();
out.putOctetString(extValue);
extValue = out.toByteArray();
HexDumpEncoder enc = new HexDumpEncoder();
sb.append("Extension unknown: "
+ "DER encoded OCTET string =\n"
+ enc.encodeBuffer(extValue) + "\n");
}
} else
sb.append(ext.toString()); // sub-class exists
} catch (Exception e) {
sb.append(", Error parsing this extension");
}
}
}
if (signature != null) {
HexDumpEncoder encoder = new HexDumpEncoder();
sb.append("\nSignature:\n" + encoder.encodeBuffer(signature)
+ "\n");
} else
sb.append("NOT signed yet\n");
return sb.toString();
}
/**
* Checks whether the given certificate is on this CRL.
*
* @param cert the certificate to check for.
* @return true if the given certificate is on this CRL,
* false otherwise.
*/
public boolean isRevoked(Certificate cert) {
if (revokedMap.isEmpty() || (!(cert instanceof X509Certificate))) {
return false;
}
X509Certificate xcert = (X509Certificate) cert;
X509IssuerSerial issuerSerial = new X509IssuerSerial(xcert);
return revokedMap.containsKey(issuerSerial);
}
/**
* Gets the version number from this CRL.
* The ASN.1 definition for this is:
* <pre>
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
* -- v3 does not apply to CRLs but appears for consistency
* -- with definition of Version for certs
* </pre>
* @return the version number, i.e. 1 or 2.
*/
public int getVersion() {
return version+1;
}
/**
* Gets the issuer distinguished name from this CRL.
* The issuer name identifies the entity who has signed (and
* issued the CRL). The issuer name field contains an
* X.500 distinguished name (DN).
* The ASN.1 definition for this is:
* <pre>
* issuer Name
*
* Name ::= CHOICE { RDNSequence }
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
* RelativeDistinguishedName ::=
* SET OF AttributeValueAssertion
*
* AttributeValueAssertion ::= SEQUENCE {
* AttributeType,
* AttributeValue }
* AttributeType ::= OBJECT IDENTIFIER
* AttributeValue ::= ANY
* </pre>
* The Name describes a hierarchical name composed of attributes,
* such as country name, and corresponding values, such as US.
* The type of the component AttributeValue is determined by the
* AttributeType; in general it will be a directoryString.
* A directoryString is usually one of PrintableString,
* TeletexString or UniversalString.
* @return the issuer name.
*/
public Principal getIssuerDN() {
return (Principal)issuer;
}
/**
* Return the issuer as X500Principal. Overrides method in X509CRL
* to provide a slightly more efficient version.
*/
public X500Principal getIssuerX500Principal() {
if (issuerPrincipal == null) {
issuerPrincipal = issuer.asX500Principal();
}
return issuerPrincipal;
}
/**
* Gets the thisUpdate date from the CRL.
* The ASN.1 definition for this is:
*
* @return the thisUpdate date from the CRL.
*/
public Date getThisUpdate() {
return (new Date(thisUpdate.getTime()));
}
/**
* Gets the nextUpdate date from the CRL.
*
* @return the nextUpdate date from the CRL, or null if
* not present.
*/
public Date getNextUpdate() {
if (nextUpdate == null)
return null;
return (new Date(nextUpdate.getTime()));
}
/**
* Gets the CRL entry with the given serial number from this CRL.
*
* @return the entry with the given serial number, or <code>null</code> if
* no such entry exists in the CRL.
* @see X509CRLEntry
*/
public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) {
if (revokedMap.isEmpty()) {
return null;
}
// assume this is a direct CRL entry (cert and CRL issuer are the same)
X509IssuerSerial issuerSerial = new X509IssuerSerial
(getIssuerX500Principal(), serialNumber);
return revokedMap.get(issuerSerial);
}
/**
* Gets the CRL entry for the given certificate.
*/
public X509CRLEntry getRevokedCertificate(X509Certificate cert) {
if (revokedMap.isEmpty()) {
return null;
}
X509IssuerSerial issuerSerial = new X509IssuerSerial(cert);
return revokedMap.get(issuerSerial);
}
/**
* Gets all the revoked certificates from the CRL.
* A Set of X509CRLEntry.
*
* @return all the revoked certificates or <code>null</code> if there are
* none.
* @see X509CRLEntry
*/
public Set<X509CRLEntry> getRevokedCertificates() {
if (revokedList.isEmpty()) {
return null;
} else {
return new TreeSet<X509CRLEntry>(revokedList);
}
}
/**
* Gets the DER encoded CRL information, the
* <code>tbsCertList</code> from this CRL.
* This can be used to verify the signature independently.
*
* @return the DER encoded CRL information.
* @exception CRLException on encoding errors.
*/
public byte[] getTBSCertList() throws CRLException {
if (tbsCertList == null)
throw new CRLException("Uninitialized CRL");
return tbsCertList.clone();
}
/**
* Gets the raw Signature bits from the CRL.
*
* @return the signature.
*/
public byte[] getSignature() {
if (signature == null)
return null;
return signature.clone();
}
/**
* Gets the signature algorithm name for the CRL
* signature algorithm. For example, the string "SHA1withDSA".
* The ASN.1 definition for this is:
* <pre>
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
* -- contains a value of the type
* -- registered for use with the
* -- algorithm object identifier value
* </pre>
*
* @return the signature algorithm name.
*/
public String getSigAlgName() {
if (sigAlgId == null)
return null;
return sigAlgId.getName();
}
/**
* Gets the signature algorithm OID string from the CRL.
* An OID is represented by a set of positive whole number separated
* by ".", that means,<br>
* <positive whole number>.<positive whole number>.<...>
* For example, the string "1.2.840.10040.4.3" identifies the SHA-1
* with DSA signature algorithm defined in
* <a href="http://www.ietf.org/rfc/rfc3279.txt">RFC 3279: Algorithms and
* Identifiers for the Internet X.509 Public Key Infrastructure Certificate
* and CRL Profile</a>.
*
* @return the signature algorithm oid string.
*/
public String getSigAlgOID() {
if (sigAlgId == null)
return null;
ObjectIdentifier oid = sigAlgId.getOID();
return oid.toString();
}
/**
* Gets the DER encoded signature algorithm parameters from this
* CRL's signature algorithm. In most cases, the signature
* algorithm parameters are null, the parameters are usually
* supplied with the Public Key.
*
* @return the DER encoded signature algorithm parameters, or
* null if no parameters are present.
*/
public byte[] getSigAlgParams() {
if (sigAlgId == null)
return null;
try {
return sigAlgId.getEncodedParams();
} catch (IOException e) {
return null;
}
}
/**
* Gets the signature AlgorithmId from the CRL.
*
* @return the signature AlgorithmId
*/
public AlgorithmId getSigAlgId() {
return sigAlgId;
}
/**
* return the AuthorityKeyIdentifier, if any.
*
* @returns AuthorityKeyIdentifier or null
* (if no AuthorityKeyIdentifierExtension)
* @throws IOException on error
*/
public KeyIdentifier getAuthKeyId() throws IOException {
AuthorityKeyIdentifierExtension aki = getAuthKeyIdExtension();
if (aki != null) {
KeyIdentifier keyId = (KeyIdentifier)aki.get(
AuthorityKeyIdentifierExtension.KEY_ID);
return keyId;
} else {
return null;
}
}
/**
* return the AuthorityKeyIdentifierExtension, if any.
*
* @returns AuthorityKeyIdentifierExtension or null (if no such extension)
* @throws IOException on error
*/
public AuthorityKeyIdentifierExtension getAuthKeyIdExtension()
throws IOException {
Object obj = getExtension(PKIXExtensions.AuthorityKey_Id);
return (AuthorityKeyIdentifierExtension)obj;
}
/**
* return the CRLNumberExtension, if any.
*
* @returns CRLNumberExtension or null (if no such extension)
* @throws IOException on error
*/
public CRLNumberExtension getCRLNumberExtension() throws IOException {
Object obj = getExtension(PKIXExtensions.CRLNumber_Id);
return (CRLNumberExtension)obj;
}
/**
* return the CRL number from the CRLNumberExtension, if any.
*
* @returns number or null (if no such extension)
* @throws IOException on error
*/
public BigInteger getCRLNumber() throws IOException {
CRLNumberExtension numExt = getCRLNumberExtension();
if (numExt != null) {
BigInteger num = numExt.get(CRLNumberExtension.NUMBER);
return num;
} else {
return null;
}
}
/**
* return the DeltaCRLIndicatorExtension, if any.
*
* @returns DeltaCRLIndicatorExtension or null (if no such extension)
* @throws IOException on error
*/
public DeltaCRLIndicatorExtension getDeltaCRLIndicatorExtension()
throws IOException {
Object obj = getExtension(PKIXExtensions.DeltaCRLIndicator_Id);
return (DeltaCRLIndicatorExtension)obj;
}
/**
* return the base CRL number from the DeltaCRLIndicatorExtension, if any.
*
* @returns number or null (if no such extension)
* @throws IOException on error
*/
public BigInteger getBaseCRLNumber() throws IOException {
DeltaCRLIndicatorExtension dciExt = getDeltaCRLIndicatorExtension();
if (dciExt != null) {
BigInteger num = dciExt.get(DeltaCRLIndicatorExtension.NUMBER);
return num;
} else {
return null;
}
}
/**
* return the IssuerAlternativeNameExtension, if any.
*
* @returns IssuerAlternativeNameExtension or null (if no such extension)
* @throws IOException on error
*/
public IssuerAlternativeNameExtension getIssuerAltNameExtension()
throws IOException {
Object obj = getExtension(PKIXExtensions.IssuerAlternativeName_Id);
return (IssuerAlternativeNameExtension)obj;
}
/**
* return the IssuingDistributionPointExtension, if any.
*
* @returns IssuingDistributionPointExtension or null
* (if no such extension)
* @throws IOException on error
*/
public IssuingDistributionPointExtension
getIssuingDistributionPointExtension() throws IOException {
Object obj = getExtension(PKIXExtensions.IssuingDistributionPoint_Id);
return (IssuingDistributionPointExtension) obj;
}
/**
* Return true if a critical extension is found that is
* not supported, otherwise return false.
*/
public boolean hasUnsupportedCriticalExtension() {
if (extensions == null)
return false;
return extensions.hasUnsupportedCriticalExtension();
}
/**
* Gets a Set of the extension(s) marked CRITICAL in the
* CRL. In the returned set, each extension is represented by
* its OID string.
*
* @return a set of the extension oid strings in the
* CRL that are marked critical.
*/
public Set<String> getCriticalExtensionOIDs() {
if (extensions == null) {
return null;
}
Set<String> extSet = new TreeSet<>();
for (Extension ex : extensions.getAllExtensions()) {
if (ex.isCritical()) {
extSet.add(ex.getExtensionId().toString());
}
}
return extSet;
}
/**
* Gets a Set of the extension(s) marked NON-CRITICAL in the
* CRL. In the returned set, each extension is represented by
* its OID string.
*
* @return a set of the extension oid strings in the
* CRL that are NOT marked critical.
*/
public Set<String> getNonCriticalExtensionOIDs() {
if (extensions == null) {
return null;
}
Set<String> extSet = new TreeSet<>();
for (Extension ex : extensions.getAllExtensions()) {
if (!ex.isCritical()) {
extSet.add(ex.getExtensionId().toString());
}
}
return extSet;
}
/**
* Gets the DER encoded OCTET string for the extension value
* (<code>extnValue</code>) identified by the passed in oid String.
* The <code>oid</code> string is
* represented by a set of positive whole number separated
* by ".", that means,<br>
* <positive whole number>.<positive whole number>.<...>
*
* @param oid the Object Identifier value for the extension.
* @return the der encoded octet string of the extension value.
*/
public byte[] getExtensionValue(String oid) {
if (extensions == null)
return null;
try {
String extAlias = OIDMap.getName(new ObjectIdentifier(oid));
Extension crlExt = null;
if (extAlias == null) { // may be unknown
ObjectIdentifier findOID = new ObjectIdentifier(oid);
Extension ex = null;
ObjectIdentifier inCertOID;
for (Enumeration<Extension> e = extensions.getElements();
e.hasMoreElements();) {
ex = e.nextElement();
inCertOID = ex.getExtensionId();
if (inCertOID.equals((Object)findOID)) {
crlExt = ex;
break;
}
}
} else
crlExt = extensions.get(extAlias);
if (crlExt == null)
return null;
byte[] extData = crlExt.getExtensionValue();
if (extData == null)
return null;
DerOutputStream out = new DerOutputStream();
out.putOctetString(extData);
return out.toByteArray();
} catch (Exception e) {
return null;
}
}
/**
* get an extension
*
* @param oid ObjectIdentifier of extension desired
* @returns Object of type <extension> or null, if not found
* @throws IOException on error
*/
public Object getExtension(ObjectIdentifier oid) {
if (extensions == null)
return null;
// XXX Consider cloning this
return extensions.get(OIDMap.getName(oid));
}
/*
* Parses an X.509 CRL, should be used only by constructors.
*/
private void parse(DerValue val) throws CRLException, IOException {
// check if can over write the certificate
if (readOnly)
throw new CRLException("cannot over-write existing CRL");
if ( val.getData() == null || val.tag != DerValue.tag_Sequence)
throw new CRLException("Invalid DER-encoded CRL data");
signedCRL = val.toByteArray();
DerValue seq[] = new DerValue[3];
seq[0] = val.data.getDerValue();
seq[1] = val.data.getDerValue();
seq[2] = val.data.getDerValue();
if (val.data.available() != 0)
throw new CRLException("signed overrun, bytes = "
+ val.data.available());
if (seq[0].tag != DerValue.tag_Sequence)
throw new CRLException("signed CRL fields invalid");
sigAlgId = AlgorithmId.parse(seq[1]);
signature = seq[2].getBitString();
if (seq[1].data.available() != 0)
throw new CRLException("AlgorithmId field overrun");
if (seq[2].data.available() != 0)
throw new CRLException("Signature field overrun");
// the tbsCertsList
tbsCertList = seq[0].toByteArray();
// parse the information
DerInputStream derStrm = seq[0].data;
DerValue tmp;
byte nextByte;
// version (optional if v1)
version = 0; // by default, version = v1 == 0
nextByte = (byte)derStrm.peekByte();
if (nextByte == DerValue.tag_Integer) {
version = derStrm.getInteger();
if (version != 1) // i.e. v2
throw new CRLException("Invalid version");
}
tmp = derStrm.getDerValue();
// signature
AlgorithmId tmpId = AlgorithmId.parse(tmp);
// the "inner" and "outer" signature algorithms must match
if (! tmpId.equals(sigAlgId))
throw new CRLException("Signature algorithm mismatch");
infoSigAlgId = tmpId;
// issuer
issuer = new X500Name(derStrm);
if (issuer.isEmpty()) {
throw new CRLException("Empty issuer DN not allowed in X509CRLs");
}
// thisUpdate
// check if UTCTime encoded or GeneralizedTime
nextByte = (byte)derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
thisUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
thisUpdate = derStrm.getGeneralizedTime();
} else {
throw new CRLException("Invalid encoding for thisUpdate"
+ " (tag=" + nextByte + ")");
}
if (derStrm.available() == 0)
return; // done parsing no more optional fields present
// nextUpdate (optional)
nextByte = (byte)derStrm.peekByte();
if (nextByte == DerValue.tag_UtcTime) {
nextUpdate = derStrm.getUTCTime();
} else if (nextByte == DerValue.tag_GeneralizedTime) {
nextUpdate = derStrm.getGeneralizedTime();
} // else it is not present
if (derStrm.available() == 0)
return; // done parsing no more optional fields present
// revokedCertificates (optional)
nextByte = (byte)derStrm.peekByte();
if ((nextByte == DerValue.tag_SequenceOf)
&& (! ((nextByte & 0x0c0) == 0x080))) {
DerValue[] badCerts = derStrm.getSequence(4);
X500Principal crlIssuer = getIssuerX500Principal();
X500Principal badCertIssuer = crlIssuer;
for (int i = 0; i < badCerts.length; i++) {
X509CRLEntryImpl entry = new X509CRLEntryImpl(badCerts[i]);
badCertIssuer = getCertIssuer(entry, badCertIssuer);
entry.setCertificateIssuer(crlIssuer, badCertIssuer);
X509IssuerSerial issuerSerial = new X509IssuerSerial
(badCertIssuer, entry.getSerialNumber());
revokedMap.put(issuerSerial, entry);
revokedList.add(entry);
}
}
if (derStrm.available() == 0)
return; // done parsing no extensions
// crlExtensions (optional)
tmp = derStrm.getDerValue();
if (tmp.isConstructed() && tmp.isContextSpecific((byte)0)) {
extensions = new CRLExtensions(tmp.data);
}
readOnly = true;
}
/**
* Extract the issuer X500Principal from an X509CRL. Parses the encoded
* form of the CRL to preserve the principal's ASN.1 encoding.
*
* Called by java.security.cert.X509CRL.getIssuerX500Principal().
*/
public static X500Principal getIssuerX500Principal(X509CRL crl) {
try {
byte[] encoded = crl.getEncoded();
DerInputStream derIn = new DerInputStream(encoded);
DerValue tbsCert = derIn.getSequence(3)[0];
DerInputStream tbsIn = tbsCert.data;
DerValue tmp;
// skip version number if present
byte nextByte = (byte)tbsIn.peekByte();
if (nextByte == DerValue.tag_Integer) {
tmp = tbsIn.getDerValue();
}
tmp = tbsIn.getDerValue(); // skip signature
tmp = tbsIn.getDerValue(); // issuer
byte[] principalBytes = tmp.toByteArray();
return new X500Principal(principalBytes);
} catch (Exception e) {
throw new RuntimeException("Could not parse issuer", e);
}
}
/**
* Returned the encoding of the given certificate for internal use.
* Callers must guarantee that they neither modify it nor expose it
* to untrusted code. Uses getEncodedInternal() if the certificate
* is instance of X509CertImpl, getEncoded() otherwise.
*/
public static byte[] getEncodedInternal(X509CRL crl) throws CRLException {
if (crl instanceof X509CRLImpl) {
return ((X509CRLImpl)crl).getEncodedInternal();
} else {
return crl.getEncoded();
}
}
/**
* Utility method to convert an arbitrary instance of X509CRL
* to a X509CRLImpl. Does a cast if possible, otherwise reparses
* the encoding.
*/
public static X509CRLImpl toImpl(X509CRL crl)
throws CRLException {
if (crl instanceof X509CRLImpl) {
return (X509CRLImpl)crl;
} else {
return X509Factory.intern(crl);
}
}
/**
* Returns the X500 certificate issuer DN of a CRL entry.
*
* @param entry the entry to check
* @param prevCertIssuer the previous entry's certificate issuer
* @return the X500Principal in a CertificateIssuerExtension, or
* prevCertIssuer if it does not exist
*/
private X500Principal getCertIssuer(X509CRLEntryImpl entry,
X500Principal prevCertIssuer) throws IOException {
CertificateIssuerExtension ciExt =
entry.getCertificateIssuerExtension();
if (ciExt != null) {
GeneralNames names = ciExt.get(CertificateIssuerExtension.ISSUER);
X500Name issuerDN = (X500Name) names.get(0).getName();
return issuerDN.asX500Principal();
} else {
return prevCertIssuer;
}
}
@Override
public void derEncode(OutputStream out) throws IOException {
if (signedCRL == null)
throw new IOException("Null CRL to encode");
out.write(signedCRL.clone());
}
/**
* Immutable X.509 Certificate Issuer DN and serial number pair
*/
private final static class X509IssuerSerial
implements Comparable<X509IssuerSerial> {
final X500Principal issuer;
final BigInteger serial;
volatile int hashcode = 0;
/**
* Create an X509IssuerSerial.
*
* @param issuer the issuer DN
* @param serial the serial number
*/
X509IssuerSerial(X500Principal issuer, BigInteger serial) {
this.issuer = issuer;
this.serial = serial;
}
/**
* Construct an X509IssuerSerial from an X509Certificate.
*/
X509IssuerSerial(X509Certificate cert) {
this(cert.getIssuerX500Principal(), cert.getSerialNumber());
}
/**
* Returns the issuer.
*
* @return the issuer
*/
X500Principal getIssuer() {
return issuer;
}
/**
* Returns the serial number.
*
* @return the serial number
*/
BigInteger getSerial() {
return serial;
}
/**
* Compares this X509Serial with another and returns true if they
* are equivalent.
*
* @param o the other object to compare with
* @return true if equal, false otherwise
*/
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof X509IssuerSerial)) {
return false;
}
X509IssuerSerial other = (X509IssuerSerial) o;
if (serial.equals(other.getSerial()) &&
issuer.equals(other.getIssuer())) {
return true;
}
return false;
}
/**
* Returns a hash code value for this X509IssuerSerial.
*
* @return the hash code value
*/
public int hashCode() {
if (hashcode == 0) {
int result = 17;
result = 37*result + issuer.hashCode();
result = 37*result + serial.hashCode();
hashcode = result;
}
return hashcode;
}
@Override
public int compareTo(X509IssuerSerial another) {
int cissuer = issuer.toString()
.compareTo(another.issuer.toString());
if (cissuer != 0) return cissuer;
return this.serial.compareTo(another.serial);
}
}
}
| gpl-2.0 |
DarkRainX/ufoai | eclipse/net.sourceforge.ufoai.glsleditors/src/cgEditor/editors/GLSLEditor.java | 1331 | package cgEditor.editors;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.editors.text.TextEditor;
import cgEditor.CgEditorPlugin;
import cgEditor.preferences.PreferenceConstants;
public class GLSLEditor extends TextEditor implements IPropertyChangeListener {
public GLSLEditor() {
super();
setSourceViewerConfiguration(new GLSLConfiguration());
CgEditorPlugin.getDefault().getPreferenceStore()
.addPropertyChangeListener(this);
}
@Override
public void dispose() {
super.dispose();
}
@Override
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
super.handlePreferenceStoreChanged(event);
}
@Override
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
boolean affect = false;
for (int i = 0; i < PreferenceConstants.PREFERENCES.length; i++) {
affect = affect
|| event.getProperty().equals(
PreferenceConstants.PREFERENCES[i][0])
|| event.getProperty().equals(
PreferenceConstants.PREFERENCES[i][1])
|| event.getProperty().equals(
PreferenceConstants.PREFERENCES[i][2]);
}
return affect || super.affectsTextPresentation(event);
}
public void propertyChange(PropertyChangeEvent event) {
handlePreferenceStoreChanged(event);
}
}
| gpl-2.0 |
ligfx/dolphin | Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/ui/main/MainActivity.java | 6154 | package org.dolphinemu.dolphinemu.ui.main;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import org.dolphinemu.dolphinemu.R;
import org.dolphinemu.dolphinemu.activities.AddDirectoryActivity;
import org.dolphinemu.dolphinemu.adapters.PlatformPagerAdapter;
import org.dolphinemu.dolphinemu.model.GameProvider;
import org.dolphinemu.dolphinemu.ui.platform.Platform;
import org.dolphinemu.dolphinemu.ui.platform.PlatformGamesView;
import org.dolphinemu.dolphinemu.ui.settings.SettingsActivity;
import org.dolphinemu.dolphinemu.utils.PermissionsHandler;
import org.dolphinemu.dolphinemu.utils.StartupHandler;
/**
* The main Activity of the Lollipop style UI. Manages several PlatformGamesFragments, which
* individually display a grid of available games for each Fragment, in a tabbed layout.
*/
public final class MainActivity extends AppCompatActivity implements MainView
{
private ViewPager mViewPager;
private Toolbar mToolbar;
private TabLayout mTabLayout;
private FloatingActionButton mFab;
private MainPresenter mPresenter = new MainPresenter(this);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setSupportActionBar(mToolbar);
mTabLayout.setupWithViewPager(mViewPager);
// Set up the FAB.
mFab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
mPresenter.onFabClick();
}
});
mPresenter.onCreate();
// Stuff in this block only happens when this activity is newly created (i.e. not a rotation)
// TODO Split some of this stuff into Application.onCreate()
if (savedInstanceState == null)
StartupHandler.HandleInit(this);
if (PermissionsHandler.hasWriteAccess(this))
{
PlatformPagerAdapter platformPagerAdapter = new PlatformPagerAdapter(
getSupportFragmentManager(), this);
mViewPager.setAdapter(platformPagerAdapter);
} else {
mViewPager.setVisibility(View.INVISIBLE);
}
}
// TODO: Replace with a ButterKnife injection.
private void findViews()
{
mToolbar = (Toolbar) findViewById(R.id.toolbar_main);
mViewPager = (ViewPager) findViewById(R.id.pager_platforms);
mTabLayout = (TabLayout) findViewById(R.id.tabs_platforms);
mFab = (FloatingActionButton) findViewById(R.id.button_add_directory);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_game_grid, menu);
return true;
}
/**
* MainView
*/
@Override
public void setVersionString(String version)
{
mToolbar.setSubtitle(version);
}
@Override
public void refresh()
{
getContentResolver().insert(GameProvider.URI_REFRESH, null);
refreshFragment();
}
@Override
public void refreshFragmentScreenshot(int fragmentPosition)
{
// Invalidate Picasso image so that the new screenshot is animated in.
Platform platform = Platform.fromPosition(mViewPager.getCurrentItem());
PlatformGamesView fragment = getPlatformGamesView(platform);
if (fragment != null)
{
fragment.refreshScreenshotAtPosition(fragmentPosition);
}
}
@Override
public void launchSettingsActivity(String menuTag)
{
SettingsActivity.launch(this, menuTag);
}
@Override
public void launchFileListActivity()
{
AddDirectoryActivity.launch(this);
}
@Override
public void showGames(Platform platform, Cursor games)
{
// no-op. Handled by PlatformGamesFragment.
}
/**
* Callback from AddDirectoryActivity. Applies any changes necessary to the GameGridActivity.
*
* @param requestCode An int describing whether the Activity that is returning did so successfully.
* @param resultCode An int describing what Activity is giving us this callback.
* @param result The information the returning Activity is providing us.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result)
{
mPresenter.handleActivityResult(requestCode, resultCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case PermissionsHandler.REQUEST_CODE_WRITE_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
StartupHandler.copyAssetsIfNeeded(this);
PlatformPagerAdapter platformPagerAdapter = new PlatformPagerAdapter(
getSupportFragmentManager(), this);
mViewPager.setAdapter(platformPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, R.string.write_permission_needed, Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
/**
* Called by the framework whenever any actionbar/toolbar icon is clicked.
*
* @param item The icon that was clicked on.
* @return True if the event was handled, false to bubble it up to the OS.
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return mPresenter.handleOptionSelection(item.getItemId());
}
private void refreshFragment()
{
Platform platform = Platform.fromPosition(mViewPager.getCurrentItem());
PlatformGamesView fragment = getPlatformGamesView(platform);
if (fragment != null)
{
fragment.refresh();
}
}
@Nullable
private PlatformGamesView getPlatformGamesView(Platform platform)
{
String fragmentTag = "android:switcher:" + mViewPager.getId() + ":" + platform;
return (PlatformGamesView) getSupportFragmentManager().findFragmentByTag(fragmentTag);
}
}
| gpl-2.0 |
kattakum/OWASP-WebScarab | src/org/owasp/webscarab/model/FilteredUrlModel.java | 8105 | /*
* FilteredUrlModel.java
*
* Created on 04 March 2005, 10:35
*/
package org.owasp.webscarab.model;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Collections;
import EDU.oswego.cs.dl.util.concurrent.Sync;
import javax.swing.event.EventListenerList;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.owasp.webscarab.util.MRUCache;
/**
*
* @author rogan
*/
public abstract class FilteredUrlModel extends AbstractUrlModel {
protected UrlModel _urlModel;
private Set<HttpUrl> _filteredUrls = null;
private Set<HttpUrl> _implicitUrls = null;
private MRUCache<HttpUrl, ArrayList<HttpUrl>> _cache = new MRUCache<HttpUrl, ArrayList<HttpUrl>>(16);
protected EventListenerList _listenerList = new EventListenerList();
protected Logger _logger = Logger.getLogger(getClass().getName());
private boolean _updating = false;
private int hit, miss = 0;
/** Creates a new instance of FilteredUrlModel */
public FilteredUrlModel(UrlModel urlModel) {
_logger.setLevel(Level.INFO);
_urlModel = urlModel;
try {
_urlModel.readLock().acquire();
updateFilteredUrls();
_urlModel.addUrlListener(new Listener());
} catch (InterruptedException ie) {
_logger.warning("Interrupted waiting for the read lock! " + ie.getMessage());
} finally {
_urlModel.readLock().release();
}
}
public Sync readLock() {
return _urlModel.readLock();
}
protected void initFilters() {
_filteredUrls = new HashSet<HttpUrl>();
_implicitUrls = new HashSet<HttpUrl>();
}
protected abstract boolean shouldFilter(HttpUrl url);
protected boolean isFiltered(HttpUrl url) {
return _filteredUrls != null && _filteredUrls.contains(url);
}
protected void setFiltered(HttpUrl url, boolean filtered) {
if (filtered) {
_filteredUrls.add(url);
} else {
_filteredUrls.remove(url);
}
}
public boolean isImplicit(HttpUrl url) {
return _implicitUrls.contains(url);
}
protected void setImplicit(HttpUrl url, boolean filtered) {
if (_implicitUrls == null) _implicitUrls = new HashSet<HttpUrl>();
if (filtered) {
_implicitUrls.add(url);
} else {
_implicitUrls.remove(url);
}
}
private boolean isVisible(HttpUrl url) {
return isImplicit(url) || ! isFiltered(url);
}
public int getIndexOf(HttpUrl url) {
int index = Collections.binarySearch(getFilteredChildren(url), url);
return index < 0 ? -1 : index;
}
public HttpUrl getChildAt(HttpUrl url, int index) {
return (HttpUrl) getFilteredChildren(url).get(index);
}
private void updateFilteredUrls() {
initFilters();
recurseTree(null);
}
private ArrayList<HttpUrl> getFilteredChildren(HttpUrl parent) {
ArrayList<HttpUrl> childList = _cache.get(parent);
if (childList != null) {
hit++;
return childList;
}
try {
childList = new ArrayList<HttpUrl>();
_urlModel.readLock().acquire();
int count = _urlModel.getChildCount(parent);
for (int i=0; i<count; i++) {
HttpUrl child = _urlModel.getChildAt(parent, i);
if (isVisible(child))
childList.add(child);
}
if (count > 0) { // we are saving some real work here
miss++;
_logger.fine("Hit=" + hit + ", miss=" + miss + " parent = " + parent + " count="+count);
_cache.put(parent, childList);
}
return childList;
} catch (InterruptedException ie) {
_logger.warning("Interrupted waiting for the read lock! " + ie.getMessage());
} finally {
_urlModel.readLock().release();
}
return null;
}
public int getChildCount(HttpUrl url) {
return getFilteredChildren(url).size();
}
private void recurseTree(HttpUrl parent) {
int count = _urlModel.getChildCount(parent);
for (int i=0; i<count; i++) {
HttpUrl url = _urlModel.getChildAt(parent, i);
if (shouldFilter(url)) {
setFiltered(url, true);
} else {
grow(url);
}
recurseTree(url);
}
}
/* adds url, and marks any previously filtered intermediate nodes as implicit
* fires events for all node that becomes visible
*/
private void grow(HttpUrl url) {
HttpUrl[] path = url.getUrlHierarchy();
for (int i=0; i<path.length-1; i++) {
if (! isVisible(path[i])) {
setImplicit(path[i], true);
if (i==0) { // update the root node
_cache.remove(null);
} else {
_cache.remove(path[i-1]);
}
if (!_updating)
fireUrlAdded(path[i], -1); //FIXME
}
}
_cache.remove(url.getParentUrl());
if (!_updating)
fireUrlAdded(url, 0); // FIXME
}
/* removes url and any implicit parents. Fires events for the all urls removed
*
*/
private void prune(HttpUrl url) {
_cache.remove(url.getParentUrl());
if (!_updating)
fireUrlRemoved(url, -1); // FIXME
HttpUrl[] path = url.getUrlHierarchy();
for (int i=path.length-2; i>=0; i--) {
if (isImplicit(path[i]) && getChildCount(path[i])==0) {
setImplicit(path[i], false);
if (i==0) { // update the root node
_cache.remove(null);
} else {
_cache.remove(path[i-1]);
}
if (!_updating)
fireUrlRemoved(path[i], -1); // FIXME
}
}
}
public void reset() {
_cache.clear();
_updating = true;
updateFilteredUrls();
_updating = false;
fireUrlsChanged();
}
private class Listener implements UrlListener {
public Listener() {
}
public void urlsChanged() {
reset();
}
public void urlAdded(UrlEvent evt) {
HttpUrl url = evt.getUrl();
if (! shouldFilter(url)) {
grow(url);
} else {
setFiltered(url, true);
}
}
public void urlChanged(UrlEvent evt) {
HttpUrl url = evt.getUrl();
if (shouldFilter(url)) { // it is now filtered
if (isVisible(url)) { // we could previously see it
if (getChildCount(url)>0) { // it has children
setFiltered(url, true);
setImplicit(url, true);
if (!_updating)
fireUrlChanged(url, -1); // FIXME
} else { // it has no children, hide it and any implicit parents
setFiltered(url, true);
prune(url);
}
} // else there is nothing to do to an already invisible node
} else { // it is now not filtered
if (! isVisible(url)) { // it was previously hidden
setFiltered(url, false);
grow(url);
} else if (!_updating) {
fireUrlChanged(url, -1); // FIXME
}
}
}
public void urlRemoved(UrlEvent evt) {
HttpUrl url = evt.getUrl();
if (isVisible(url)) {
prune(url);
} else {
setFiltered(url, false);
}
}
}
}
| gpl-2.0 |
JetBrains/jdk8u_jaxws | src/share/jaxws_classes/com/sun/xml/internal/xsom/impl/parser/state/attributeDeclBody.java | 19034 | /*
* Copyright (c) 1997, 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.
*/
/* this file is generated by RelaxNGCC */
package com.sun.xml.internal.xsom.impl.parser.state;
import com.sun.xml.internal.bind.WhiteSpaceProcessor;
import com.sun.xml.internal.xsom.impl.*;
import com.sun.xml.internal.xsom.impl.parser.*;
import com.sun.xml.internal.xsom.parser.*;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
class attributeDeclBody extends NGCCHandler {
private String name;
private ForeignAttributesImpl fa;
private AnnotationImpl annotation;
private Locator locator;
private boolean isLocal;
private String defaultValue;
private UName typeName;
private String fixedValue;
protected final NGCCRuntimeEx $runtime;
private int $_ngcc_current_state;
protected String $uri;
protected String $localName;
protected String $qname;
public final NGCCRuntime getRuntime() {
return($runtime);
}
public attributeDeclBody(NGCCHandler parent, NGCCEventSource source, NGCCRuntimeEx runtime, int cookie, Locator _locator, boolean _isLocal, String _defaultValue, String _fixedValue) {
super(source, parent, cookie);
$runtime = runtime;
this.locator = _locator;
this.isLocal = _isLocal;
this.defaultValue = _defaultValue;
this.fixedValue = _fixedValue;
$_ngcc_current_state = 13;
}
public attributeDeclBody(NGCCRuntimeEx runtime, Locator _locator, boolean _isLocal, String _defaultValue, String _fixedValue) {
this(null, runtime, runtime, -1, _locator, _isLocal, _defaultValue, _fixedValue);
}
private void action0()throws SAXException {
type = new DelayedRef.SimpleType(
$runtime, locator, $runtime.currentSchema, typeName );
}
private void action1()throws SAXException {
formSpecified = true;
}
public void enterElement(String $__uri, String $__local, String $__qname, Attributes $attrs) throws SAXException {
int $ai;
$uri = $__uri;
$localName = $__local;
$qname = $__qname;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromEnterElement(makeResult(), super._cookie, $__uri, $__local, $__qname, $attrs);
}
break;
case 12:
{
if(($ai = $runtime.getAttributeIndex("","name"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
else {
unexpectedEnterElement($__qname);
}
}
break;
case 7:
{
if(($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("annotation"))) {
NGCCHandler h = new annotation(this, super._source, $runtime, 388, null,AnnotationContext.ATTRIBUTE_DECL);
spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs);
}
else {
$_ngcc_current_state = 1;
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
}
break;
case 9:
{
if((($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("annotation")) || ((($ai = $runtime.getAttributeIndex("","type"))>=0 && (($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("simpleType")) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("annotation")))) || ($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("simpleType"))))) {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs);
}
else {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs);
}
}
break;
case 13:
{
if(($ai = $runtime.getAttributeIndex("","form"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
else {
$_ngcc_current_state = 12;
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
}
break;
case 1:
{
if(($ai = $runtime.getAttributeIndex("","type"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
else {
if(($__uri.equals("http://www.w3.org/2001/XMLSchema") && $__local.equals("simpleType"))) {
NGCCHandler h = new simpleType(this, super._source, $runtime, 379);
spawnChildFromEnterElement(h, $__uri, $__local, $__qname, $attrs);
}
else {
$_ngcc_current_state = 0;
$runtime.sendEnterElement(super._cookie, $__uri, $__local, $__qname, $attrs);
}
}
}
break;
default:
{
unexpectedEnterElement($__qname);
}
break;
}
}
public void leaveElement(String $__uri, String $__local, String $__qname) throws SAXException {
int $ai;
$uri = $__uri;
$localName = $__local;
$qname = $__qname;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromLeaveElement(makeResult(), super._cookie, $__uri, $__local, $__qname);
}
break;
case 12:
{
if(($ai = $runtime.getAttributeIndex("","name"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
else {
unexpectedLeaveElement($__qname);
}
}
break;
case 7:
{
$_ngcc_current_state = 1;
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
break;
case 9:
{
if(($ai = $runtime.getAttributeIndex("","type"))>=0) {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromLeaveElement(h, $__uri, $__local, $__qname);
}
else {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromLeaveElement(h, $__uri, $__local, $__qname);
}
}
break;
case 13:
{
if(($ai = $runtime.getAttributeIndex("","form"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
else {
$_ngcc_current_state = 12;
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
}
break;
case 1:
{
if(($ai = $runtime.getAttributeIndex("","type"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
else {
$_ngcc_current_state = 0;
$runtime.sendLeaveElement(super._cookie, $__uri, $__local, $__qname);
}
}
break;
default:
{
unexpectedLeaveElement($__qname);
}
break;
}
}
public void enterAttribute(String $__uri, String $__local, String $__qname) throws SAXException {
int $ai;
$uri = $__uri;
$localName = $__local;
$qname = $__qname;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromEnterAttribute(makeResult(), super._cookie, $__uri, $__local, $__qname);
}
break;
case 12:
{
if(($__uri.equals("") && $__local.equals("name"))) {
$_ngcc_current_state = 11;
}
else {
unexpectedEnterAttribute($__qname);
}
}
break;
case 7:
{
$_ngcc_current_state = 1;
$runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname);
}
break;
case 9:
{
if(($__uri.equals("") && $__local.equals("type"))) {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromEnterAttribute(h, $__uri, $__local, $__qname);
}
else {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromEnterAttribute(h, $__uri, $__local, $__qname);
}
}
break;
case 13:
{
if(($__uri.equals("") && $__local.equals("form"))) {
$_ngcc_current_state = 15;
}
else {
$_ngcc_current_state = 12;
$runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname);
}
}
break;
case 1:
{
if(($__uri.equals("") && $__local.equals("type"))) {
$_ngcc_current_state = 5;
}
else {
$_ngcc_current_state = 0;
$runtime.sendEnterAttribute(super._cookie, $__uri, $__local, $__qname);
}
}
break;
default:
{
unexpectedEnterAttribute($__qname);
}
break;
}
}
public void leaveAttribute(String $__uri, String $__local, String $__qname) throws SAXException {
int $ai;
$uri = $__uri;
$localName = $__local;
$qname = $__qname;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromLeaveAttribute(makeResult(), super._cookie, $__uri, $__local, $__qname);
}
break;
case 14:
{
if(($__uri.equals("") && $__local.equals("form"))) {
$_ngcc_current_state = 12;
}
else {
unexpectedLeaveAttribute($__qname);
}
}
break;
case 7:
{
$_ngcc_current_state = 1;
$runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname);
}
break;
case 10:
{
if(($__uri.equals("") && $__local.equals("name"))) {
$_ngcc_current_state = 9;
}
else {
unexpectedLeaveAttribute($__qname);
}
}
break;
case 9:
{
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromLeaveAttribute(h, $__uri, $__local, $__qname);
}
break;
case 13:
{
$_ngcc_current_state = 12;
$runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname);
}
break;
case 1:
{
$_ngcc_current_state = 0;
$runtime.sendLeaveAttribute(super._cookie, $__uri, $__local, $__qname);
}
break;
case 4:
{
if(($__uri.equals("") && $__local.equals("type"))) {
$_ngcc_current_state = 0;
}
else {
unexpectedLeaveAttribute($__qname);
}
}
break;
default:
{
unexpectedLeaveAttribute($__qname);
}
break;
}
}
public void text(String $value) throws SAXException {
int $ai;
switch($_ngcc_current_state) {
case 0:
{
revertToParentFromText(makeResult(), super._cookie, $value);
}
break;
case 12:
{
if(($ai = $runtime.getAttributeIndex("","name"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendText(super._cookie, $value);
}
}
break;
case 7:
{
$_ngcc_current_state = 1;
$runtime.sendText(super._cookie, $value);
}
break;
case 9:
{
if(($ai = $runtime.getAttributeIndex("","type"))>=0) {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromText(h, $value);
}
else {
NGCCHandler h = new foreignAttributes(this, super._source, $runtime, 390, fa);
spawnChildFromText(h, $value);
}
}
break;
case 13:
{
if(($ai = $runtime.getAttributeIndex("","form"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendText(super._cookie, $value);
}
else {
$_ngcc_current_state = 12;
$runtime.sendText(super._cookie, $value);
}
}
break;
case 15:
{
if($value.equals("unqualified")) {
NGCCHandler h = new qualification(this, super._source, $runtime, 395);
spawnChildFromText(h, $value);
}
else {
if($value.equals("qualified")) {
NGCCHandler h = new qualification(this, super._source, $runtime, 395);
spawnChildFromText(h, $value);
}
}
}
break;
case 1:
{
if(($ai = $runtime.getAttributeIndex("","type"))>=0) {
$runtime.consumeAttribute($ai);
$runtime.sendText(super._cookie, $value);
}
else {
$_ngcc_current_state = 0;
$runtime.sendText(super._cookie, $value);
}
}
break;
case 11:
{
name = WhiteSpaceProcessor.collapse($value);
$_ngcc_current_state = 10;
}
break;
case 5:
{
NGCCHandler h = new qname(this, super._source, $runtime, 381);
spawnChildFromText(h, $value);
}
break;
}
}
public void onChildCompleted(Object $__result__, int $__cookie__, boolean $__needAttCheck__)throws SAXException {
switch($__cookie__) {
case 388:
{
annotation = ((AnnotationImpl)$__result__);
$_ngcc_current_state = 1;
}
break;
case 379:
{
type = ((SimpleTypeImpl)$__result__);
$_ngcc_current_state = 0;
}
break;
case 390:
{
fa = ((ForeignAttributesImpl)$__result__);
$_ngcc_current_state = 7;
}
break;
case 395:
{
form = ((Boolean)$__result__).booleanValue();
action1();
$_ngcc_current_state = 14;
}
break;
case 381:
{
typeName = ((UName)$__result__);
action0();
$_ngcc_current_state = 4;
}
break;
}
}
public boolean accepted() {
return((($_ngcc_current_state == 0) || (($_ngcc_current_state == 1) || ($_ngcc_current_state == 7))));
}
private boolean form;
private boolean formSpecified = false;
private AttributeDeclImpl makeResult() {
if(type==null)
// type defaults to anySimpleType
type = $runtime.parser.schemaSet.anySimpleType;
if(!formSpecified) form = $runtime.attributeFormDefault;
// global attributes are always qualified
if(!isLocal) form = true;
String tns;
if(form==true) tns = $runtime.currentSchema.getTargetNamespace();
else tns = "";
// proper handling of anonymous types
return new AttributeDeclImpl( $runtime.document, tns, name,
annotation, locator, fa, isLocal,
$runtime.createXmlString(defaultValue),
$runtime.createXmlString(fixedValue),
type );
}
private Ref.SimpleType type;
}
| gpl-2.0 |
SpoonLabs/astor | examples/math_50v2/src/main/java/org/apache/commons/math/genetics/AbstractListChromosome.java | 3510 | /*
* 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.genetics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Chromosome represented by an immutable list of a fixed length.
*
* @param <T> type of the representation list
* @version $Id$
* @since 2.0
*/
public abstract class AbstractListChromosome<T> extends Chromosome {
/** List representing the chromosome */
private final List<T> representation;
/**
* Constructor.
* @param representation inner representation of the chromosome
*/
public AbstractListChromosome(final List<T> representation) {
checkValidity(representation);
this.representation = Collections.unmodifiableList(new ArrayList<T> (representation));
}
/**
* Constructor.
* @param representation inner representation of the chromosome
*/
public AbstractListChromosome(final T[] representation) {
this(Arrays.asList(representation));
}
/**
*
* Asserts that <code>representation</code> can represent a valid chromosome.
* @param chromosomeRepresentation representation of the chromosome
* @throws InvalidRepresentationException iff the <code>representation</code> can not represent
* a valid chromosome
*/
protected abstract void checkValidity(List<T> chromosomeRepresentation) throws InvalidRepresentationException;
/**
* Returns the (immutable) inner representation of the chromosome.
* @return the representation of the chromosome
*/
protected List<T> getRepresentation() {
return representation;
}
/**
* Returns the length of the chromosome.
* @return the length of the chromosome
*/
public int getLength() {
return getRepresentation().size();
}
/**
* Creates a new instance of the same class as <code>this</code> is, with a
* given <code>arrayRepresentation</code>. This is needed in crossover and
* mutation operators, where we need a new instance of the same class, but
* with different array representation.
*
* Usually, this method just calls a constructor of the class.
*
* @param chromosomeRepresentation
* the inner array representation of the new chromosome.
* @return new instance extended from FixedLengthChromosome with the given
* arrayRepresentation
*/
public abstract AbstractListChromosome<T> newFixedLengthChromosome(final List<T> chromosomeRepresentation);
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format("(f=%s %s)", getFitness(), getRepresentation());
}
}
| gpl-2.0 |
unofficial-opensource-apple/gccfast | libjava/java/sql/Struct.java | 2845 | /* Struct.java -- Mapping for a SQL structured type.
Copyright (C) 1999, 2000, 2002 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.sql;
import java.util.Map;
/**
* This interface implements the standard type mapping for a SQL
* structured type.
*
* @author Aaron M. Renn (arenn@urbanophile.com)
*/
public interface Struct
{
/**
* This method returns the name of the SQL structured type for this
* object.
*
* @return The SQL structured type name.
* @exception SQLException If an error occurs.
*/
public String getSQLTypeName() throws SQLException;
/**
* This method returns the attributes of this SQL structured type.
*
* @return The attributes of this structure type.
* @exception SQLException If an error occurs.
*/
public Object[] getAttributes() throws SQLException;
/**
* This method returns the attributes of this SQL structured type.
* The specified map of type mappings overrides the default mappings.
*
* @param map The map of SQL type mappings.
* @return The attributes of this structure type.
* @exception SQLException If a error occurs.
*/
public Object[] getAttributes(Map map) throws SQLException;
}
| gpl-2.0 |
plata/POL-POM-5 | phoenicis-engines/src/main/java/org/phoenicis/engines/dto/EngineSubCategoryDTO.java | 3039 | /*
* Copyright (C) 2015-2017 PÂRIS Quentin
*
* 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 org.phoenicis.engines.dto;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.phoenicis.tools.version.Version;
import org.phoenicis.tools.version.VersionComparator;
import java.util.Comparator;
import java.util.List;
public class EngineSubCategoryDTO {
private final String name;
private final String description;
private final List<EngineVersionDTO> packages;
@JsonCreator
public EngineSubCategoryDTO(@JsonProperty("name") String name, @JsonProperty("description") String description,
@JsonProperty("packages") List<EngineVersionDTO> packages) {
this.name = name;
this.description = description;
this.packages = packages;
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public List<EngineVersionDTO> getPackages() {
return packages;
}
@Override
public String toString() {
return new ToStringBuilder(EngineSubCategoryDTO.class).append("name", name).append("description", description)
.append("packages", packages).toString();
}
public static Comparator<EngineVersionDTO> comparator() {
return (o1, o2) -> new VersionComparator().compare(new Version(o1.getVersion()), new Version(o2.getVersion()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EngineSubCategoryDTO that = (EngineSubCategoryDTO) o;
return new EqualsBuilder()
.append(name, that.name)
.append(description, that.description)
.append(packages, that.packages)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(name)
.append(description)
.append(packages)
.toHashCode();
}
}
| gpl-3.0 |
UniversityOfHawaiiORS/kc | coeus-impl/src/main/java/org/kuali/kra/coi/auth/ViewCoiDisclosureAuthorizer.java | 1578 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* 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 org.kuali.kra.coi.auth;
import org.apache.commons.lang3.StringUtils;
import org.kuali.kra.coi.CoiDisclosure;
import org.kuali.kra.infrastructure.PermissionConstants;
/**
*
* This class is to check if user has permission to view coi disclosure
*/
public class ViewCoiDisclosureAuthorizer extends CoiDisclosureAuthorizer {
@Override
public boolean isAuthorized(String userId, CoiDisclosureTask task) {
CoiDisclosure coiDisclosure = task.getCoiDisclosure();
return hasPermission(userId, coiDisclosure, PermissionConstants.VIEW_COI_DISCLOSURE)
|| hasPermission(userId, coiDisclosure, PermissionConstants.MAINTAIN_COI_DISCLOSURE)
|| StringUtils.equals(userId, coiDisclosure.getPersonId());
}
}
| agpl-3.0 |
mukadder/kc | coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/budget/core/ProposalBudgetRateAndPeriodController.java | 13755 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2016 Kuali, Inc.
*
* 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 org.kuali.coeus.propdev.impl.budget.core;
import static org.kuali.kra.infrastructure.KeyConstants.QUESTION_RECALCULATE_BUDGET_CONFIRMATION;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.kuali.coeus.common.budget.framework.core.Budget;
import org.kuali.coeus.common.budget.framework.period.AddBudgetPeriodAndTotalEvent;
import org.kuali.coeus.common.budget.framework.period.BudgetPeriod;
import org.kuali.coeus.common.budget.framework.period.GenerateBudgetPeriodEvent;
import org.kuali.coeus.common.budget.framework.period.SaveBudgetPeriodAndTotalEvent;
import org.kuali.coeus.propdev.impl.budget.ProposalDevelopmentBudgetExt;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.UifParameters;
import org.kuali.rice.krad.uif.component.BindingInfo;
import org.kuali.rice.krad.uif.util.ObjectPropertyUtils;
import org.kuali.rice.krad.util.ErrorMessage;
import org.kuali.rice.krad.web.controller.MethodAccessible;
import org.kuali.rice.krad.web.form.DialogResponse;
import org.kuali.rice.krad.web.service.impl.CollectionControllerServiceImpl.CollectionActionParameters;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = "/proposalBudget")
public class ProposalBudgetRateAndPeriodController extends ProposalBudgetControllerBase {
private static final String CONFIRM_PERIOD_CHANGES_DIALOG_ID = "PropBudget-PeriodsPage-ConfirmPeriodChangesDialog";
private static final String PERIOD_CHANGES_DIALOG_ID = "PropBudget-PeriodsPage-ChangePeriodDialog";
private static final String BUDGET_PERIOD_ERROR_PATH_PREFIX = "budget.budgetPeriods";
private static final String NEW_PERIOD_DIALOG_ID = "PropBudget-PeriodsPage-AddDialog";
@MethodAccessible
@Transactional @RequestMapping(params="methodToCall=resetToBudgetPeriodDefault")
public ModelAndView resetToBudgetPeriodDefault(@ModelAttribute("KualiForm") ProposalBudgetForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
ProposalDevelopmentBudgetExt budget = form.getBudget();
String warningMessage = getBudgetSummaryService().defaultWarningMessage(budget);
DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_PERIOD_CHANGES_DIALOG_ID);
if (StringUtils.isNotBlank(warningMessage)) {
if(dialogResponse == null) {
form.setDefaultBudgetPeriodWarningMessage(warningMessage);
return getModelAndViewService().showDialog(CONFIRM_PERIOD_CHANGES_DIALOG_ID, true, form);
}else {
boolean confirmResetDefault = dialogResponse.getResponseAsBoolean();
if(confirmResetDefault) {
getBudgetSummaryService().defaultBudgetPeriods(budget);
getBudgetSummaryService().adjustStartEndDatesForLineItems(budget);
getBudgetSummaryService().syncBudgetPersonSalaryDetails(budget);
}
}
}else {
getBudgetSummaryService().defaultBudgetPeriods(budget);
getBudgetSummaryService().syncBudgetPersonSalaryDetails(budget);
}
return getModelAndViewService().getModelAndView(form);
}
@MethodAccessible
@Transactional @RequestMapping(params="methodToCall=recalculateBudgetWithChanges")
public ModelAndView recalculateBudgetWithChanges(@ModelAttribute("KualiForm") ProposalBudgetForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
ProposalDevelopmentBudgetExt budget = form.getBudget();
getBudgetSummaryService().calculateBudget(budget);
return getModelAndViewService().getModelAndView(form);
}
@Transactional @RequestMapping(params="methodToCall=addBudgetPeriod")
public ModelAndView addBudgetPeriod(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception {
BudgetPeriod newBudgetPeriod = ((BudgetPeriod)form.getNewCollectionLines().get("budget.budgetPeriods"));
Budget budget = form.getBudget();
newBudgetPeriod.setBudget(budget);
String addLineBindingPath = getAddLineBindingPath(form);
String errorPath = addLineBindingPath + ".";
if (getKcBusinessRulesEngine().applyRules(new AddBudgetPeriodAndTotalEvent(budget, newBudgetPeriod, errorPath))) {
getBudgetSummaryService().addBudgetPeriod(budget, newBudgetPeriod);
ObjectPropertyUtils.setPropertyValue(form, addLineBindingPath, new BudgetPeriod());
}
form.setUpdateComponentId(NEW_PERIOD_DIALOG_ID);
return getModelAndViewService().getModelAndView(form);
}
protected String getAddLineBindingPath(ProposalBudgetForm form) {
final CollectionActionParameters parameters = new CollectionActionParameters(form, false);
BindingInfo addLineBindingInfo = (BindingInfo) form.getViewPostMetadata().getComponentPostData(
parameters.getSelectedCollectionId(), UifConstants.PostMetadata.ADD_LINE_BINDING_INFO);
return addLineBindingInfo.getBindingPath();
}
@Transactional @RequestMapping(params="methodToCall=saveBudgetPeriod")
public ModelAndView saveBudgetPeriod(@ModelAttribute("KualiForm") ProposalBudgetForm form) throws Exception {
Budget budget = form.getBudget();
ModelAndView modelAndView = getModelAndViewService().getModelAndView(form);
int selectedLine = Integer.parseInt(form.getActionParamaterValue(UifParameters.SELECTED_LINE_INDEX));
BudgetPeriod budgetPeriod = budget.getBudgetPeriods().get(selectedLine);
if (isBudgetPeriodDateChanged(budgetPeriod) && isOnlyLineItemDateError()) {
getGlobalVariableService().getMessageMap().clearErrorMessages();
DialogResponse dialogResponse = form.getDialogResponse(PERIOD_CHANGES_DIALOG_ID);
if(dialogResponse == null) {
return getModelAndViewService().showDialog(PERIOD_CHANGES_DIALOG_ID, true, form);
}else {
boolean confirmResetDefault = dialogResponse.getResponseAsBoolean();
if(confirmResetDefault) {
getBudgetSummaryService().adjustStartEndDatesForLineItems(budgetPeriod);
}
}
}
boolean rulePassed = getKcBusinessRulesEngine().applyRules(new SaveBudgetPeriodAndTotalEvent(budget, BUDGET_PERIOD_ERROR_PATH_PREFIX));
if(rulePassed) {
getBudgetCalculationService().calculateBudgetPeriod(budget, budgetPeriod);
modelAndView = super.saveLine(form);
}
return modelAndView;
}
@MethodAccessible
@Transactional @RequestMapping(params="methodToCall=generateAllPeriods")
public ModelAndView generateAllPeriods(@ModelAttribute("KualiForm") ProposalBudgetForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
ProposalDevelopmentBudgetExt budget = form.getBudget();
boolean rulePassed = getKcBusinessRulesEngine().applyRules(
new GenerateBudgetPeriodEvent(form.getBudget(), null));
if(rulePassed) {
DialogResponse dialogResponse = form.getDialogResponse(CONFIRM_PERIOD_CHANGES_DIALOG_ID);
Budget originalBudget = getOriginalBudget(form);
if(dialogResponse == null && isRateTypeChanged(originalBudget, budget)) {
form.setDefaultBudgetPeriodWarningMessage(getKualiConfigurationService().getPropertyValueAsString(QUESTION_RECALCULATE_BUDGET_CONFIRMATION));
return getModelAndViewService().showDialog(CONFIRM_PERIOD_CHANGES_DIALOG_ID, true, form);
}
boolean confirmRecalculate = dialogResponse !=null ? dialogResponse.getResponseAsBoolean() : true;
if(confirmRecalculate) {
getBudgetSummaryService().updateOnOffCampusFlag(budget, budget.getOnOffCampusFlag());
getBudgetSummaryService().generateAllPeriods(budget);
form.setSelectedBudget(budget);
getBudgetCalculationService().populateBudgetSummaryTotals(form.getSelectedBudget());
}
}
return getModelAndViewService().getModelAndView(form);
}
@Transactional @RequestMapping(params="methodToCall=readyGeneratePeriod")
public ModelAndView readyGeneratePeriod(@ModelAttribute("KualiForm") ProposalBudgetForm form, BindingResult result, HttpServletRequest request, HttpServletResponse response) throws Exception {
DialogResponse dialogResponse = form.getDialogResponse("PropBudget-PeriodsPage-ReadyToGeneratePeriodsDialog");
if (dialogResponse == null) {
return getModelAndViewService().showDialog("PropBudget-PeriodsPage-ReadyToGeneratePeriodsDialog",true,form);
} else if (dialogResponse.getResponseAsBoolean()) {
form.setPageId(ProposalBudgetConstants.KradConstants.SUBAWARD_PAGE_ID);
return generateAllPeriods(form,result,request,response);
}
return getModelAndViewService().getModelAndView(form);
}
@Transactional @RequestMapping(params={"methodToCall=save", "pageId=PropBudget-PeriodsPage"})
public ModelAndView save(ProposalBudgetForm form) {
ModelAndView modelAndView = getModelAndViewService().getModelAndView(form);
Budget budget = form.getBudget();
if (isBudgetPeriodDateChanged(budget) && isOnlyLineItemDateError()) {
getGlobalVariableService().getMessageMap().clearErrorMessages();
DialogResponse dialogResponse = form.getDialogResponse(PERIOD_CHANGES_DIALOG_ID);
if(dialogResponse == null) {
return getModelAndViewService().showDialog(PERIOD_CHANGES_DIALOG_ID, true, form);
}else {
boolean confirmResetDefault = dialogResponse.getResponseAsBoolean();
if(confirmResetDefault) {
getBudgetSummaryService().adjustStartEndDatesForLineItems(budget);
}
}
}
return super.save(form);
}
/**
* Method is to verify whether budget dates changed.
* @param budget
* @return
*/
private boolean isBudgetPeriodDateChanged(Budget budget) {
boolean budgetPeriodDateChanged = false;
for (BudgetPeriod budgetPeriod : budget.getBudgetPeriods()) {
budgetPeriodDateChanged = isBudgetPeriodDateChanged(budgetPeriod);
if(budgetPeriodDateChanged) {
break;
}
}
return budgetPeriodDateChanged;
}
private boolean isBudgetPeriodDateChanged(BudgetPeriod budgetPeriod) {
if (budgetPeriod.getStartDate() != null && budgetPeriod.getOldStartDate() != null &&
budgetPeriod.getEndDate() != null && budgetPeriod.getOldEndDate() != null &&
(budgetPeriod.getStartDate().compareTo(budgetPeriod.getOldStartDate()) != 0
|| budgetPeriod.getEndDate().compareTo(budgetPeriod.getOldEndDate()) != 0)) {
return true;
}
return false;
}
/**
* This method is to check the error map to see if there is any error other than line item date error.
* line item date date error should be resolved with adjustlineitem start/end date.
* This is called after rule verification and before save.
* @return
*/
private boolean isOnlyLineItemDateError() {
Map<String, List<ErrorMessage>> errors = getGlobalVariableService().getMessageMap().getErrorMessages();
List<String> lineItemDateErrors = getLineItemDateErrors();
if (!errors.isEmpty()) {
for (Map.Entry<String, List<ErrorMessage>> entry : errors.entrySet()) {
List<ErrorMessage> errorMessages = entry.getValue();
for(ErrorMessage errorMessage : errorMessages) {
if (!lineItemDateErrors.contains(errorMessage.getErrorKey())) {
return false;
}
}
}
}
return true;
}
/**
* List of line item errors specific to date that we can skip
* to adjust line item dates as per adjusted period dates
* @return
*/
private List<String> getLineItemDateErrors() {
List<String> lineItemDateErrors = new ArrayList<String>();
lineItemDateErrors.add("error.lineItem.dateDoesNotmatch");
lineItemDateErrors.add("error.line.item.start.date");
lineItemDateErrors.add("error.line.item.end.date");
return lineItemDateErrors;
}
}
| agpl-3.0 |
sanjupolus/KC6.oLatest | coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/docperm/PermissionsRule.java | 3194 | /*
* Kuali Coeus, a comprehensive research administration system for higher education.
*
* Copyright 2005-2015 Kuali, Inc.
*
* 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 org.kuali.coeus.propdev.impl.docperm;
import org.kuali.coeus.propdev.impl.core.ProposalDevelopmentDocument;
import org.kuali.rice.krad.rules.rule.BusinessRule;
import java.util.List;
/**
* Defines the Business Rule for processing Proposal Permissions.
*
* @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
*/
public interface PermissionsRule extends BusinessRule {
/**
* Determines the legality of adding a proposal user to the
* given proposal development document.
*
* @param document the proposal development document.
* @param proposalUserRolesList list of proposal user roles
* @param proposalUser the proposal user to be added to the document.
* @return true if the addition is valid; otherwise false.
*/
public boolean processAddProposalUserBusinessRules(ProposalDevelopmentDocument document,
List<ProposalUserRoles> proposalUserRolesList,
ProposalUserRoles proposalUser);
/**
* Determines the legality of deleting a proposal user from the
* given proposal development document.
*
* @param document the proposal development document.
* @param proposalUserRolesList list of proposal user roles
* @param index the index into proposalUserRolesList of the user to delete
* @return true if the addition is valid; otherwise false.
*/
public boolean processDeleteProposalUserBusinessRules(ProposalDevelopmentDocument document,
List<ProposalUserRoles> proposalUserRolesList,
int index);
/**
* Determines if it is legal to edit the roles for a user.
*
* @param document the proposal development document.
* @param proposalUserRolesList list of proposal user roles
* @param editRoles the proposal roles to edit for a user
* @return true if the addition is valid; otherwise false.
*/
public boolean processEditProposalUserRolesBusinessRules(ProposalDevelopmentDocument document,
List<ProposalUserRoles> proposalUserRolesList,
ProposalUserRoles editRoles);
}
| agpl-3.0 |
JoeCarlson/intermine | bio/sources/biogrid/test/src/org/intermine/bio/dataconversion/BioGridConverterTest.java | 2231 | package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2016 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.File;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import org.intermine.dataconversion.ItemsTestCase;
import org.intermine.dataconversion.MockItemWriter;
import org.intermine.metadata.Model;
import org.intermine.model.fulldata.Item;
public class BioGridConverterTest extends ItemsTestCase
{
Model model = Model.getInstanceByName("genomic");
BioGridConverter converter;
MockItemWriter itemWriter;
private final String currentFile = "BIOGRID-ORGANISM-Drosophila_melanogaster-3.1.76.psi25.xml";
public BioGridConverterTest(String arg) {
super(arg);
}
public void setUp() throws Exception {
super.setUp();
itemWriter = new MockItemWriter(new HashMap<String, Item>());
converter = new BioGridConverter(itemWriter, model);
converter.rslv = IdResolverService.getMockIdResolver("Gene");
converter.rslv.addResolverEntry("7227", "FBgn001", Collections.singleton("FBgn001"));
converter.rslv.addResolverEntry("7227", "FBgn002", Collections.singleton("FBgn002"));
}
public void testProcess() throws Exception {
Reader reader = new InputStreamReader(getClass().getClassLoader()
.getResourceAsStream(currentFile));
converter.setCurrentFile(new File(currentFile));
converter.setBiogridOrganisms("10116 4932 10090 7227");
System.out.println(converter.getCurrentFile());
converter.process(reader);
converter.close();
// uncomment to write out a new target items file
//writeItemsFile(itemWriter.getItems(), "biogrid-tgt-items.xml");
Set<org.intermine.xml.full.Item> expected = readItemSet("BioGridConverterTest_tgt.xml");
assertEquals(expected, itemWriter.getItems());
}
}
| lgpl-2.1 |
wesley1001/orbeon-forms | src/main/java/org/orbeon/oxf/processor/DelegationProcessor.java | 33366 | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.message.*;
import org.apache.axis.soap.SOAPConstants;
import org.dom4j.*;
import org.dom4j.Text;
import org.dom4j.io.DOMReader;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.util.XPath;
import org.orbeon.oxf.xml.XMLReceiver;
import org.orbeon.oxf.servicedirectory.ServiceDirectory;
import org.orbeon.oxf.util.*;
import org.orbeon.oxf.webapp.ProcessorService;
import org.orbeon.oxf.xml.*;
import org.orbeon.oxf.xml.dom4j.*;
import org.orbeon.saxon.dom4j.DocumentWrapper;
import org.orbeon.saxon.om.DocumentInfo;
import org.w3c.dom.Node;
import org.xml.sax.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
public class DelegationProcessor extends ProcessorImpl {
public static final String DELEGATION_NAMESPACE_URI = "http://orbeon.org/oxf/xml/delegation";
private static final String DEFAULT_SELECT_WEB_SERVICE_RPC = "/*:Envelope/*:Body/*[1]/text() | /*:Envelope/*:Body/*[1]/*";
private static final String DEFAULT_SELECT_WEB_SERVICE_DOCUMENT = "/*:Envelope/*:Body/text() | /*:Envelope/*:Body/*";
private static final String DEFAULT_SELECT_BUS = "/*:Envelope/*:Body/*";
public final String INPUT_INTERFACE = "interface";
public final String INPUT_CALL = "call";
public DelegationProcessor() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_INTERFACE, DELEGATION_NAMESPACE_URI));
addInputInfo(new ProcessorInputOutputInfo(INPUT_CALL));
addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA));
}
public ProcessorOutput createOutput(String name) {
ProcessorOutput output = new ProcessorOutputImpl(DelegationProcessor.this, name) {
public void readImpl(final PipelineContext context, final XMLReceiver xmlReceiver) {
final List<ServiceDefinition> services = readServices(readInputAsDOM4J(context, INPUT_INTERFACE));
readInputAsSAX(context, INPUT_CALL, new ForwardingXMLReceiver(xmlReceiver) {
Locator locator;
String operationName;
Integer operationTimeout;
ServiceDefinition service;
OperationDefinition operation;
SAXStore parameters;
private NamespaceContext namespaceContext = new NamespaceContext();
public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException {
namespaceContext.startElement();
if (uri.equals(DELEGATION_NAMESPACE_URI) && localname.equals("execute")) {
// Find service
service = null;
String serviceId = attributes.getValue("service");
for ( Iterator<ServiceDefinition> i = services.iterator(); i.hasNext();) {
ServiceDefinition candidateService = i.next();
if (candidateService.id.equals(serviceId)) {
service = candidateService;
break;
}
}
if (service == null)
throw new OXFException("Cannot find service with id \"" + serviceId + "\"");
operation = null;
operationName = attributes.getValue("operation");
// Find operation for Web service
if (service.type == ServiceDefinition.WEB_SERVICE_TYPE && operationName != null) {
for (Iterator<OperationDefinition> i = service.operations.iterator(); i.hasNext();) {
OperationDefinition candidateOperation = i.next();
if (candidateOperation.name.equals(operationName)) {
operation = candidateOperation;
break;
}
}
if (operation == null)
throw new ValidationException("No operation '" + operationName + "' declared", new LocationData(locator));
}
// Get timeout if any
{
final String timeoutAttribute = attributes.getValue("timeout");
if (timeoutAttribute != null) {
try {
operationTimeout = new Integer(timeoutAttribute);
} catch (NumberFormatException e) {
throw new ValidationException("Invalid timeout specified: " + timeoutAttribute, new LocationData(locator));
}
if (operationTimeout.intValue() < 0)
throw new ValidationException("Invalid timeout specified: " + operationTimeout, new LocationData(locator));
}
}
// Start building the parameters document
{
parameters = new SAXStore();
parameters.startDocument();
{
// Handle namespaces in scope as of delegation:execute element
for (Enumeration e = namespaceContext.getPrefixes(); e.hasMoreElements();) {
final String namespacePrefix = (String) e.nextElement();
if (!namespacePrefix.startsWith("xml") && !namespacePrefix.equals(""))
parameters.startPrefixMapping(namespacePrefix, namespaceContext.getURI(namespacePrefix));
}
final String defaultNS = namespaceContext.getURI("");
if (defaultNS != null && defaultNS.length() > 0)
super.startPrefixMapping("", defaultNS);
}
parameters.startElement("", "parameters", "parameters", SAXUtils.EMPTY_ATTRIBUTES);
}
} else {
// Store values if we are inside a <delegation:execute>
if (parameters == null) {
super.startElement(uri, localname, qName, attributes);
} else {
parameters.startElement(uri, localname, qName, attributes);
}
}
}
public void endElement(String uri, String localname, String qName) {
try {
if (uri.equals(DELEGATION_NAMESPACE_URI)) {
if (localname.equals("execute")) {
// Complete parameters document
{
parameters.endElement("", "parameters", "parameters");
{
// Handle namespaces in scope as of delegation:execute element
for (Enumeration e = namespaceContext.getPrefixes(); e.hasMoreElements();) {
final String namespacePrefix = (String) e.nextElement();
if (!namespacePrefix.startsWith("xml") && !namespacePrefix.equals(""))
parameters.endPrefixMapping(namespacePrefix);
}
final String defaultNS = namespaceContext.getURI("");
if (defaultNS != null && defaultNS.length() > 0)
super.endPrefixMapping("");
}
parameters.endDocument();
}
if (service.type == ServiceDefinition.WEB_SERVICE_TYPE
|| service.type == ServiceDefinition.BUS_SERVICE_TYPE) {
// Call Web service
final Service axisService = new Service();
final Call call = (Call) axisService.createCall();
if (operationTimeout != null)
call.setTimeout(operationTimeout);
// Get document containing the parameters
final org.w3c.dom.Element parametersElement = getParametersDomDocument().getDocumentElement();
// Populate envelope
final SOAPEnvelope requestEnvelope =
service.soapVersion != null && service.soapVersion.equals("1.2")
? new SOAPEnvelope(SOAPConstants.SOAP12_CONSTANTS)
: new SOAPEnvelope();
if (service.type == ServiceDefinition.BUS_SERVICE_TYPE || "document".equals(service.style)) {
// Add elements to directly to body
for (int i = 0; i < parametersElement.getChildNodes().getLength(); i++) {
final Node child = parametersElement.getChildNodes().item(i);
if (child instanceof org.w3c.dom.Element)
requestEnvelope.addBodyElement(new SOAPBodyElement((org.w3c.dom.Element) child));
}
} else {
// Create body element with operation name, and add elements as children
final SOAPBodyElement requestBody = new SOAPBodyElement(new PrefixedQName(operation.nsuri, operation.name, "m"));
for (int i = 0; i < parametersElement.getChildNodes().getLength(); i++) {
final Node child = parametersElement.getChildNodes().item(i);
if (child instanceof org.w3c.dom.Element) {
requestBody.addChild(new MessageElement((org.w3c.dom.Element) child));
} else if (child instanceof org.w3c.dom.Text) {
requestBody.addTextNode(child.toString());
} else {
throw new OXFException("Unsupported node type: " + child.getClass().getName());
}
}
requestEnvelope.addBodyElement(requestBody);
}
// Call service
SOAPEnvelope resultEnvelope = null;
if (service.type == ServiceDefinition.WEB_SERVICE_TYPE) {
// Call Web service
call.setTargetEndpointAddress(new URL(service.endpoint));
if (operation != null && operation.soapAction != null) {
call.setUseSOAPAction(true);
call.setSOAPActionURI(operation.soapAction);
}
call.setReturnClass(javax.xml.soap.SOAPMessage.class);
resultEnvelope = call.invoke(requestEnvelope);
} else {
// Call bus service
javax.jms.QueueConnection requestQueueConnection = null;
javax.jms.QueueSession requestQueueSession = null;
javax.jms.QueueSender queueSender = null;
try {
requestQueueConnection = JMSUtils.getQueueConnection();
requestQueueSession = requestQueueConnection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
queueSender = requestQueueSession.createSender
((javax.jms.Queue) new InitialContext().lookup(JMSUtils.JNDI_SERVICE_PREFIX + service.name));
javax.jms.ObjectMessage responseMessage = requestQueueSession.createObjectMessage();
responseMessage.setObject(requestEnvelope);
// Send message
if (ServiceDirectory.instance().getServiceByName(service.name).hasOutputs()) {
// Response expected
javax.jms.QueueConnection responseQueueConnection = null;
javax.jms.QueueSession responseQueueSession = null;
javax.jms.QueueReceiver queueReceiver = null;
try {
responseQueueConnection = JMSUtils.getQueueConnection();
responseQueueSession = responseQueueConnection.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue temporaryQueue = responseQueueSession.createTemporaryQueue();
queueReceiver = responseQueueSession.createReceiver(temporaryQueue);
responseMessage.setJMSReplyTo(temporaryQueue);
responseQueueConnection.start();
queueSender.send(responseMessage);
javax.jms.Message message = queueReceiver.receive();
resultEnvelope = (SOAPEnvelope) ((javax.jms.ObjectMessage) message).getObject();
} finally{
if (queueReceiver != null) queueReceiver.close();
if (responseQueueSession != null) responseQueueSession.close();
if (responseQueueConnection != null) responseQueueConnection.close();
}
} else {
// No response expected
queueSender.send(responseMessage);
}
} finally {
if (queueSender != null) queueSender.close();
if (requestQueueSession != null) requestQueueSession.close();
if (requestQueueConnection != null) requestQueueConnection.close();
}
}
// Handle result
if (resultEnvelope != null) {
// Throw exception if a fault is returned and the user does not want the fault to be returned
if (resultEnvelope.getBody().getFault() != null && !service.returnFault) {
throw new OXFException("SOAP Fault. Request:\n"
+ TransformerUtils.domToString(requestEnvelope.getAsDocument())
+ "\n\nResponse:\n"
+ TransformerUtils.domToString(resultEnvelope.getAsDocument()));
}
// Send body from result envelope
final LocationSAXWriter locationSAXWriter = new LocationSAXWriter();
locationSAXWriter.setContentHandler(xmlReceiver);
final DocumentFactory factory = NonLazyUserDataDocumentFactory.getInstance();
final Document resultEnvelopeDOM4j = new DOMReader(factory).read(resultEnvelope.getAsDocument());
final String xpathString =
operation != null && operation.select != null
? operation.select
: service.type == ServiceDefinition.WEB_SERVICE_TYPE
? ("document".equals(service.style) ? DEFAULT_SELECT_WEB_SERVICE_DOCUMENT : DEFAULT_SELECT_WEB_SERVICE_RPC)
: DEFAULT_SELECT_BUS;
final DocumentInfo documentInfo = new DocumentWrapper(resultEnvelopeDOM4j, null, XPath.GlobalConfiguration());
final PooledXPathExpression expr = XPathCache.getXPathExpression(
documentInfo.getConfiguration(), documentInfo, xpathString,
operation != null && operation.select != null
? operation.selectNamespaceContext : null, getLocationData());
for (Iterator i = expr.evaluateToJavaReturnToPool().iterator(); i.hasNext();) {
// Create document with node from SOAP envelope
final Object result = i.next();
if (result instanceof Element) {
locationSAXWriter.write((Element) result);
} else if (result instanceof Document) {
locationSAXWriter.write(((Document) result).getRootElement());
} else if (result instanceof Text) {
locationSAXWriter.write((Text) result);
} else {
throw new OXFException("Unsupported result from select expression: '" + result.getClass() + "'");
}
}
}
} else if (service.type == ServiceDefinition.STATELESS_EJB_TYPE
|| service.type == ServiceDefinition.JAVABEAN_TYPE) {
// Get document containing the parameters
final Document parametersDocument = getParametersDocument();
// Get parameter values and types
final List<Class> parameterTypes = new ArrayList<Class>();
final List<Serializable> parameterValues = new ArrayList<Serializable>();
// Go through elements
for (Iterator i = XPathUtils.selectIterator(parametersDocument, "/*/*"); i.hasNext();) {
final org.dom4j.Element parameterElement = (org.dom4j.Element) i.next();
final String parameterValue = parameterElement.getText();
// TODO: should pass true?
final QName type = Dom4jUtils.extractAttributeValueQName(parameterElement, XMLConstants.XSI_TYPE_QNAME, false);
if (type == null || XMLConstants.XS_STRING_QNAME.equals(type)) {
parameterTypes.add(String.class);
parameterValues.add(parameterValue);
} else if (XMLConstants.XS_DOUBLE_QNAME.equals(type)) {
parameterTypes.add(Double.TYPE);
parameterValues.add(new Double(parameterValue));
} else if (XMLConstants.XS_BOOLEAN_QNAME.equals(type)) {
parameterTypes.add(Boolean.TYPE);
parameterValues.add(new Boolean(parameterValue));
} else if (XMLConstants.XS_INTEGER_QNAME.equals(type)) {
parameterTypes.add(Integer.TYPE);
parameterValues.add(new Integer(parameterValue));
}
}
if (service.type == ServiceDefinition.STATELESS_EJB_TYPE) {
// Call EJB method
final Context jndiContext = (Context) context.getAttribute(ProcessorService.JNDIContext());
if (jndiContext == null)
throw new ValidationException("JNDI context not found in pipeline context.", new LocationData(locator));
final Object home = jndiContext.lookup(service.jndiName);
if (home == null)
throw new ValidationException("Home interface not found in JNDI context: " + service.jndiName, new LocationData(locator));
final Method create = home.getClass().getDeclaredMethod("create", new Class[]{});
final Object instance = create.invoke(home);
final String result = callMethod(instance.getClass(), operationName, parameterTypes, instance, parameterValues);
super.characters(result.toCharArray(), 0, result.length());
} else if (service.type == ServiceDefinition.JAVABEAN_TYPE) {
// Call JavaBean method
final Class clazz = Class.forName(service.clazz);
final Object instance = clazz.newInstance();
final String result = callMethod(clazz, operationName, parameterTypes, instance, parameterValues);
super.characters(result.toCharArray(), 0, result.length());
}
}
}
} else {
// Store values if we are inside a <delegation:execute>
if (parameters == null) {
super.endElement(uri, localname, qName);
} else {
parameters.endElement(uri, localname, qName);
}
}
} catch (Exception e) {
throw new OXFException(e);
}
namespaceContext.endElement();
}
public void characters(char[] chars, int start, int length) throws SAXException {
// Store values if we are inside a <delegation:execute>
if (parameters == null) {
super.characters(chars, start, length);
} else {
parameters.characters(chars, start, length);
}
}
public void startPrefixMapping(String prefix, String uri) throws SAXException {
namespaceContext.startPrefixMapping(prefix, uri);
if (parameters == null) {
super.startPrefixMapping(prefix, uri);
} else {
parameters.startPrefixMapping(prefix, uri);
}
}
public void endPrefixMapping(String s) throws SAXException {
if (parameters == null) {
super.endPrefixMapping(s);
} else {
parameters.endPrefixMapping(s);
}
}
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
private Document getParametersDocument() throws SAXException {
// Create Document
final Document result = TransformerUtils.saxStoreToDom4jDocument(parameters);
parameters = null;
return result;
}
private org.w3c.dom.Document getParametersDomDocument() throws SAXException {
// Create DOM document
final org.w3c.dom.Document result = TransformerUtils.saxStoreToDomDocument(parameters);
parameters = null;
return result;
}
});
};
};
addOutput(name, output);
return output;
}
/**
* Calls a method on an object with the reflexion API.
*/
private String callMethod(Class clazz, String methodName, List<Class> parameterTypes,
Object instance, List<Serializable> parameterValues)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
String result;
Class[] parameterClasses = new Class[parameterTypes.size()];
parameterTypes.toArray(parameterClasses);
Method method = clazz.getDeclaredMethod(methodName, parameterClasses);
result = method.invoke(instance, parameterValues.toArray()).toString();
return result;
}
/**
* Returns a list of AbstractService objects.
*/
private List<ServiceDefinition> readServices(Document interfaceDocument) {
List<ServiceDefinition> services = new java.util.ArrayList<ServiceDefinition>();
for (java.util.Iterator i = interfaceDocument.getRootElement().elements("service").iterator(); i.hasNext();) {
Element serviceElement = (Element) i.next();
// Create Service Definition
ServiceDefinition service = new ServiceDefinition();
services.add(service);
String serviceType = serviceElement.attributeValue("type");
service.type =
"webservice".equals(serviceType) ? ServiceDefinition.WEB_SERVICE_TYPE :
"stateless-ejb".equals(serviceType) ? ServiceDefinition.STATELESS_EJB_TYPE :
"javabean".equals(serviceType) ? ServiceDefinition.JAVABEAN_TYPE :
"bus".equals(serviceType) ? ServiceDefinition.BUS_SERVICE_TYPE:
-1;
service.id = serviceElement.attributeValue("id");
service.endpoint = serviceElement.attributeValue("endpoint");
service.jndiName = serviceElement.attributeValue("uri");
service.name = serviceElement.attributeValue("name");
service.clazz = serviceElement.attributeValue("class");
service.style = serviceElement.attributeValue("style");
service.soapVersion = serviceElement.attributeValue("soap-version");
service.returnFault = "true".equals(serviceElement.attributeValue("return-fault"));
// Create operations
for (java.util.Iterator j = XPathUtils.selectIterator(serviceElement, "operation"); j.hasNext();) {
Element operationElement = (Element) j.next();
OperationDefinition operation = new OperationDefinition();
operation.service = service;
service.operations.add(operation);
operation.name = operationElement.attributeValue("name");
operation.nsuri = operationElement.attributeValue("nsuri");
operation.soapAction = operationElement.attributeValue("soap-action");
operation.encodingStyle = operationElement.attributeValue("encodingStyle");
String select = operationElement.attributeValue("select");
if (select != null) {
operation.select = select;
operation.selectNamespaceContext = new NamespaceMapping(Dom4jUtils.getNamespaceContextNoDefault(operationElement));
}
}
}
return services;
}
private static class ServiceDefinition {
public final static int WEB_SERVICE_TYPE = 1;
public final static int STATELESS_EJB_TYPE = 2;
public final static int JAVABEAN_TYPE = 3;
public final static int BUS_SERVICE_TYPE = 4;
public int type;
public String id;
public String endpoint;
public String jndiName;
public String name;
public String clazz;
public String style;
public String soapVersion;
public boolean returnFault;
public List<OperationDefinition> operations = new java.util.ArrayList<OperationDefinition>();
}
private static class OperationDefinition {
public ServiceDefinition service;
public String name;
public String nsuri;
public String soapAction;
public String encodingStyle;
public String select;
public NamespaceMapping selectNamespaceContext;
}
}
| lgpl-2.1 |
paiyetan/glycoworkbench | src/org/eurocarbdb/application/glycoworkbench/Base64.java | 26516 | /*
* EuroCarbDB, a framework for carbohydrate bioinformatics
*
* Copyright (c) 2006-2009, Eurocarb project, or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
* A copy of this license accompanies this distribution in the file LICENSE.txt.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* Last commit: $Rev$ by $Author$ on $Date:: $
*/
package org.eurocarbdb.application.glycoworkbench;
import java.util.Arrays;
/** A very fast and memory efficient class to encode and decode to and from BASE64 in full accordance
* with RFC 2045.<br><br>
* On Windows XP sp1 with 1.4.2_04 and later ;), this encoder and decoder is about 10 times faster
* on small arrays (10 - 1000 bytes) and 2-3 times as fast on larger arrays (10000 - 1000000 bytes)
* compared to <code>sun.misc.Encoder()/Decoder()</code>.<br><br>
*
* On byte arrays the encoder is about 20% faster than Jakarta Commons Base64 Codec for encode and
* about 50% faster for decoding large arrays. This implementation is about twice as fast on very small
* arrays (< 30 bytes). If source/destination is a <code>String</code> this
* version is about three times as fast due to the fact that the Commons Codec result has to be recoded
* to a <code>String</code> from <code>byte[]</code>, which is very expensive.<br><br>
*
* This encode/decode algorithm doesn't create any temporary arrays as many other codecs do, it only
* allocates the resulting array. This produces less garbage and it is possible to handle arrays twice
* as large as algorithms that create a temporary array. (E.g. Jakarta Commons Codec). It is unknown
* whether Sun's <code>sun.misc.Encoder()/Decoder()</code> produce temporary arrays but since performance
* is quite low it probably does.<br><br>
*
* The encoder produces the same output as the Sun one except that the Sun's encoder appends
* a trailing line separator if the last character isn't a pad. Unclear why but it only adds to the
* length and is probably a side effect. Both are in conformance with RFC 2045 though.<br>
* Commons codec seem to always att a trailing line separator.<br><br>
*
* <b>Note!</b>
* The encode/decode method pairs (types) come in three versions with the <b>exact</b> same algorithm and
* thus a lot of code redundancy. This is to not create any temporary arrays for transcoding to/from different
* format types. The methods not used can simply be commented out.<br><br>
*
* There is also a "fast" version of all decode methods that works the same way as the normal ones, but
* har a few demands on the decoded input. Normally though, these fast verions should be used if the source if
* the input is known and it hasn't bee tampered with.<br><br>
*
* If you find the code useful or you find a bug, please send me a note at base64 @ miginfocom . com.
*
* Licence (BSD):
* ==============
*
* Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (base64 @ miginfocom . com)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* Neither the name of the MiG InfoCom AB nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* @version 2.2
* @author Mikael Grev
* Date: 2004-aug-02
* Time: 11:31:11
*/
public class Base64
{
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
// ****************************************************************************************
// * char[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>char[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static char[] encodeToChar(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(char[] sArr)
{
return decode(sArr,0,sArr.length);
}
public final static byte[] decode(char[] sArr, int start, int length) // Check special case
{
int sLen = sArr != null ? length : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[start+i]] < 0)
sepCnt++;
System.out.println(sLen + " " + sepCnt);
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[start+(--i)]] <= 0;)
if (sArr[start+i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[start+(s++)]];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * byte[] version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep)
{
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen;) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/** Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i] & 0xff] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0;)
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++] & 0xff];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(byte[] sArr)
{
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
// ****************************************************************************************
// * String version
// ****************************************************************************************
/** Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static String encodeToString(byte[] sArr, boolean lineSep)
{
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
/** Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
* and without line separators.<br>
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
* @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(String str)
{
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
// Count '=' at end
int pad = 0;
for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0;)
if (str.charAt(i) == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len;) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[str.charAt(s++)];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++]= (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/** Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
* fast as {@link #decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
* @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String s)
{
// Check special case
int sLen = s.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[s.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
} | lgpl-3.0 |
Tybion/community-edition | projects/web-client/source/java/org/alfresco/web/bean/ml/MultilingualUtils.java | 5407 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.web.bean.ml;
import java.io.Serializable;
import java.util.Locale;
import java.util.Map;
import javax.faces.context.FacesContext;
import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.ml.MultilingualContentService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.web.app.servlet.FacesHelper;
import org.alfresco.web.bean.repository.Node;
/**
* Util class for the management of multilingual documents on the web client side
*
* @author yanipig
*/
public class MultilingualUtils implements Serializable
{
private static final long serialVersionUID = 2218309432064312000L;
/**
* Returns true if the current user has enough right to add a content to the space
* where the pivot translation is located in.
*
* @param multlingualDocument Node
* @param fc FacesContext
* @return boolean
*/
public static boolean canAddChildrenToPivotSpace(Node multlingualDocument, FacesContext fc)
{
MultilingualContentService mlservice = getMultilingualContentService(fc);
NodeService nodeService = getNodeService(fc);
// get the pivot translation and get the space where it's located
NodeRef pivot = mlservice.getPivotTranslation(multlingualDocument.getNodeRef());
NodeRef space = nodeService.getPrimaryParent(pivot).getParentRef();
// return if the current user can add a content to the space of the pivot
return new Node(space).hasPermission(PermissionService.ADD_CHILDREN);
}
/**
* Returns true if the current user can delete each translation of the mlContainer of the given node
*
* @param multlingualDocument Node
* @param fc FacesContext
* @return boolean
*/
public static boolean canDeleteEachTranslation(Node multlingualDocument, FacesContext fc)
{
boolean can = true;
MultilingualContentService mlservice = getMultilingualContentService(fc);
Map<Locale, NodeRef> translations = mlservice.getTranslations(multlingualDocument.getNodeRef());
for (Map.Entry<Locale, NodeRef> entry : translations.entrySet())
{
Node translation = new Node(entry.getValue());
if(translation.hasPermission(PermissionService.DELETE_NODE) == false
|| translation.isLocked() == true
|| translation.hasAspect(ContentModel.ASPECT_WORKING_COPY) == true
)
{
can = false;
break;
}
}
return can;
}
/**
* Returns true if the current user can move each translation of the mlContainer of the given node
*
* @param multlingualDocument Node
* @param fc FacesContext
* @return boolean
*/
public static boolean canMoveEachTranslation(Node multlingualDocument, FacesContext fc)
{
boolean can = true;
MultilingualContentService mlservice = getMultilingualContentService(fc);
Map<Locale, NodeRef> translations = mlservice.getTranslations(multlingualDocument.getNodeRef());
for (Map.Entry<Locale, NodeRef> entry : translations.entrySet())
{
Node translation = new Node(entry.getValue());
if(translation.hasPermission(PermissionService.DELETE_NODE) == false)
{
can = false;
break;
}
}
return can;
}
/**
* Returns true if the current user can delete each translation and create
* * a new content in the space
*
* @param multlingualDocument Node
* @param fc FacesContext
* @return boolean
*/
public static boolean canStartNewEditon(Node multlingualDocument, FacesContext fc)
{
boolean canDelete = MultilingualUtils.canMoveEachTranslation(multlingualDocument, fc);
boolean canCreate = MultilingualUtils.canAddChildrenToPivotSpace(multlingualDocument, fc);
return canDelete && canCreate;
}
private static MultilingualContentService getMultilingualContentService(FacesContext fc)
{
return (MultilingualContentService) FacesHelper.getManagedBean(fc, "MultilingualContentService");
}
private static NodeService getNodeService(FacesContext fc)
{
return (NodeService) FacesHelper.getManagedBean(fc, "NodeService");
}
}
| lgpl-3.0 |
tectronics/phantomuserland | tools/plc/src/ru/dz/plc/compiler/PhantomVariable.java | 678 | package ru.dz.plc.compiler;
/**
* <p>Title: ru.dz.plc.compiler</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author dz
* @version 1.0
*/
public class PhantomVariable
{
String name;
PhantomType type;
public PhantomVariable( PhantomVariable v )
{
this.name = v.name;
this.type = v.type;
}
public PhantomVariable( String name, PhantomType type)
{
this.name = name;
this.type = type;
}
public String getName() { return name; }
public PhantomType getType() { return type; }
public void setType(PhantomType type) {
this.type = type;
}
};
| lgpl-3.0 |
universsky/diddler | src/org/jnetpcap/packet/PcapPacketHandler.java | 1210 | /*
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Sly Technologies, Inc.
*
* This file is part of jNetPcap.
*
* jNetPcap is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jnetpcap.packet;
// TODO: Auto-generated Javadoc
/**
* The Interface PcapPacketHandler.
*
* @param <T>
* the generic type
* @author Mark Bednarczyk
* @author Sly Technologies, Inc.
*/
public interface PcapPacketHandler<T> {
/**
* Next packet.
*
* @param packet
* the packet
* @param user
* the user
*/
public void nextPacket(PcapPacket packet, T user);
}
| lgpl-3.0 |
marcelohd/retrolambda | retrolambda/src/main/java/net/orfjackal/retrolambda/util/Bytecode.java | 2117 | // Copyright © 2013-2015 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package net.orfjackal.retrolambda.util;
import net.orfjackal.retrolambda.lambdas.Handles;
import org.objectweb.asm.*;
import static org.objectweb.asm.Opcodes.*;
public class Bytecode {
public static void generateDelegateMethod(ClassVisitor cv, int access, Handle method, Handle target) {
MethodVisitor mv = cv.visitMethod(access, method.getName(), method.getDesc(), null, null);
mv.visitCode();
// if the target method is constructor, then we must NEW up the instance inside the delegate method
if (target.getTag() == H_NEWINVOKESPECIAL) {
mv.visitTypeInsn(NEW, target.getOwner());
mv.visitInsn(DUP);
}
// we assume one of the methods to be static and the other virtual, i.e. it has an implicit 'this' argument
Type[] args = longest(
Type.getArgumentTypes(method.getDesc()),
Type.getArgumentTypes(target.getDesc()));
int varIndex = 0;
for (Type arg : args) {
mv.visitVarInsn(arg.getOpcode(ILOAD), varIndex);
varIndex += arg.getSize();
}
mv.visitMethodInsn(Handles.getOpcode(target), target.getOwner(), target.getName(), target.getDesc(), target.getTag() == H_INVOKEINTERFACE);
mv.visitInsn(Type.getReturnType(method.getDesc()).getOpcode(IRETURN));
mv.visitMaxs(-1, -1); // rely on ClassWriter.COMPUTE_MAXS
mv.visitEnd();
}
private static Type[] longest(Type[] t1, Type[] t2) {
return t1.length > t2.length ? t1 : t2;
}
public static String prependArgumentType(String desc, Type type) {
Type returnType = Type.getReturnType(desc);
Type[] args = Type.getArgumentTypes(desc);
Type[] newArgs = new Type[args.length + 1];
newArgs[0] = type;
System.arraycopy(args, 0, newArgs, 1, args.length);
return Type.getMethodDescriptor(returnType, newArgs);
}
}
| apache-2.0 |
josegom/training | kerby/kerby-download/kerby-all-1.0.0-RC1/kerby-kerb/kerb-core/src/main/java/org/apache/kerby/kerberos/kerb/spec/pa/pkinit/ExternalPrincipalIdentifier.java | 2641 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.spec.pa.pkinit;
import org.apache.kerby.asn1.type.Asn1FieldInfo;
import org.apache.kerby.asn1.type.Asn1OctetString;
import org.apache.kerby.kerberos.kerb.spec.KrbSequenceType;
/**
ExternalPrincipalIdentifier ::= SEQUENCE {
subjectName [0] IMPLICIT OCTET STRING OPTIONAL,
issuerAndSerialNumber [1] IMPLICIT OCTET STRING OPTIONAL,
subjectKeyIdentifier [2] IMPLICIT OCTET STRING OPTIONAL
}
*/
public class ExternalPrincipalIdentifier extends KrbSequenceType {
private static final int SUBJECT_NAME = 0;
private static final int ISSUER_AND_SERIAL_NUMBER = 1;
private static final int SUBJECT_KEY_IDENTIFIER = 2;
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(SUBJECT_NAME, Asn1OctetString.class, true),
new Asn1FieldInfo(ISSUER_AND_SERIAL_NUMBER, Asn1OctetString.class, true),
new Asn1FieldInfo(SUBJECT_KEY_IDENTIFIER, Asn1OctetString.class, true)
};
public ExternalPrincipalIdentifier() {
super(fieldInfos);
}
public byte[] getSubjectName() {
return getFieldAsOctets(SUBJECT_NAME);
}
public void setSubjectName(byte[] subjectName) {
setFieldAsOctets(SUBJECT_NAME, subjectName);
}
public byte[] getIssuerSerialNumber() {
return getFieldAsOctets(ISSUER_AND_SERIAL_NUMBER);
}
public void setIssuerSerialNumber(byte[] issuerSerialNumber) {
setFieldAsOctets(ISSUER_AND_SERIAL_NUMBER, issuerSerialNumber);
}
public byte[] getSubjectKeyIdentifier() {
return getFieldAsOctets(SUBJECT_KEY_IDENTIFIER);
}
public void setSubjectKeyIdentifier(byte[] subjectKeyIdentifier) {
setFieldAsOctets(SUBJECT_KEY_IDENTIFIER, subjectKeyIdentifier);
}
}
| apache-2.0 |
treasure-data/presto | presto-main/src/main/java/io/prestosql/block/BlockJsonSerde.java | 3249 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.block;
import com.fasterxml.jackson.core.Base64Variants;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.airlift.slice.Slices;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.block.BlockEncodingSerde;
import javax.inject.Inject;
import java.io.IOException;
import static io.prestosql.block.BlockSerdeUtil.readBlock;
import static io.prestosql.block.BlockSerdeUtil.writeBlock;
import static java.lang.Math.toIntExact;
import static java.util.Objects.requireNonNull;
public final class BlockJsonSerde
{
private BlockJsonSerde() {}
public static class Serializer
extends JsonSerializer<Block>
{
private final BlockEncodingSerde blockEncodingSerde;
@Inject
public Serializer(BlockEncodingSerde blockEncodingSerde)
{
this.blockEncodingSerde = requireNonNull(blockEncodingSerde, "blockEncodingSerde is null");
}
@Override
public void serialize(Block block, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException
{
// Encoding name is length prefixed as are many block encodings
SliceOutput output = new DynamicSliceOutput(toIntExact(block.getSizeInBytes() + block.getEncodingName().length() + (2 * Integer.BYTES)));
writeBlock(blockEncodingSerde, output, block);
Slice slice = output.slice();
jsonGenerator.writeBinary(Base64Variants.MIME_NO_LINEFEEDS, slice.byteArray(), slice.byteArrayOffset(), slice.length());
}
}
public static class Deserializer
extends JsonDeserializer<Block>
{
private final BlockEncodingSerde blockEncodingSerde;
@Inject
public Deserializer(BlockEncodingSerde blockEncodingSerde)
{
this.blockEncodingSerde = requireNonNull(blockEncodingSerde, "blockEncodingSerde is null");
}
@Override
public Block deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException
{
byte[] decoded = jsonParser.getBinaryValue(Base64Variants.MIME_NO_LINEFEEDS);
return readBlock(blockEncodingSerde, Slices.wrappedBuffer(decoded));
}
}
}
| apache-2.0 |
camunda/camunda-engine-dmn | feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelEngineTest.java | 16536 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; 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.camunda.bpm.dmn.feel.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineFactoryImpl;
import org.camunda.bpm.dmn.feel.impl.juel.el.FeelFunctionMapper;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.value.DateValue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class FeelEngineTest {
public static final String INPUT_VARIABLE = "input";
public static FeelEngine feelEngine;
public VariableMap variables;
@BeforeClass
public static void initFeelEngine() {
feelEngine = new FeelEngineFactoryImpl().createInstance();
}
@Before
public void initVariables() {
variables = Variables.createVariables();
}
@Test
public void testLong() {
variables.putValue("integer", 12);
variables.putValue("primitive", 12L);
variables.putValue("typed", Variables.longValue(12L));
assertEvaluatesToTrue(Variables.longValue(12L), "<= typed");
assertEvaluatesToTrue(Variables.longValue(12L), "<= primitive");
assertEvaluatesToTrue(Variables.longValue(12L), "<= integer");
}
@Test
public void testEndpointString() {
assertEvaluatesToTrue("Hello World", "\"Hello World\"");
assertEvaluatesToFalse("Hello World", "\"Hello Camunda\"");
assertEvaluatesToFalse("Hello World", "\"\"");
assertEvaluatesToTrue("", "\"\"");
assertEvaluatesToTrue("123", "\"123\"");
assertEvaluatesToTrue("Why.not?", "\"Why.not?\"");
}
@Test
public void testEndpointVariable() {
variables.put("y", "a");
assertEvaluatesToTrue("a", "y");
assertEvaluatesToFalse("b", "y");
variables.put("customer", Collections.singletonMap("name", "camunda"));
assertEvaluatesToTrue("camunda", "customer.name");
assertEvaluatesToFalse("hello", "customer.name");
}
@Test
public void testEndpointVariableGreater() {
variables.put("y", 13.37);
assertEvaluatesToTrue(12, "<y");
assertEvaluatesToFalse(13.38, "<y");
}
@Test
public void testEndpointVariableGreaterEqual() {
variables.put("y", 13.37);
assertEvaluatesToTrue(12, "<=y");
assertEvaluatesToTrue(13.37, "<=y");
assertEvaluatesToFalse(13.38, "<=y");
}
@Test
public void testEndpointVariableLess() {
variables.put("y", 13.37);
assertEvaluatesToFalse(12, ">y");
assertEvaluatesToTrue(13.38, ">y");
}
@Test
public void testEndpointVariableLessEqual() {
variables.put("y", 13.37);
assertEvaluatesToFalse(12, ">=y");
assertEvaluatesToTrue(13.37, ">=y");
assertEvaluatesToTrue(13.38, ">=y");
}
@Test
public void testEndpointBoolean() {
assertEvaluatesToTrue(true, "true");
assertEvaluatesToFalse(true, "false");
assertEvaluatesToTrue(false, "false");
assertEvaluatesToFalse(false, "true");
}
@Test
public void testEndpointNumber() {
assertEvaluatesToTrue(13, "13");
assertEvaluatesToTrue(13.37, "13.37");
assertEvaluatesToTrue(0.37, ".37");
assertEvaluatesToFalse(13.37, "23.42");
assertEvaluatesToFalse(0.42, ".37");
}
@Test
public void testEndpointNumberGreater() {
assertEvaluatesToTrue(12, "<13");
assertEvaluatesToTrue(13.35, "<13.37");
assertEvaluatesToTrue(0.337, "<.37");
assertEvaluatesToFalse(13.37, "<13.37");
assertEvaluatesToFalse(0.37, "<.37");
}
@Test
public void testEndpointNumberGreaterEqual() {
assertEvaluatesToTrue(13.37, "<=13.37");
assertEvaluatesToTrue(13.337, "<=13.37");
assertEvaluatesToTrue(0.37, "<=.37");
assertEvaluatesToTrue(0.337, "<=.37");
assertEvaluatesToFalse(13.42, "<=13.37");
assertEvaluatesToFalse(0.42, "<=.37");
}
@Test
public void testEndpointNumberLess() {
assertEvaluatesToTrue(13.37, ">13");
assertEvaluatesToTrue(13.42, ">13.37");
assertEvaluatesToTrue(0.42, ">.37");
assertEvaluatesToFalse(13.37, ">13.37");
assertEvaluatesToFalse(0.37, ">.37");
}
@Test
public void testEndpointNumberLessEqual() {
assertEvaluatesToTrue(13.37, ">=13");
assertEvaluatesToTrue(13.37, ">=13.37");
assertEvaluatesToTrue(0.37, ">=.37");
assertEvaluatesToTrue(0.42, ">=.37");
assertEvaluatesToFalse(13.337, ">=13.37");
assertEvaluatesToFalse(0.23, ">=.37");
}
@Test
public void testEndpointDateAndTime() {
DateValue dateTime = parseDateAndTime("2015-12-12T22:12:53");
assertEvaluatesToTrue(dateTime, "date and time(\"2015-12-12T22:12:53\")");
variables.put("y", "2015-12-12T22:12:53");
assertEvaluatesToTrue(dateTime, "date and time(y)");
}
@Test
public void testThreadSafetyDateAndTimeParsing() throws ExecutionException, InterruptedException {
int threadCount = 2;
ExecutorService pool = Executors.newFixedThreadPool(threadCount);
Set<Future<Date>> futureSet = new HashSet<Future<Date>>();
Set<Date> expectedDates = new HashSet<Date>();
for(int i = 1; i <= 3 * threadCount; i++) {
final String dateAndTimeString = "2015-12-12T22:12:5" + i;
expectedDates.add(
FeelFunctionMapper.parseDateAndTime(dateAndTimeString)
);
futureSet.add(pool.submit(new Callable<Date>() {
public Date call() throws Exception {
return FeelFunctionMapper.parseDateAndTime(dateAndTimeString);
}
}));
}
pool.shutdown();
Set<Date> actualDates = new HashSet<Date>();
for( Future<Date> dateFuture : futureSet ) {
actualDates.add(dateFuture.get());
}
assertThat(actualDates).hasSameElementsAs(expectedDates);
}
@Test
public void testIntervalNumber() {
assertEvaluatesToTrue(0.23, "[.12...37]");
assertEvaluatesToTrue(0.23, "[.12...37)");
assertEvaluatesToTrue(0.23, "[.12...37[");
assertEvaluatesToTrue(0.23, "(.12...37]");
assertEvaluatesToTrue(0.23, "(.12...37)");
assertEvaluatesToTrue(0.23, "(.12...37[");
assertEvaluatesToTrue(0.23, "].12...37]");
assertEvaluatesToTrue(0.23, "].12...37)");
assertEvaluatesToTrue(0.23, "].12...37[");
assertEvaluatesToFalse(13.37, "[.12...37]");
assertEvaluatesToFalse(13.37, "[.12...37)");
assertEvaluatesToFalse(13.37, "[.12...37[");
assertEvaluatesToFalse(13.37, "(.12...37]");
assertEvaluatesToFalse(13.37, "(.12...37)");
assertEvaluatesToFalse(13.37, "(.12...37[");
assertEvaluatesToFalse(13.37, "].12...37]");
assertEvaluatesToFalse(13.37, "].12...37)");
assertEvaluatesToFalse(13.37, "].12...37[");
}
@Test
public void testIntervalVariable() {
variables.put("a", 10);
variables.put("b", 15);
assertEvaluatesToTrue(13.37, "[a..b]");
assertEvaluatesToTrue(13.37, "[a..b)");
assertEvaluatesToTrue(13.37, "[a..b[");
assertEvaluatesToTrue(13.37, "(a..b]");
assertEvaluatesToTrue(13.37, "(a..b)");
assertEvaluatesToTrue(13.37, "(a..b[");
assertEvaluatesToTrue(13.37, "]a..b]");
assertEvaluatesToTrue(13.37, "]a..b)");
assertEvaluatesToTrue(13.37, "]a..b[");
assertEvaluatesToFalse(0.37, "[a..b]");
assertEvaluatesToFalse(0.37, "[a..b)");
assertEvaluatesToFalse(0.37, "[a..b[");
assertEvaluatesToFalse(0.37, "(a..b]");
assertEvaluatesToFalse(0.37, "(a..b)");
assertEvaluatesToFalse(0.37, "(a..b[");
assertEvaluatesToFalse(0.37, "]a..b]");
assertEvaluatesToFalse(0.37, "]a..b)");
assertEvaluatesToFalse(0.37, "]a..b[");
}
@Test
public void testIntervalDateAndTime() {
DateValue dateAndTime = parseDateAndTime("2016-03-03T00:00:00");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:01\")[");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:01\"))");
assertEvaluatesToTrue(dateAndTime, "[date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "]date and time(\"2016-03-02T23:59:59\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToTrue(dateAndTime, "(date and time(\"2016-03-02T23:59:59\")..date and time(\"2016-06-06T00:00:00\")]");
dateAndTime = parseDateAndTime("2013-03-03T00:00:00");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))");
assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")[");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-02T23:59:59\")]");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\")[");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\"))");
assertEvaluatesToFalse(dateAndTime, "[date and time(\"2016-03-03T00:00:01\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToFalse(dateAndTime, "]date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
assertEvaluatesToFalse(dateAndTime, "(date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]");
}
@Test
public void testNot() {
variables.put("y", 13.37);
assertEvaluatesToTrue("Hello camunda", "not(\"Hello World\")");
assertEvaluatesToTrue(0.37, "not(y)");
assertEvaluatesToFalse(0.37, "not(<y)");
assertEvaluatesToFalse(0.37, "not(<=y)");
assertEvaluatesToTrue(0.37, "not(>y)");
assertEvaluatesToTrue(0.37, "not(>=y)");
assertEvaluatesToTrue(0.37, "not(13.37)");
assertEvaluatesToFalse(0.37, "not(<13.37)");
assertEvaluatesToFalse(0.37, "not(<=13.37)");
assertEvaluatesToTrue(0.37, "not(>13.37)");
assertEvaluatesToTrue(0.37, "not(>=13.37)");
assertEvaluatesToFalse(0.37, "not(.37)");
assertEvaluatesToTrue(0.37, "not(<.37)");
assertEvaluatesToFalse(0.37, "not(<=.37)");
assertEvaluatesToTrue(0.37, "not(>.37)");
assertEvaluatesToFalse(0.37, "not(>=.37)");
}
@Test
public void testList() {
variables.put("a", "Hello camunda");
variables.put("y", 0);
assertEvaluatesToTrue("Hello World", "a,\"Hello World\"");
assertEvaluatesToTrue("Hello camunda", "a,\"Hello World\"");
assertEvaluatesToFalse("Hello unknown", "a,\"Hello World\"");
assertEvaluatesToTrue(0, "y,12,13.37,.37");
assertEvaluatesToTrue(12, "y,12,13.37,.37");
assertEvaluatesToTrue(13.37, "y,12,13.37,.37");
assertEvaluatesToTrue(0.37, "y,12,13.37,.37");
assertEvaluatesToFalse(0.23, "y,12,13.37,.37");
assertEvaluatesToTrue(-1, "<y,>13.37,>=.37");
assertEvaluatesToTrue(0.37, "<y,>13.37,>=.37");
assertEvaluatesToFalse(0, "<y,>13.37,>=.37");
}
@Test
public void testNested() {
variables.put("a", 23.42);
assertEvaluatesToTrue(0.37, "not(>=a,13.37,].37...42),<.37)");
assertEvaluatesToFalse(23.42, "not(>=a,13.37,].37...42),<.37)");
assertEvaluatesToFalse(13.37, "not(>=a,13.37,].37...42),<.37)");
assertEvaluatesToFalse(0.38, "not(>=a,13.37,].37...42),<.37)");
assertEvaluatesToFalse(0, "not(>=a,13.37,].37...42),<.37)");
}
@Test
public void testDontCare() {
assertEvaluatesToTrue(13.37, "-");
}
@Test
public void testWhitespace() {
assertEvaluatesToTrue("Hello World", "'Hello World' ");
assertEvaluatesToTrue("Hello World", " 'Hello World'");
assertEvaluatesToTrue("Hello World", " 'Hello World' ");
assertEvaluatesToTrue(12, " 12 ");
assertEvaluatesToTrue(10.2, " <12 ");
assertEvaluatesToTrue(0, "< 12 ");
assertEvaluatesToTrue(12.3, "\t>=12 ");
assertEvaluatesToTrue(0, " not( 13 ,\t>0)\t");
}
@Test
public void testPojo() {
variables.putValue("pojo", new TestPojo("foo", 13.37));
assertEvaluatesToTrue("foo", "pojo.foo");
assertEvaluatesToFalse("camunda", "pojo.foo");
assertEvaluatesToTrue(12, "<= pojo.bar");
assertEvaluatesToFalse(13.33, ">= pojo.bar");
}
public void assertEvaluatesToTrue(Object input, String feelExpression) {
boolean result = evaluateFeel(input, feelExpression);
assertThat(result).isTrue();
}
public void assertEvaluatesToFalse(Object input, String feelExpression) {
boolean result = evaluateFeel(input, feelExpression);
assertThat(result).isFalse();
}
public boolean evaluateFeel(Object input, String feelExpression) {
variables.putValue(INPUT_VARIABLE, input);
return feelEngine.evaluateSimpleUnaryTests(feelExpression, INPUT_VARIABLE, variables.asVariableContext());
}
protected DateValue parseDateAndTime(String dateAndTimeString) {
Date date = FeelFunctionMapper.parseDateAndTime(dateAndTimeString);
return Variables.dateValue(date);
}
public class TestPojo {
protected String foo;
protected Double bar;
public TestPojo(String foo, Double bar) {
this.foo = foo;
this.bar = bar;
}
public String getFoo() {
return foo;
}
public Double getBar() {
return bar;
}
public String toString() {
return "TestPojo{" +
"foo='" + foo + '\'' +
", bar=" + bar +
'}';
}
}
}
| apache-2.0 |
schatt/lightwave | vmafd/interop/java/vks/src/test/java/com/vmware/provider/VecsKeyStoreEngineTest.java | 12989 | /*
* Copyright © 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the “License”); you may not
* use this file except in compliance with the License. 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.vmware.provider;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Enumeration;
import javax.crypto.spec.SecretKeySpec;
import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.vmware.identity.vecs.AlreadyExistsException;
import com.vmware.identity.vecs.VecsStoreFactory;
import sun.misc.BASE64Decoder;
public class VecsKeyStoreEngineTest {
private static final String _storeName = "store-name";
private static KeyStore _keyStore;
private static VecsStoreFactory _factory = VecsStoreFactory.getVecsStoreFactoryViaIPC();
@BeforeClass
static public void init() throws Exception {
Security.addProvider(new VMwareSecurityProvider());
try {
_factory.createCertStore(_storeName);
} catch (AlreadyExistsException e) {
}
_keyStore = KeyStore.getInstance("VKS");
_keyStore.load(new VecsLoadStoreParameter(_storeName));
}
@AfterClass
static public void destroy() throws Exception {
_factory.deleteCertStore(_storeName);
}
@Test
public void test() {
String PROVIDER_NAME = "VECS";
System.out.println("ClassPath : " + System.getProperty("java.classpath"));
Provider p = Security.getProvider(PROVIDER_NAME);
assertNotNull(p);
System.out.println("Name : " + p.getName());
System.out.println("version " + p.getVersion());
System.out.println("info " + p.getInfo());
}
@Test
public void setAndGetCertificateEntry() throws KeyStoreException,
CertificateException {
X509Certificate inCert = getCertificate();
String alias = "pubcert";
_keyStore.setCertificateEntry(alias, inCert);
Certificate outCert = _keyStore.getCertificate(alias);
Assert.assertEquals(inCert, outCert);
_keyStore.deleteEntry(alias);
}
@Test
public void setAndGetPrivateKeyEntry() throws CertificateException,
UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
X509Certificate cert = getCertificate();
PrivateKey inKey = getPrivateKey();
String alias = "privatentry";
_keyStore.setKeyEntry(alias, inKey, null, new X509Certificate[] { cert });
Key outKey = _keyStore.getKey(alias, null);
Assert.assertEquals(inKey, outKey);
_keyStore.deleteEntry(alias);
}
@Test
public void setAndGetSecretKeyEntry() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
String secret = "my_$ecret!@#%\\";
SecretKeySpec inKey = new SecretKeySpec(secret.getBytes(), "myalgo");
String alias = "secretentry";
_keyStore.setKeyEntry(alias, inKey, null, null);
Key outKey = _keyStore.getKey(alias, null);
String outSecret = new String(outKey.getEncoded());
Assert.assertTrue(secret.equals(outSecret));
_keyStore.deleteEntry(alias);
}
@Test
public void enumAliasesAndCheckStoreSizeAndCheckTheEntryTypes()
throws CertificateException, UnrecoverableKeyException,
NoSuchAlgorithmException, KeyStoreException {
// setup
X509Certificate cert = getCertificate();
PrivateKey inKey = getPrivateKey();
String privAlias = "privatentry";
int privCount = 10;
String publAlias = "publicentry";
int publCount = 10;
int i;
for (i = 0; i < privCount; i++) {
_keyStore.setKeyEntry(privAlias + i, inKey, null,
new X509Certificate[] { cert });
}
int j;
for (j = 0; j < publCount; j++) {
_keyStore.setCertificateEntry(publAlias + j, cert);
}
Enumeration<String> aliasEnum = _keyStore.aliases();
i = 0;
String alias = null;
while (aliasEnum.hasMoreElements()) {
i++;
alias = aliasEnum.nextElement();
Assert.assertNotNull(alias);
}
Assert.assertEquals(privCount + publCount, i);
int storeSize = _keyStore.size();
Assert.assertEquals(privCount + publCount, storeSize);
// getEntryTypeByAlias test
for (i = 0; i < privCount; i++) {
Assert.assertTrue(_keyStore.containsAlias(privAlias + i));
Assert.assertTrue(_keyStore.isKeyEntry(privAlias + i));
}
for (j = 0; j < publCount; j++) {
Assert.assertTrue(_keyStore.containsAlias(publAlias + j));
Assert.assertTrue(_keyStore.isCertificateEntry(publAlias + j));
}
// clean up
for (i = 0; i < privCount; i++) {
_keyStore.deleteEntry(privAlias + i);
}
for (j = 0; j < publCount; j++) {
_keyStore.deleteEntry(publAlias + j);
}
}
@Test
public void containsAliasNegative() throws KeyStoreException {
boolean bRes = _keyStore.containsAlias("non-existing");
Assert.assertFalse(bRes);
}
@Test
public void multiThreadedEnumAliasesAndCheckStoreSizeAndCheckTheEntryTypes()
throws CertificateException, UnrecoverableKeyException,
NoSuchAlgorithmException, KeyStoreException {
Thread thr1 = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
enumAliasesAndCheckStoreSizeAndCheckTheEntryTypes();
} catch (UnrecoverableKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thr1.run();
enumAliasesAndCheckStoreSizeAndCheckTheEntryTypes();
}
private PrivateKey getPrivateKey() throws UnrecoverableKeyException,
NoSuchAlgorithmException {
String keyString = "-----BEGIN PRIVATE KEY-----\n"
+ "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC/Pf0mKuCRlDXu\n"
+ "yxkpKgoe56U9Cja2+FCUT+MRNO9OiEZJtQUMNhxOiHO08cNtkPvV3Rp7ceFjpcD7\n"
+ "EQP6MvHGCgsfwnwlBydEKOYAm3Q1pNG/UZpgLyp2w9d30+Xw/bYIFr9Fxpf+5qIz\n"
+ "70/Dz1eD0B1T++O17I6ytZJzeGZ2A+uJUcBypI666vruKx9vUopj2TZUFsQ2aVST\n"
+ "Kq/Wa2rqB+ooH2GRnz8WSaQi6AIEmyIjlwE7ywdDxxT755jFEM3sfDtJpLSHkH7R\n"
+ "qyhnTqTiW4WqmZKEJfzsc4+9c9tV4fuhp3JhTWaKV1YEsq4IQw0CSQ87msGLzoh0\n"
+ "uCz127bnAgMBAAECggEAAumonuRdSj+rI0lwRypkQBHqzYddIPlJj5C4lnerbhNG\n"
+ "RXNz3GVAlh5JljJudbnqaVig7CC7vD73NaZjMfQvrtf9UQ0EbgicsP2RzzrkO2Lu\n"
+ "F49gc2GUhdLix75Foh+DHmlrnV5HzLKU5YdEvD3pXnu/eUV8s4si+0F9CwmE6fw2\n"
+ "OErHKu3JZFuCpEJYCaCDZmaxVM1GofqcWqgpl2Z7trMfeo8zeZZAmDrxGHzGqoL3\n"
+ "0JJhVxtqORAanmCq7wjQuQdiex7gBIhPrPBB8xwRQ3nHl/4O3eFybMVlj29qi3sQ\n"
+ "GiwEvf8hjy+gu3ntd9dnINM4zRlsc635tr494jgBgQKBgQDT/uBGErBrPXcSU9SN\n"
+ "J/aGWRznLS8MoRJ4AI2ZgpHAV7r2Csw4Wwp5ypxioeFhjgLb6CRdthHtiS0ZRFU1\n"
+ "dgH3ee9huYDzoKFuIibGCmvpwjERKDrusrBXoS0FxO2LyslMlJJLn2ii8+9XLJ26\n"
+ "o/OfrXoBQdFFf4yDSzC90j12ZwKBgQDm8E4jYNzuaBADgYHLxz1RY7/s99C8sK0p\n"
+ "9UPQjTHn0iksRwpmb4tyzVsaEYl5BXUC8PqMOsSvbX25mGFHjuXdXo+KT/k6v8fQ\n"
+ "i/hsRV8b2LpRLMFU4kNtacF5YtZrhmjaKdGt0+v5PJf58cX44TObm8Lh85L4tWsr\n"
+ "EFIkLKprgQKBgEUHjUfD9iY1UXxqR5/fD2sXwU2VbOiT2kuxAmqmFYeoCXzsbys6\n"
+ "meKmkt2bEKSPdWbd5FmPW68ZJ9I+afCKiIFo9wW/PboW5/nQrQd3hUQMs6V+kBIB\n"
+ "pWIjXWGvihom4f1Js4lkUtIc1CZypLmNgVrRRhT6tYYHzl1CMpDc0J6pAoGBANd+\n"
+ "cUtt/XqxvA+pb1aZykwCSntzG2KXcl5usSMQPftWDnl0qO3BNFyh51rB9ofpYbCm\n"
+ "8QSdah9Qijr/R/cgDrqsnECyM5xwjKG7mspdSUyQxfstShJNOCIGxzTf17lqKLk6\n"
+ "wJ/12oIt2pqu0s9URXX0uLtjMEfH8gKzLhL3YucBAoGBALwrCT3p5XfED4o2GOhk\n"
+ "d0m3vWzYMoBYiOKUm1E36PvkzGjErWbEJ/pom4zd41EdYkRy/dDiXbm3gd+jFkty\n"
+ "qGc1I2Kvty01aFRKr290hC51IUyWV4EPTnosNr55+HjxsXqy0NHxOCmeH/cpn/Jb\n"
+ "t3I2y2Lf4p+M0T7mq0ovD0uI\n" + "-----END PRIVATE KEY-----";
PrivateKey key = decodePrivateKey(keyString);
return key;
}
private X509Certificate getCertificate() throws CertificateException {
String certificateString = "-----BEGIN CERTIFICATE-----\n"
+ "MIIDkDCCAnigAwIBAgIRAN+NbA6d3U+aKpXIRKKhYfowDQYJKoZIhvcNAQELBQAw\n"
+ "TzELMAkGA1UEBhMCVVMxDzANBgNVBAoTBlZNd2FyZTEbMBkGA1UECxMSVk13YXJl\n"
+ "IEVuZ2luZWVyaW5nMRIwEAYDVQQDEwlDZXJUb29sQ0EwHhcNMTIxMTIxMDAzNjE3\n"
+ "WhcNMjIxMTE5MDAzNjE3WjBPMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGVk13YXJl\n"
+ "MRswGQYDVQQLExJWTXdhcmUgRW5naW5lZXJpbmcxEjAQBgNVBAMTCUNlclRvb2xD\n"
+ "QTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALqfVt5lOc1gPIgy27kl\n"
+ "PvbAS+sLWpReg4NbfUx3gOMA5Ga18nBfy4pbmIv5tZIg95TFresULi83lZwZOJ6M\n"
+ "svOW7Lu1UQPDofBEiqZ0j7GFj0qbW4oUP3ePqTwBIRr2QXhgRPHhR9wxKfc5Yvl7\n"
+ "trmkaQvSbit+7OtHoirSaBCyLnU1D35UbSzT1qINkrgzS/aCHk4r2wuQDaIWCi4O\n"
+ "FdaSgMldEoFD6lhxnDXjZpXP3Cdkd20aIP7dDNj2EXJhgxtGih9HFd9tEEB6wOem\n"
+ "VRLchBLno9RF98P4tvjlfbuIQImrA4WoWp7VlcFbc/RlPOe0ubOHZ/RXDLO90KRl\n"
+ "UmsCAwEAAaNnMGUwEgYDVR0TAQH/BAgwBgEB/wIBATAOBgNVHQ8BAf8EBAMCAQYw\n"
+ "HQYDVR0OBBYEFB4QOUMmKZ3oVHst0ghXZTB+xwgWMCAGA1UdEQQZMBeBD3ZtY2FA\n"
+ "dm13YXJlLmNvbYcEfwAAATANBgkqhkiG9w0BAQsFAAOCAQEAVREDPIqZI90veiXV\n"
+ "hrwXuay9HQpyFOfPq8wXQlrAXsO83toWsDK8bFhiRBwS4qmlI3kIhu25hKUBdyJG\n"
+ "KSAoSojJkMtHhZV4pHWG6h3lUElZ/qSwfgZHfougaN/2MYmx+KL4hjqvXeJhD6ps\n"
+ "zHeNAk2az4LI1u2Xt2CBNKxOLYOgjInVNlF9qlF+EcZgr9xKtXnKcBK3c7ErWLtX\n"
+ "6oM7ZMbGvHd49+sKS0cy9RWomemhS6+LtvBb1Bk9gafmRR7nMfqHBWM0OKg0Wtfj\n"
+ "w6v8QfJWLI4MeBexS5VV2zLAOH3FD6GMJSmICkRKsVuBd7aqBEn2RMbzyW0bIvHr\n"
+ "8vVU/A==\n" + "-----END CERTIFICATE-----\n";
InputStream is;
X509Certificate cert = null;
is = new ByteArrayInputStream(certificateString.getBytes());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate) cf.generateCertificate(is);
return cert;
}
private PrivateKey decodePrivateKey(String privateKey)
throws NoSuchAlgorithmException, UnrecoverableKeyException {
if (privateKey == null) {
throw new NullPointerException("pem string key is null");
}
String pemPrivateKey = new String(privateKey);
pemPrivateKey = pemPrivateKey.replace("-----BEGIN PRIVATE KEY-----", "");
pemPrivateKey = pemPrivateKey.replace("-----END PRIVATE KEY-----", "");
BASE64Decoder decoder = new BASE64Decoder();
byte[] encodedKey;
try {
encodedKey = decoder.decodeBuffer(pemPrivateKey);
} catch (IOException e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException(
"Not able to do BASE64 decoding.");
uke.addSuppressed(e);
throw uke;
}
KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
PrivateKey pKey;
try {
pKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(
encodedKey));
} catch (InvalidKeySpecException e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException(
"Not able to generate private key from key spec.");
uke.addSuppressed(e);
throw uke;
}
return pKey;
}
}
| apache-2.0 |
nelsonsilva/wave-protocol | src/org/waveprotocol/wave/client/doodad/selection/CaretView.java | 1015 | /**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.client.doodad.selection;
/**
* UI interface for the caret marker
*/
public interface CaretView {
/** Update the label of a user's caret */
void setName(String name);
/**
* Set marker's display color
*/
void setColor(RgbColor color);
/**
* Set the current displayed IME composition state for the user's marker
*/
void setCompositionState(String state);
}
| apache-2.0 |
gradle/gradle | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/ivyservice/resolveengine/oldresult/DefaultTransientConfigurationResults.java | 1545 | /*
* Copyright 2013 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.internal.artifacts.ivyservice.resolveengine.oldresult;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.internal.artifacts.DependencyGraphNodeResult;
import java.util.Map;
public class DefaultTransientConfigurationResults implements TransientConfigurationResults {
private final Map<Dependency, DependencyGraphNodeResult> firstLevelDependencies;
private final DependencyGraphNodeResult root;
public DefaultTransientConfigurationResults(DependencyGraphNodeResult root, Map<Dependency, DependencyGraphNodeResult> firstLevelDependencies) {
this.firstLevelDependencies = firstLevelDependencies;
this.root = root;
}
@Override
public Map<Dependency, DependencyGraphNodeResult> getFirstLevelDependencies() {
return firstLevelDependencies;
}
@Override
public DependencyGraphNodeResult getRootNode() {
return root;
}
}
| apache-2.0 |
nathanvick/flyway | flyway-core/src/main/java/org/flywaydb/core/internal/util/jdbc/TransactionCallback.java | 1068 | /**
* Copyright 2010-2016 Boxfuse GmbH
*
* 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.flywaydb.core.internal.util.jdbc;
import java.sql.SQLException;
/**
* Callback for TransactionTemplate.
*
* @param <T> The type of the transaction code result.
*/
public interface TransactionCallback<T> {
/**
* Executes this code within a transaction.
*
* @return The result of the transaction code.
* @throws SQLException when the execution of a statement failed.
*/
T doInTransaction() throws SQLException;
}
| apache-2.0 |
gmarz/elasticsearch | core/src/main/java/org/elasticsearch/cluster/node/DiscoveryNode.java | 15586 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster.node;
import org.elasticsearch.Version;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.node.Node;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* A discovery node represents a node that is part of the cluster.
*/
public class DiscoveryNode implements Writeable, ToXContent {
public static boolean nodeRequiresLocalStorage(Settings settings) {
boolean localStorageEnable = Node.NODE_LOCAL_STORAGE_SETTING.get(settings);
if (localStorageEnable == false &&
(Node.NODE_DATA_SETTING.get(settings) ||
Node.NODE_MASTER_SETTING.get(settings))
) {
// TODO: make this a proper setting validation logic, requiring multi-settings validation
throw new IllegalArgumentException("storage can not be disabled for master and data nodes");
}
return localStorageEnable;
}
public static boolean isMasterNode(Settings settings) {
return Node.NODE_MASTER_SETTING.get(settings);
}
public static boolean isDataNode(Settings settings) {
return Node.NODE_DATA_SETTING.get(settings);
}
public static boolean isIngestNode(Settings settings) {
return Node.NODE_INGEST_SETTING.get(settings);
}
private final String nodeName;
private final String nodeId;
private final String ephemeralId;
private final String hostName;
private final String hostAddress;
private final TransportAddress address;
private final Map<String, String> attributes;
private final Version version;
private final Set<Role> roles;
/**
* Creates a new {@link DiscoveryNode}
* <p>
* <b>Note:</b> if the version of the node is unknown {@link Version#minimumCompatibilityVersion()} should be used for the current
* version. it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
* the node might not be able to communicate with the remove node. After initial handshakes node versions will be discovered
* and updated.
* </p>
*
* @param id the nodes unique (persistent) node id. This constructor will auto generate a random ephemeral id.
* @param address the nodes transport address
* @param version the version of the node
*/
public DiscoveryNode(final String id, TransportAddress address, Version version) {
this(id, address, Collections.emptyMap(), EnumSet.allOf(Role.class), version);
}
/**
* Creates a new {@link DiscoveryNode}
* <p>
* <b>Note:</b> if the version of the node is unknown {@link Version#minimumCompatibilityVersion()} should be used for the current
* version. it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
* the node might not be able to communicate with the remove node. After initial handshakes node versions will be discovered
* and updated.
* </p>
*
* @param id the nodes unique (persistent) node id. This constructor will auto generate a random ephemeral id.
* @param address the nodes transport address
* @param attributes node attributes
* @param roles node roles
* @param version the version of the node
*/
public DiscoveryNode(String id, TransportAddress address, Map<String, String> attributes, Set<Role> roles,
Version version) {
this("", id, address, attributes, roles, version);
}
/**
* Creates a new {@link DiscoveryNode}
* <p>
* <b>Note:</b> if the version of the node is unknown {@link Version#minimumCompatibilityVersion()} should be used for the current
* version. it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
* the node might not be able to communicate with the remove node. After initial handshakes node versions will be discovered
* and updated.
* </p>
*
* @param nodeName the nodes name
* @param nodeId the nodes unique persistent id. An ephemeral id will be auto generated.
* @param address the nodes transport address
* @param attributes node attributes
* @param roles node roles
* @param version the version of the node
*/
public DiscoveryNode(String nodeName, String nodeId, TransportAddress address,
Map<String, String> attributes, Set<Role> roles, Version version) {
this(nodeName, nodeId, UUIDs.randomBase64UUID(), address.getAddress(), address.getAddress(), address, attributes, roles, version);
}
/**
* Creates a new {@link DiscoveryNode}.
* <p>
* <b>Note:</b> if the version of the node is unknown {@link Version#minimumCompatibilityVersion()} should be used for the current
* version. it corresponds to the minimum version this elasticsearch version can communicate with. If a higher version is used
* the node might not be able to communicate with the remove node. After initial handshakes node versions will be discovered
* and updated.
* </p>
*
* @param nodeName the nodes name
* @param nodeId the nodes unique persistent id
* @param ephemeralId the nodes unique ephemeral id
* @param hostAddress the nodes host address
* @param address the nodes transport address
* @param attributes node attributes
* @param roles node roles
* @param version the version of the node
*/
public DiscoveryNode(String nodeName, String nodeId, String ephemeralId, String hostName, String hostAddress,
TransportAddress address, Map<String, String> attributes, Set<Role> roles, Version version) {
if (nodeName != null) {
this.nodeName = nodeName.intern();
} else {
this.nodeName = "";
}
this.nodeId = nodeId.intern();
this.ephemeralId = ephemeralId.intern();
this.hostName = hostName.intern();
this.hostAddress = hostAddress.intern();
this.address = address;
if (version == null) {
this.version = Version.CURRENT;
} else {
this.version = version;
}
this.attributes = Collections.unmodifiableMap(attributes);
//verify that no node roles are being provided as attributes
Predicate<Map<String, String>> predicate = (attrs) -> {
for (Role role : Role.values()) {
assert attrs.containsKey(role.getRoleName()) == false;
}
return true;
};
assert predicate.test(attributes);
Set<Role> rolesSet = EnumSet.noneOf(Role.class);
rolesSet.addAll(roles);
this.roles = Collections.unmodifiableSet(rolesSet);
}
/** Creates a DiscoveryNode representing the local node. */
public static DiscoveryNode createLocal(Settings settings, TransportAddress publishAddress, String nodeId) {
Map<String, String> attributes = new HashMap<>(Node.NODE_ATTRIBUTES.get(settings).getAsMap());
Set<DiscoveryNode.Role> roles = new HashSet<>();
if (Node.NODE_INGEST_SETTING.get(settings)) {
roles.add(DiscoveryNode.Role.INGEST);
}
if (Node.NODE_MASTER_SETTING.get(settings)) {
roles.add(DiscoveryNode.Role.MASTER);
}
if (Node.NODE_DATA_SETTING.get(settings)) {
roles.add(DiscoveryNode.Role.DATA);
}
return new DiscoveryNode(Node.NODE_NAME_SETTING.get(settings), nodeId, publishAddress,attributes, roles, Version.CURRENT);
}
/**
* Creates a new {@link DiscoveryNode} by reading from the stream provided as argument
* @param in the stream
* @throws IOException if there is an error while reading from the stream
*/
public DiscoveryNode(StreamInput in) throws IOException {
this.nodeName = in.readString().intern();
this.nodeId = in.readString().intern();
this.ephemeralId = in.readString().intern();
this.hostName = in.readString().intern();
this.hostAddress = in.readString().intern();
this.address = new TransportAddress(in);
int size = in.readVInt();
this.attributes = new HashMap<>(size);
for (int i = 0; i < size; i++) {
this.attributes.put(in.readString(), in.readString());
}
int rolesSize = in.readVInt();
this.roles = EnumSet.noneOf(Role.class);
for (int i = 0; i < rolesSize; i++) {
int ordinal = in.readVInt();
if (ordinal < 0 || ordinal >= Role.values().length) {
throw new IOException("Unknown Role ordinal [" + ordinal + "]");
}
this.roles.add(Role.values()[ordinal]);
}
this.version = Version.readVersion(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(nodeName);
out.writeString(nodeId);
out.writeString(ephemeralId);
out.writeString(hostName);
out.writeString(hostAddress);
address.writeTo(out);
out.writeVInt(attributes.size());
for (Map.Entry<String, String> entry : attributes.entrySet()) {
out.writeString(entry.getKey());
out.writeString(entry.getValue());
}
out.writeVInt(roles.size());
for (Role role : roles) {
out.writeVInt(role.ordinal());
}
Version.writeVersion(version, out);
}
/**
* The address that the node can be communicated with.
*/
public TransportAddress getAddress() {
return address;
}
/**
* The unique id of the node.
*/
public String getId() {
return nodeId;
}
/**
* The unique ephemeral id of the node. Ephemeral ids are meant to be attached the the life span
* of a node process. When ever a node is restarted, it's ephemeral id is required to change (while it's {@link #getId()}
* will be read from the data folder and will remain the same across restarts). Since all node attributes and addresses
* are maintained during the life span of a node process, we can (and are) using the ephemeralId in
* {@link DiscoveryNode#equals(Object)}.
*/
public String getEphemeralId() {
return ephemeralId;
}
/**
* The name of the node.
*/
public String getName() {
return this.nodeName;
}
/**
* The node attributes.
*/
public Map<String, String> getAttributes() {
return this.attributes;
}
/**
* Should this node hold data (shards) or not.
*/
public boolean isDataNode() {
return roles.contains(Role.DATA);
}
/**
* Can this node become master or not.
*/
public boolean isMasterNode() {
return roles.contains(Role.MASTER);
}
/**
* Returns a boolean that tells whether this an ingest node or not
*/
public boolean isIngestNode() {
return roles.contains(Role.INGEST);
}
/**
* Returns a set of all the roles that the node fulfills.
* If the node doesn't have any specific role, the set is returned empty, which means that the node is a coordinating only node.
*/
public Set<Role> getRoles() {
return roles;
}
public Version getVersion() {
return this.version;
}
public String getHostName() {
return this.hostName;
}
public String getHostAddress() {
return this.hostAddress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DiscoveryNode that = (DiscoveryNode) o;
return ephemeralId.equals(that.ephemeralId);
}
@Override
public int hashCode() {
// we only need to hash the id because it's highly unlikely that two nodes
// in our system will have the same id but be different
// This is done so that this class can be used efficiently as a key in a map
return ephemeralId.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (nodeName.length() > 0) {
sb.append('{').append(nodeName).append('}');
}
sb.append('{').append(nodeId).append('}');
sb.append('{').append(ephemeralId).append('}');
sb.append('{').append(hostName).append('}');
sb.append('{').append(address).append('}');
if (!attributes.isEmpty()) {
sb.append(attributes);
}
return sb.toString();
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(getId());
builder.field("name", getName());
builder.field("ephemeral_id", getEphemeralId());
builder.field("transport_address", getAddress().toString());
builder.startObject("attributes");
for (Map.Entry<String, String> entry : attributes.entrySet()) {
builder.field(entry.getKey(), entry.getValue());
}
builder.endObject();
builder.endObject();
return builder;
}
/**
* Enum that holds all the possible roles that that a node can fulfill in a cluster.
* Each role has its name and a corresponding abbreviation used by cat apis.
*/
public enum Role {
MASTER("master", "m"),
DATA("data", "d"),
INGEST("ingest", "i");
private final String roleName;
private final String abbreviation;
Role(String roleName, String abbreviation) {
this.roleName = roleName;
this.abbreviation = abbreviation;
}
public String getRoleName() {
return roleName;
}
public String getAbbreviation() {
return abbreviation;
}
}
}
| apache-2.0 |
nknize/elasticsearch | x-pack/plugin/sql/qa/server/single-node/src/test/java/org/elasticsearch/xpack/sql/qa/single_node/CliShowIT.java | 399 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.qa.single_node;
import org.elasticsearch.xpack.sql.qa.cli.ShowTestCase;
public class CliShowIT extends ShowTestCase {}
| apache-2.0 |
rhodgin/brooklyn | core/src/main/java/brooklyn/entity/basic/ConfigKeys.java | 8069 | package brooklyn.entity.basic;
import javax.annotation.Nonnull;
import brooklyn.config.ConfigKey;
import brooklyn.event.basic.AttributeSensorAndConfigKey;
import brooklyn.event.basic.BasicAttributeSensorAndConfigKey;
import brooklyn.event.basic.BasicConfigKey;
import brooklyn.event.basic.BasicConfigKey.BasicConfigKeyOverwriting;
import brooklyn.event.basic.PortAttributeSensorAndConfigKey;
import com.google.common.base.CaseFormat;
import com.google.common.base.Preconditions;
import com.google.common.reflect.TypeToken;
/**
* Dictionary of {@link ConfigKey} entries.
*/
public class ConfigKeys {
public static <T> ConfigKey<T> newConfigKey(Class<T> type, String name) {
return new BasicConfigKey<T>(type, name);
}
public static <T> ConfigKey<T> newConfigKey(Class<T> type, String name, String description) {
return new BasicConfigKey<T>(type, name, description);
}
public static <T> ConfigKey<T> newConfigKey(TypeToken<T> type, String name) {
return new BasicConfigKey<T>(type, name);
}
public static <T> ConfigKey<T> newConfigKey(TypeToken<T> type, String name, String description) {
return new BasicConfigKey<T>(type, name, description);
}
public static <T> ConfigKey<T> newConfigKey(Class<T> type, String name, String description, T defaultValue) {
return new BasicConfigKey<T>(type, name, description, defaultValue);
}
public static <T> ConfigKey<T> newConfigKey(TypeToken<T> type, String name, String description, T defaultValue) {
return new BasicConfigKey<T>(type, name, description, defaultValue);
}
public static <T> AttributeSensorAndConfigKey<T,T> newSensorAndConfigKey(Class<T> type, String name, String description) {
return new BasicAttributeSensorAndConfigKey<T>(type, name, description);
}
public static <T> AttributeSensorAndConfigKey<T,T> newSensorAndConfigKey(Class<T> type, String name, String description, T defaultValue) {
return new BasicAttributeSensorAndConfigKey<T>(type, name, description, defaultValue);
}
public static <T> AttributeSensorAndConfigKey<T,T> newSensorAndConfigKey(TypeToken<T> type, String name, String description) {
return new BasicAttributeSensorAndConfigKey<T>(type, name, description);
}
public static <T> AttributeSensorAndConfigKey<T,T> newSensorAndConfigKey(TypeToken<T> type, String name, String description, T defaultValue) {
return new BasicAttributeSensorAndConfigKey<T>(type, name, description, defaultValue);
}
public static AttributeSensorAndConfigKey<String,String> newStringSensorAndConfigKey(String name, String description) {
return new BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey(name, description);
}
public static AttributeSensorAndConfigKey<String,String> newStringSensorAndConfigKey(String name, String description, String defaultValue) {
return new BasicAttributeSensorAndConfigKey.StringAttributeSensorAndConfigKey(name, description, defaultValue);
}
public static AttributeSensorAndConfigKey<Integer,Integer> newIntegerSensorAndConfigKey(String name, String description) {
return new BasicAttributeSensorAndConfigKey.IntegerAttributeSensorAndConfigKey(name, description);
}
public static AttributeSensorAndConfigKey<Integer,Integer> newIntegerSensorAndConfigKey(String name, String description, Integer defaultValue) {
return new BasicAttributeSensorAndConfigKey.IntegerAttributeSensorAndConfigKey(name, description, defaultValue);
}
public static PortAttributeSensorAndConfigKey newPortSensorAndConfigKey(String name, String description) {
return new PortAttributeSensorAndConfigKey(name, description);
}
public static PortAttributeSensorAndConfigKey newPortSensorAndConfigKey(String name, String description, Object defaultValue) {
return new PortAttributeSensorAndConfigKey(name, description, defaultValue);
}
/** Infers the type from the default value */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> ConfigKey<T> newConfigKey(String name, String description, @Nonnull T defaultValue) {
return new BasicConfigKey<T>((Class)Preconditions.checkNotNull(defaultValue,
"Type must be exlicit for ConfigKey if defaultValue is null").getClass(),
name, description, defaultValue);
}
public static <T> BasicConfigKey.Builder<T> builder(Class<T> type) {
return BasicConfigKey.builder(type);
}
public static <T> BasicConfigKey.Builder<T> builder(TypeToken<T> type) {
return BasicConfigKey.builder(type);
}
// ---- extensions to keys
public static <T> ConfigKey<T> newConfigKeyWithDefault(ConfigKey<T> parent, T defaultValue) {
return new BasicConfigKeyOverwriting<T>(parent, defaultValue);
}
public static <T> ConfigKey<T> newConfigKeyRenamed(String newName, ConfigKey<T> key) {
return new BasicConfigKey<T>(key.getTypeToken(), newName, key.getDescription(), key.getDefaultValue());
}
public static <T> ConfigKey<T> newConfigKeyWithPrefix(String prefix, ConfigKey<T> key) {
return newConfigKeyRenamed(prefix+key.getName(), key);
}
/** converts the name of the key from one case-strategy (e.g. lowerCamel) to andother (e.g. lower-hyphen) */
public static <T> ConfigKey<T> convert(ConfigKey<T> key, CaseFormat inputCaseStrategy, CaseFormat outputCaseStrategy) {
return newConfigKeyRenamed(inputCaseStrategy.to(outputCaseStrategy, key.getName()), key);
}
// ---- typed keys
public static ConfigKey<String> newStringConfigKey(String name) {
return newConfigKey(String.class, name);
}
public static ConfigKey<String> newStringConfigKey(String name, String description) {
return newConfigKey(String.class, name, description);
}
public static ConfigKey<String> newStringConfigKey(String name, String description, String defaultValue) {
return newConfigKey(String.class, name, description, defaultValue);
}
public static ConfigKey<Integer> newIntegerConfigKey(String name) {
return newConfigKey(Integer.class, name);
}
public static ConfigKey<Integer> newIntegerConfigKey(String name, String description) {
return newConfigKey(Integer.class, name, description);
}
public static ConfigKey<Integer> newIntegerConfigKey(String name, String description, Integer defaultValue) {
return newConfigKey(Integer.class, name, description, defaultValue);
}
public static ConfigKey<Long> newLongConfigKey(String name) {
return newConfigKey(Long.class, name);
}
public static ConfigKey<Long> newLongConfigKey(String name, String description) {
return newConfigKey(Long.class, name, description);
}
public static ConfigKey<Long> newLongConfigKey(String name, String description, Long defaultValue) {
return newConfigKey(Long.class, name, description, defaultValue);
}
public static ConfigKey<Double> newDoubleConfigKey(String name) {
return newConfigKey(Double.class, name);
}
public static ConfigKey<Double> newDoubleConfigKey(String name, String description) {
return newConfigKey(Double.class, name, description);
}
public static ConfigKey<Double> newDoubleConfigKey(String name, String description, Double defaultValue) {
return newConfigKey(Double.class, name, description, defaultValue);
}
public static ConfigKey<Boolean> newBooleanConfigKey(String name) {
return newConfigKey(Boolean.class, name);
}
public static ConfigKey<Boolean> newBooleanConfigKey(String name, String description) {
return newConfigKey(Boolean.class, name, description);
}
public static ConfigKey<Boolean> newBooleanConfigKey(String name, String description, Boolean defaultValue) {
return newConfigKey(Boolean.class, name, description, defaultValue);
}
}
| apache-2.0 |
yogidevendra/incubator-apex-malhar | examples/wordcount/src/main/java/org/apache/apex/examples/wordcount/ApplicationWithQuerySupport.java | 5844 | /**
* 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.apex.examples.wordcount;
import java.net.URI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import com.datatorrent.api.DAG;
import com.datatorrent.api.Operator;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.annotation.ApplicationAnnotation;
import com.datatorrent.lib.appdata.schemas.SchemaUtils;
import com.datatorrent.lib.appdata.snapshot.AppDataSnapshotServerMap;
import com.datatorrent.lib.io.ConsoleOutputOperator;
import com.datatorrent.lib.io.PubSubWebSocketAppDataQuery;
import com.datatorrent.lib.io.PubSubWebSocketAppDataResult;
/**
* Simple example that computes word frequencies from any file dropped into a
* monitored directory. It outputs the top N word-frequency pairs for each file
* as well globally across all files.
* <p>
* Each input file generates a corresponding output file in the output directory
* containing the top N pairs for that file. The output is also written
* to an internal store to support visualization in the UI via queries.
* <p>
* @since 3.2.0
*/
@ApplicationAnnotation(name = "TopNWordsWithQueries")
public class ApplicationWithQuerySupport implements StreamingApplication
{
private static final Logger LOG = LoggerFactory.getLogger(ApplicationWithQuerySupport.class);
/**
* Name of schema file.
*/
public static final String SNAPSHOT_SCHEMA = "WordDataSchema.json";
/**
* Populates the DAG with operators and connecting streams
*
* @param dag The directed acyclic graph of operators to populate
* @param conf The configuration
*/
@Override
public void populateDAG(DAG dag, Configuration conf)
{
// create operators
LineReader lineReader = dag.addOperator("lineReader", new LineReader());
WordReader wordReader = dag.addOperator("wordReader", new WordReader());
WindowWordCount windowWordCount = dag.addOperator("windowWordCount", new WindowWordCount());
FileWordCount fileWordCount = dag.addOperator("fileWordCount", new FileWordCount());
WordCountWriter wcWriter = dag.addOperator("wcWriter", new WordCountWriter());
ConsoleOutputOperator console = dag.addOperator("console", new ConsoleOutputOperator());
console.setStringFormat("wordCount: %s");
// create streams
dag.addStream("lines", lineReader.output, wordReader.input);
dag.addStream("control", lineReader.control, fileWordCount.control);
dag.addStream("words", wordReader.output, windowWordCount.input);
dag.addStream("windowWordCounts", windowWordCount.output, fileWordCount.input);
dag.addStream("fileWordCounts", fileWordCount.fileOutput, wcWriter.input);
String gatewayAddress = dag.getValue(DAG.GATEWAY_CONNECT_ADDRESS);
if (!StringUtils.isEmpty(gatewayAddress)) { // add query support
URI uri = URI.create("ws://" + gatewayAddress + "/pubsub");
AppDataSnapshotServerMap snapshotServerFile
= dag.addOperator("snapshotServerFile", new AppDataSnapshotServerMap());
AppDataSnapshotServerMap snapshotServerGlobal
= dag.addOperator("snapshotServerGlobal", new AppDataSnapshotServerMap());
String snapshotServerJSON = SchemaUtils.jarResourceFileToString(SNAPSHOT_SCHEMA);
snapshotServerFile.setSnapshotSchemaJSON(snapshotServerJSON);
snapshotServerGlobal.setSnapshotSchemaJSON(snapshotServerJSON);
PubSubWebSocketAppDataQuery wsQueryFile = new PubSubWebSocketAppDataQuery();
PubSubWebSocketAppDataQuery wsQueryGlobal = new PubSubWebSocketAppDataQuery();
wsQueryFile.setUri(uri);
wsQueryGlobal.setUri(uri);
snapshotServerFile.setEmbeddableQueryInfoProvider(wsQueryFile);
snapshotServerGlobal.setEmbeddableQueryInfoProvider(wsQueryGlobal);
PubSubWebSocketAppDataResult wsResultFile
= dag.addOperator("wsResultFile", new PubSubWebSocketAppDataResult());
PubSubWebSocketAppDataResult wsResultGlobal
= dag.addOperator("wsResultGlobal", new PubSubWebSocketAppDataResult());
wsResultFile.setUri(uri);
wsResultGlobal.setUri(uri);
Operator.InputPort<String> queryResultFilePort = wsResultFile.input;
Operator.InputPort<String> queryResultGlobalPort = wsResultGlobal.input;
dag.addStream("WordCountsFile", fileWordCount.outputPerFile, snapshotServerFile.input, console.input);
dag.addStream("WordCountsGlobal", fileWordCount.outputGlobal, snapshotServerGlobal.input);
dag.addStream("ResultFile", snapshotServerFile.queryResult, queryResultFilePort);
dag.addStream("ResultGlobal", snapshotServerGlobal.queryResult, queryResultGlobalPort);
} else {
//throw new RuntimeException("Error: No GATEWAY_CONNECT_ADDRESS");
dag.addStream("WordCounts", fileWordCount.outputPerFile, console.input);
}
LOG.info("done with populateDAG, isDebugEnabled = " + LOG.isDebugEnabled());
LOG.info("Returning from populateDAG");
}
}
| apache-2.0 |
ugate/ugate | src/main/java/org/ugate/gui/view/AlarmSettings.java | 8731 | package org.ugate.gui.view;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import org.ugate.gui.ControlBar;
import org.ugate.gui.ControlPane;
import org.ugate.gui.GuiUtil;
import org.ugate.gui.components.UGateCtrlBox;
import org.ugate.gui.components.UGateToggleSwitchBox;
import org.ugate.resources.RS;
import org.ugate.resources.RS.KEY;
import org.ugate.service.entity.Command;
import org.ugate.service.entity.Model;
import org.ugate.service.entity.RemoteNodeType;
import org.ugate.service.entity.jpa.RemoteNode;
import org.ugate.service.entity.jpa.RemoteNodeReading;
/**
* {@link RemoteNode} general settings configuration
*/
public class AlarmSettings extends ControlPane {
private UGateToggleSwitchBox<RemoteNode> syncToggleSwitch;
private UGateToggleSwitchBox<RemoteNode> soundsToggleSwitch;
private UGateToggleSwitchBox<RemoteNode> emailToggleSwitch;
private UGateToggleSwitchBox<RemoteNode> imgResToggleSwitch;
private UGateToggleSwitchBox<RemoteNode> universalRemoteAccessToggleSwitch;
private UGateCtrlBox<RemoteNode, Model, Void> remoteAddress;
private UGateCtrlBox<RemoteNode, Model, Void> workingDir;
private UGateCtrlBox<RemoteNode, Model, Void> accessKey1;
private UGateCtrlBox<RemoteNode, Model, Void> accessKey2;
private UGateCtrlBox<RemoteNode, Model, Void> accessKey3;
private UGateToggleSwitchBox<RemoteNode> gateToggleSwitchView;
private AlarmMultistates alarmMultistates;
/**
* Constructor
*
* @param controlBar
* the {@linkplain ControlBar}
* @param the
* {@linkplain SensorReading}
*/
public AlarmSettings(final ControlBar controlBar) {
super(controlBar);
int ci = -1;
addRemoteNodeSetupChildren(++ci, 0);
addNotificationOptionChildren(++ci, 0);
addGateChildren(++ci, 0);
}
protected void addNotificationOptionChildren(final int columnIndex, final int rowIndex) {
final Label soundLabel = createLabel(KEY.SERVICE_CMD_SOUNDS);
final Label emailLabel = createLabel(KEY.MAIL_ALARM_NOTIFY);
final Label imgResLabel = createLabel(KEY.CAM_RES);
final Label syncResLabel = createLabel(KEY.WIRELESS_REMOTE_SYNC);
soundsToggleSwitch = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(), RemoteNodeType.DEVICE_SOUNDS_ON,
RS.IMG_SOUND_ON, RS.IMG_SOUND_OFF);
controlBar.addHelpTextTrigger(soundsToggleSwitch, RS.rbLabel(KEY.SERVICE_CMD_SOUNDS_TOGGLE));
emailToggleSwitch = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(), RemoteNodeType.MAIL_ALERT_ON,
RS.IMG_EMAIL_NOTIFY_ON, RS.IMG_EMAIL_NOTIFY_OFF);
controlBar.addHelpTextTrigger(emailToggleSwitch, RS.rbLabel(KEY.MAIL_ALARM_NOTIFY_DESC));
imgResToggleSwitch = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(), RemoteNodeType.CAM_RESOLUTION,
RS.IMG_CAM_TOGGLE_VGA, RS.IMG_CAM_TOGGLE_QVGA,
RS.rbLabel(KEY.CAM_RES_VGA),
RS.rbLabel(KEY.CAM_RES_QVGA));
imgResToggleSwitch.getToggleItem().toggleSwitchImageView.setEffect(new DropShadow());
controlBar.addHelpTextTrigger(imgResToggleSwitch, RS.rbLabel(KEY.CAM_RES_DESC));
syncToggleSwitch = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(), RemoteNodeType.DEVICE_AUTO_SYNCHRONIZE,
RS.IMG_SYNC_ON, RS.IMG_SYNC_OFF);
controlBar.addHelpTextTrigger(syncToggleSwitch, RS.rbLabel(KEY.WIRELESS_REMOTE_SYNC_DESC));
final Parent generalCell = createCell(soundLabel, soundsToggleSwitch, emailLabel, emailToggleSwitch,
imgResLabel, imgResToggleSwitch, syncResLabel, syncToggleSwitch);
add(generalCell, columnIndex, rowIndex);
}
protected void addRemoteNodeSetupChildren(final int columnIndex, final int rowIndex) {
final Label univRemoteLabel = createLabel(KEY.WIRELESS_REMOTE_UNIVERSAL);
final Label nodeLabel = createLabel(KEY.WIRELESS_NODE_REMOTE_ADDY);
nodeLabel.setPrefWidth(350d);
remoteAddress = new UGateCtrlBox<>(controlBar.getRemoteNodePA(),
RemoteNodeType.WIRELESS_ADDRESS, UGateCtrlBox.Type.TEXT,
RS.rbLabel(KEY.WIRELESS_NODE_REMOTE_ADDY), null);
remoteAddress.label.getStyleClass().add("dialog-normal");
controlBar.addHelpTextTrigger(remoteAddress, RS.rbLabel(
KEY.WIRELESS_NODE_REMOTE_ADDY_DESC,
controlBar.getRemoteNode().getAddress()));
workingDir = new UGateCtrlBox<>(controlBar.getRemoteNodePA(),
RemoteNodeType.WIRELESS_WORKING_DIR_PATH,
UGateCtrlBox.Type.DIR_CHOOSER,
RS.rbLabel(KEY.WIRELESS_WORKING_DIR), null);
workingDir.label.getStyleClass().add("dialog-normal");
controlBar.addHelpTextTrigger(workingDir,
RS.rbLabel(KEY.WIRELESS_WORKING_DIR_DESC));
alarmMultistates = new AlarmMultistates(controlBar, Orientation.HORIZONTAL);
universalRemoteAccessToggleSwitch = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(),
RemoteNodeType.UNIVERSAL_REMOTE_ACCESS_ON,
RS.IMG_UNIVERSAL_REMOTE_ON, RS.IMG_UNIVERSAL_REMOTE_OFF);
controlBar.addHelpTextTrigger(universalRemoteAccessToggleSwitch,
RS.rbLabel(KEY.WIRELESS_REMOTE_UNIVERSAL_DESC,
controlBar.getRemoteNode().getAddress()));
accessKey1 = new UGateCtrlBox<>(controlBar.getRemoteNodePA(),
RemoteNodeType.UNIVERSAL_REMOTE_ACCESS_CODE_1,
ACCESS_KEY_CODE_FORMAT, null, null, null, RS.rbLabel(
KEY.WIRELESS_ACCESS_KEY, 1), null);
controlBar.addHelpTextTrigger(accessKey1, RS.rbLabel(KEY.WIRELESS_ACCESS_KEY_DESC, 1));
accessKey2 = new UGateCtrlBox<>(controlBar.getRemoteNodePA(),
RemoteNodeType.UNIVERSAL_REMOTE_ACCESS_CODE_2,
ACCESS_KEY_CODE_FORMAT, null, null, null, RS.rbLabel(
KEY.WIRELESS_ACCESS_KEY, 2), null);
controlBar.addHelpTextTrigger(accessKey2, RS.rbLabel(KEY.WIRELESS_ACCESS_KEY_DESC, 2));
accessKey3 = new UGateCtrlBox<>(controlBar.getRemoteNodePA(),
RemoteNodeType.UNIVERSAL_REMOTE_ACCESS_CODE_3,
ACCESS_KEY_CODE_FORMAT, null, null, null, RS.rbLabel(
KEY.WIRELESS_ACCESS_KEY, 3), null);
controlBar.addHelpTextTrigger(accessKey3, RS.rbLabel(KEY.WIRELESS_ACCESS_KEY_DESC, 3));
final HBox accessKeysContainer = new HBox(5);
accessKeysContainer.getChildren().addAll(accessKey1, accessKey2, accessKey3);
final Parent setupCell = createCell(nodeLabel, remoteAddress, workingDir, alarmMultistates,
univRemoteLabel, universalRemoteAccessToggleSwitch, accessKeysContainer);
add(setupCell, columnIndex, rowIndex);
}
protected void addGateChildren(final int columnIndex, final int rowIndex) {
final Label gateHeader = createLabel(KEY.GATE_CONFIG);
gateToggleSwitchView = new UGateToggleSwitchBox<>(
controlBar.getRemoteNodePA(), RemoteNodeType.GATE_ACCESS_ON,
RS.IMG_GATE_ON, RS.IMG_GATE_OFF);
controlBar.addHelpTextTrigger(gateToggleSwitchView, RS.rbLabel(KEY.GATE_ACCESS_DESC));
final Label gateCtrlHeader = createLabel(KEY.GATE_STATE);
final ImageView gateToggleImgView = RS.imgView(RS.IMG_GATE_CLOSED);
final Button gateToggleBtn = new Button();
gateToggleBtn.setCursor(Cursor.HAND);
gateToggleBtn.setGraphic(gateToggleImgView);
controlBar.addHelpTextTrigger(gateToggleBtn, RS.rbLabel(KEY.GATE_TOGGLE_DESC));
gateToggleBtn.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(final MouseEvent event) {
if (GuiUtil.isPrimaryPress(event)) {
gateToggleBtn.setDisable(true);
if (controlBar.createCommandService(Command.GATE_TOGGLE_OPEN_CLOSE, true) == null) {
gateToggleBtn.setDisable(false);
}
}
}
});
controlBar.getSensorReadingsView().sensorReadingsProperty().addListener(
new ChangeListener<RemoteNodeReading>() {
@Override
public void changed(final ObservableValue<? extends RemoteNodeReading> observable,
final RemoteNodeReading oldValue, final RemoteNodeReading newValue) {
// when a command is sent to a remote node to open/close a gate a response for
// sensor readings will be sent to the host where the gate state update is captured
gateToggleImgView.setImage(newValue != null && newValue.getGateState() == 1 ?
RS.img(RS.IMG_GATE_OPENED) : RS.img(RS.IMG_GATE_CLOSED));
gateToggleBtn.setDisable(false);
}
});
final Parent cell = createCell(gateHeader, gateToggleSwitchView,
gateCtrlHeader, gateToggleBtn);
add(cell, columnIndex, rowIndex);
}
}
| apache-2.0 |
madhav123/gkmaster | application/src/main/java/org/mifos/framework/business/service/ServiceFactory.java | 2085 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.framework.business.service;
import java.util.HashMap;
import java.util.Map;
import org.mifos.framework.exceptions.ServiceUnavailableException;
import org.mifos.framework.util.helpers.BusinessServiceName;
import org.mifos.framework.util.helpers.ExceptionConstants;
public class ServiceFactory {
private ServiceFactory() {
}
private static ServiceFactory instance = new ServiceFactory();
private Map<BusinessServiceName, BusinessService> businessServicesMap = new HashMap<BusinessServiceName, BusinessService>();
public static ServiceFactory getInstance() {
return instance;
}
/**
* @deprecated Call the constructor of the business service directly. For
* example, <code>new ConfigurationBusinessService();</code>
*/
@Deprecated
public BusinessService getBusinessService(BusinessServiceName key) throws ServiceUnavailableException {
if (!businessServicesMap.containsKey(key)) {
try {
businessServicesMap.put(key, (BusinessService) Class.forName(key.getName()).newInstance());
} catch (Exception cnfe) {
throw new ServiceUnavailableException(ExceptionConstants.SERVICEEXCEPTION, cnfe);
}
}
return businessServicesMap.get(key);
}
}
| apache-2.0 |
jhrcek/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-case-mgmt/kie-wb-common-stunner-case-mgmt-project-client/src/main/java/org/kie/workbench/common/stunner/cm/project/client/CaseManagementProjectClientEntryPoint.java | 932 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.cm.project.client;
import org.jboss.errai.ioc.client.api.EntryPoint;
import org.jboss.errai.ui.shared.api.annotations.Bundle;
@EntryPoint
@Bundle("resources/i18n/CaseManagementProjectClientConstants.properties")
public class CaseManagementProjectClientEntryPoint {
}
| apache-2.0 |
ddiroma/pentaho-kettle | core/src/main/java/org/pentaho/di/core/vfs/SftpFileSystemWindowsProvider.java | 4571 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2021 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.vfs;
import com.jcraft.jsch.Session;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.sftp.SftpClientFactory;
import org.apache.commons.vfs2.provider.sftp.SftpFileProvider;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* This class serves two main purposes.
* <ol>
* <li>
* To provide a correct way of running sftp commands on Windows server.
* Current implementation of commons-vfs calls <code>id -G</code> or <code>id -u</code>,
* which is incorrect for Windows.
* </li>
* <li>
* To provide a way to release sftp connections, when we're done.
* commons-vfs says we do not close fileSystemManager until application shutdown
* (see <a href="https://issues.apache.org/jira/browse/VFS-454">VFS-454</a>).
* Thus, we need to close the connections.<br/>
* There is {@link org.apache.commons.vfs2.provider.AbstractFileProvider#freeUnusedResources()},
* which we can use to achieve this. But, unfortunately, original SftpFileSystem only releases them
* when all file objects it's associated with are garbage collected. This is too restrictive and inconvenient.
* Here we make the sftp file system object releasable when there are open file objects,
* we only need i/o streams to be closed. <br/>
* This is pretty safe to do. Even a file object would want to open a stream once again (currently wouldn't),
* the file system object re-creates session and opens a new connection.
* </li>
* </ol>
* This provider replaces {@link SftpFileProvider} in FileSystemManager (see overridden providers.xml).
* And then used to spawn SftpFileSystemWindows and SftpFileObjectWithWindowsSupport.
*/
// suppress the "too many parents" warning; can't be helped here
@SuppressWarnings( "squid:S110" )
public class SftpFileSystemWindowsProvider extends SftpFileProvider {
/**
* Creates a new Session. Note that this method is borrowed from the parent class and should mirror it if the
* commons-vfs2 library is updated.
*
* @return A Session, never null.
*/
static Session createSession( final GenericFileName rootName, final FileSystemOptions fileSystemOptions )
throws FileSystemException {
UserAuthenticationData authData = null;
try {
authData = UserAuthenticatorUtils.authenticate( fileSystemOptions, AUTHENTICATOR_TYPES );
return SftpClientFactory.createConnection( rootName.getHostName(), rootName.getPort(),
UserAuthenticatorUtils.getData( authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar( rootName.getUserName() ) ),
UserAuthenticatorUtils.getData( authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar( rootName.getPassword() ) ),
fileSystemOptions );
} catch ( final Exception e ) {
throw new FileSystemException( "vfs.provider.sftp/connect.error", rootName, e );
} finally {
UserAuthenticatorUtils.cleanup( authData );
}
}
@Override
protected FileSystem doCreateFileSystem( FileName name, FileSystemOptions fileSystemOptions )
throws FileSystemException {
return new SftpFileSystemWindows(
(GenericFileName) name, createSession( (GenericFileName) name, fileSystemOptions ), fileSystemOptions );
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/util/SampleableConcurrentHashMap.java | 15036 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.hazelcast.internal.util;
import com.hazelcast.internal.eviction.Expirable;
import com.hazelcast.internal.iteration.IterationPointer;
import com.hazelcast.internal.serialization.SerializableByConvention;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.BiConsumer;
/**
* ConcurrentHashMap to extend iterator capability.
*
* @param <K> Type of the key
* @param <V> Type of the value
*/
@SerializableByConvention
public class SampleableConcurrentHashMap<K, V> extends ConcurrentReferenceHashMap<K, V> {
private static final float LOAD_FACTOR = 0.91f;
public SampleableConcurrentHashMap(int initialCapacity) {
this(initialCapacity, ReferenceType.STRONG, ReferenceType.STRONG);
}
public SampleableConcurrentHashMap(int initialCapacity, ReferenceType keyType, ReferenceType valueType) {
// Concurrency level 1 is important for fetch-method to function properly.
// Moreover partitions are single threaded and higher concurrency has not much gain
this(initialCapacity, LOAD_FACTOR, 1, keyType, valueType, null);
}
private SampleableConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel,
ReferenceType keyType, ReferenceType valueType, EnumSet<Option> options) {
super(initialCapacity, loadFactor, concurrencyLevel, keyType, valueType, options);
}
/**
* Fetches at least {@code size} keys from the given {@code pointers} and
* puts them into the {@code keys} list.
*
* @param pointers the pointers defining the state where to begin iteration
* @param size Count of how many keys will be fetched
* @param keys List that fetched keys will be put into
* @return the pointers defining the state where iteration has ended
*/
public IterationPointer[] fetchKeys(IterationPointer[] pointers, int size, List<K> keys) {
return fetchNext(pointers, size, (k, v) -> keys.add(k));
}
/**
* Fetches at least {@code size} keys from the given {@code pointers} and
* puts them into the {@code entries} list.
*
* @param pointers the pointers defining the state where to begin iteration
* @param size Count of how many entries will be fetched
* @param entries List that fetched entries will be put into
* @return the pointers defining the state where iteration has ended
*/
public IterationPointer[] fetchEntries(IterationPointer[] pointers,
int size,
List<Map.Entry<K, V>> entries) {
return fetchNext(pointers, size, (k, v) -> entries.add(new AbstractMap.SimpleEntry<>(k, v)));
}
/**
* Fetches at most {@code size} keys starting at the given {@code pointers} and
* invokes the {@code entryConsumer} for each key-value pair.
*
* @param pointers the pointers defining the state where to begin iteration
* @param size Count of how many entries will be fetched
* @param entryConsumer the consumer to call with fetched key-value pairs
* @return the pointers defining the state where iteration has ended
*/
private IterationPointer[] fetchNext(IterationPointer[] pointers,
int size,
BiConsumer<K, V> entryConsumer) {
long now = Clock.currentTimeMillis();
Segment<K, V> segment = segments[0];
try {
segment.lock();
HashEntry<K, V>[] currentTable = segment.table;
int currentTableSize = currentTable.length;
pointers = checkPointers(pointers, currentTableSize);
IterationPointer lastPointer = pointers[pointers.length - 1];
int nextTableIndex;
if (lastPointer.getIndex() >= 0 && lastPointer.getIndex() < segment.table.length) {
nextTableIndex = lastPointer.getIndex();
} else {
nextTableIndex = currentTable.length - 1;
}
int counter = 0;
while (nextTableIndex >= 0 && counter < size) {
HashEntry<K, V> nextEntry = currentTable[nextTableIndex--];
while (nextEntry != null) {
V value = nextEntry.value();
if (isValidForFetching(value, now)) {
K key = nextEntry.key();
if (key != null && hasNotBeenObserved(key, pointers)) {
entryConsumer.accept(key, value);
counter++;
}
}
nextEntry = nextEntry.next;
}
}
lastPointer.setIndex(nextTableIndex);
return pointers;
} finally {
segment.unlock();
}
}
/**
* Checks the {@code pointers} to see if we need to restart iteration on the
* current table and returns the updated pointers if necessary.
*
* @param pointers the pointers defining the state of iteration
* @param currentTableSize the current table size
* @return the updated pointers, if necessary
*/
private IterationPointer[] checkPointers(IterationPointer[] pointers, int currentTableSize) {
IterationPointer lastPointer = pointers[pointers.length - 1];
boolean iterationStarted = lastPointer.getSize() == -1;
boolean tableResized = lastPointer.getSize() != currentTableSize;
// clone pointers to avoid mutating given reference
// add new pointer if resize happened during iteration
int newLength = !iterationStarted && tableResized ? pointers.length + 1 : pointers.length;
IterationPointer[] updatedPointers = new IterationPointer[newLength];
for (int i = 0; i < pointers.length; i++) {
updatedPointers[i] = new IterationPointer(pointers[i]);
}
// reset last pointer if we haven't started iteration or there was a resize
if (iterationStarted || tableResized) {
updatedPointers[updatedPointers.length - 1] = new IterationPointer(Integer.MAX_VALUE, currentTableSize);
}
return updatedPointers;
}
/**
* Returns {@code true} if the given {@code key} has not been already observed
* (or should have been observed) with the iteration state provided by the
* {@code pointers}.
*
* @param key the key to check
* @param pointers the iteration state
* @return if the key should have already been observed by the iteration user
*/
private boolean hasNotBeenObserved(K key, IterationPointer[] pointers) {
if (pointers.length < 2) {
// there was no resize yet so we most definitely haven't observed the entry
return true;
}
int hash = hashOf(key);
// check only the pointers up to the last, we haven't observed it with the last pointer
for (int i = 0; i < pointers.length - 1; i++) {
IterationPointer iterationPointer = pointers[i];
int tableSize = iterationPointer.getSize();
int tableIndex = iterationPointer.getIndex();
int index = hash & (tableSize - 1);
if (index > tableIndex) {
// entry would have been located after in the table on the given size
// so we have observed it
return false;
}
}
return true;
}
protected boolean isValidForFetching(V value, long now) {
if (value instanceof Expirable) {
return !((Expirable) value).isExpiredAt(now);
}
return true;
}
/**
* Entry to define keys and values for sampling.
*
* @param <K> type of key
* @param <V> type of value
*/
public static class SamplingEntry<K, V> {
protected final K key;
protected final V value;
public SamplingEntry(K key, V value) {
this.key = key;
this.value = value;
}
public K getEntryKey() {
return key;
}
public V getEntryValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof SamplingEntry)) {
return false;
}
@SuppressWarnings("unchecked")
SamplingEntry e = (SamplingEntry) o;
return Objects.equals(key, e.key) && Objects.equals(value, e.value);
}
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode())
^ (value == null ? 0 : value.hashCode());
}
public String toString() {
return key + "=" + value;
}
}
protected <E extends SamplingEntry> E createSamplingEntry(K key, V value) {
return (E) new SamplingEntry(key, value);
}
/**
* Gets and returns samples as <code>sampleCount</code>.
*
* @param sampleCount Count of samples
* @return the sampled {@link SamplingEntry} list
*/
public <E extends SamplingEntry> Iterable<E> getRandomSamples(int sampleCount) {
if (sampleCount < 0) {
throw new IllegalArgumentException("Sample count cannot be a negative value.");
}
if (sampleCount == 0 || size() == 0) {
return Collections.EMPTY_LIST;
}
return new LazySamplingEntryIterableIterator<>(sampleCount);
}
/**
* Not thread safe
*/
private final class LazySamplingEntryIterableIterator<E extends SamplingEntry> implements Iterable<E>, Iterator<E> {
private final int maxEntryCount;
private final int randomNumber;
private final int firstSegmentIndex;
private int currentSegmentIndex;
private int currentBucketIndex;
private HashEntry<K, V> mostRecentlyReturnedEntry;
private int returnedEntryCount;
private boolean reachedToEnd;
private E currentSample;
private LazySamplingEntryIterableIterator(int maxEntryCount) {
this.maxEntryCount = maxEntryCount;
this.randomNumber = ThreadLocalRandomProvider.get().nextInt(Integer.MAX_VALUE);
this.firstSegmentIndex = randomNumber % segments.length;
this.currentSegmentIndex = firstSegmentIndex;
this.currentBucketIndex = -1;
}
@Override
public Iterator<E> iterator() {
return this;
}
/**
* Originally taken by Jaromir Hamala's implementation and changed as incremental implementation.
* So kudos to Jaromir :)
*/
@SuppressWarnings({"checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity"})
private void iterate() {
if (returnedEntryCount >= maxEntryCount || reachedToEnd) {
currentSample = null;
return;
}
do {
Segment<K, V> segment = segments[currentSegmentIndex];
if (segment != null) {
HashEntry<K, V>[] table = segment.table;
// Pick up a starting point
int firstBucketIndex = randomNumber % table.length;
// If current bucket index is not initialized yet, initialize it with starting point
if (currentBucketIndex == -1) {
currentBucketIndex = firstBucketIndex;
}
do {
// If current entry is not initialized yet, initialize it
if (mostRecentlyReturnedEntry == null) {
mostRecentlyReturnedEntry = table[currentBucketIndex];
} else {
mostRecentlyReturnedEntry = mostRecentlyReturnedEntry.next;
}
while (mostRecentlyReturnedEntry != null) {
V value = mostRecentlyReturnedEntry.value();
K key = mostRecentlyReturnedEntry.key();
if (isValidForSampling(key, value)) {
currentSample = createSamplingEntry(key, value);
// If we reached end of entries, advance current bucket index
returnedEntryCount++;
return;
}
mostRecentlyReturnedEntry = mostRecentlyReturnedEntry.next;
}
// Advance current bucket index
currentBucketIndex = ++currentBucketIndex < table.length ? currentBucketIndex : 0;
} while (currentBucketIndex != firstBucketIndex);
}
// Advance current segment index
currentSegmentIndex = ++currentSegmentIndex < segments.length ? currentSegmentIndex : 0;
// Clear current bucket index to initialize at next segment
currentBucketIndex = -1;
// Clear current entry index to initialize at next segment
mostRecentlyReturnedEntry = null;
} while (currentSegmentIndex != firstSegmentIndex);
reachedToEnd = true;
currentSample = null;
}
@Override
public boolean hasNext() {
if (currentSample == null) {
iterate();
}
return currentSample != null;
}
@Override
public E next() {
if (hasNext()) {
E returnValue = currentSample;
currentSample = null;
return returnValue;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Removing is not supported");
}
}
protected boolean isValidForSampling(K key, V value) {
return key != null && value != null;
}
}
| apache-2.0 |
DariusX/camel | components/camel-syslog/src/test/java/org/apache/camel/component/syslog/MinaDataFormatTest.java | 3582 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.syslog;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.test.AvailablePortFinder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.BeforeClass;
import org.junit.Test;
public class MinaDataFormatTest extends CamelTestSupport {
private static int serverPort;
private final int messageCount = 1;
private final String message = "<165>Aug 4 05:34:00 mymachine myproc[10]: %% It's\n time to make the do-nuts. %% Ingredients: Mix=OK, Jelly=OK #\n"
+ " Devices: Mixer=OK, Jelly_Injector=OK, Frier=OK # Transport:\n" + " Conveyer1=OK, Conveyer2=OK # %%";
@BeforeClass
public static void initPort() {
serverPort = AvailablePortFinder.getNextAvailable();
}
@Test
public void testSendingRawUDP() throws IOException, InterruptedException {
MockEndpoint mock = getMockEndpoint("mock:syslogReceiver");
MockEndpoint mock2 = getMockEndpoint("mock:syslogReceiver2");
mock.expectedMessageCount(1);
mock2.expectedMessageCount(1);
mock2.expectedBodiesReceived(message);
DatagramSocket socket = new DatagramSocket();
try {
InetAddress address = InetAddress.getByName("127.0.0.1");
for (int i = 0; i < messageCount; i++) {
byte[] data = message.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, address, serverPort);
socket.send(packet);
Thread.sleep(100);
}
} finally {
socket.close();
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
//context.setTracing(true);
DataFormat syslogDataFormat = new SyslogDataFormat();
// we setup a Syslog listener on a random port.
from("mina:udp://127.0.0.1:" + serverPort).unmarshal(syslogDataFormat).process(new Processor() {
public void process(Exchange ex) {
assertTrue(ex.getIn().getBody() instanceof SyslogMessage);
}
}).to("mock:syslogReceiver").
marshal(syslogDataFormat).to("mock:syslogReceiver2");
}
};
}
}
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/javax/management/AttributeValueExp.java | 4739 | /*
* Copyright (c) 1999, 2004, 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 javax.management;
// RI import
import javax.management.MBeanServer;
/**
* Represents attributes used as arguments to relational constraints.
* An <CODE>AttributeValueExp</CODE> may be used anywhere a <CODE>ValueExp</CODE> is required.
*
* @since 1.5
*/
public class AttributeValueExp implements ValueExp {
/* Serial version */
private static final long serialVersionUID = -7768025046539163385L;
/**
* @serial The name of the attribute
*/
private String attr;
/**
* An <code>AttributeValueExp</code> with a null attribute.
* @deprecated An instance created with this constructor cannot be
* used in a query.
*/
@Deprecated
public AttributeValueExp() {
}
/**
* Creates a new <CODE>AttributeValueExp</CODE> representing the
* specified object attribute, named attr.
*
* @param attr the name of the attribute whose value is the value
* of this {@link ValueExp}.
*/
public AttributeValueExp(String attr) {
this.attr = attr;
}
/**
* Returns a string representation of the name of the attribute.
*
* @return the attribute name.
*/
public String getAttributeName() {
return attr;
}
/**
* Applies the <CODE>AttributeValueExp</CODE> on an MBean.
*
* @param name The name of the MBean on which the <CODE>AttributeValueExp</CODE> will be applied.
*
* @return The <CODE>ValueExp</CODE>.
*
* @exception BadAttributeValueExpException
* @exception InvalidApplicationException
* @exception BadStringOperationException
* @exception BadBinaryOpValueExpException
*
*/
public ValueExp apply(ObjectName name) throws BadStringOperationException, BadBinaryOpValueExpException,
BadAttributeValueExpException, InvalidApplicationException {
Object result = getAttribute(name);
if (result instanceof Number) {
return new NumericValueExp((Number)result);
} else if (result instanceof String) {
return new StringValueExp((String)result);
} else if (result instanceof Boolean) {
return new BooleanValueExp((Boolean)result);
} else {
throw new BadAttributeValueExpException(result);
}
}
/**
* Returns the string representing its value.
*/
public String toString() {
return attr;
}
/**
* Sets the MBean server on which the query is to be performed.
*
* @param s The MBean server on which the query is to be performed.
*/
/* There is no need for this method, because if a query is being
evaluted an AttributeValueExp can only appear inside a QueryExp,
and that QueryExp will itself have done setMBeanServer. */
public void setMBeanServer(MBeanServer s) {
}
/**
* Return the value of the given attribute in the named MBean.
* If the attempt to access the attribute generates an exception,
* return null.
*
* @param name the name of the MBean whose attribute is to be returned.
*
* @return the value of the attribute, or null if it could not be
* obtained.
*/
protected Object getAttribute(ObjectName name) {
try {
// Get the value from the MBeanServer
MBeanServer server = QueryEval.getMBeanServer();
return server.getAttribute(name, attr);
} catch (Exception re) {
return null;
}
}
}
| apache-2.0 |
nutzam/nutz | test/org/nutz/dao/test/normal/mysql/StudentJson.java | 1183 | package org.nutz.dao.test.normal.mysql;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.nutz.dao.entity.annotation.ColDefine;
import org.nutz.dao.entity.annotation.ColType;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.json.Json;
import org.nutz.lang.util.NutMap;
@Table("t_mysql_student_json")
public class StudentJson extends Student {
public StudentJson() {}
public StudentJson(ResultSet rs) throws SQLException {
this.setId(rs.getInt("id"));
this.data = NutMap.WRAP(rs.getString("data"));
this.studentResult = Json.fromJson(StudentResult.class, rs.getString("studentResult"));
}
@ColDefine(customType = "json", type = ColType.MYSQL_JSON)
private NutMap data;
@ColDefine(customType = "json", type = ColType.MYSQL_JSON)
private StudentResult studentResult;
public NutMap getData() {
return data;
}
public void setData(NutMap data) {
this.data = data;
}
public StudentResult getStudentResult() {
return studentResult;
}
public void setStudentResult(StudentResult studentResult) {
this.studentResult = studentResult;
}
}
| apache-2.0 |
lsmall/flowable-engine | modules/flowable-engine/src/main/java/org/flowable/engine/impl/event/logger/handler/TaskCreatedEventHandler.java | 1422 | /* 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.flowable.engine.impl.event.logger.handler;
import java.util.Map;
import org.flowable.common.engine.api.delegate.event.FlowableEntityEvent;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.EventLogEntryEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
/**
* @author Joram Barrez
*/
public class TaskCreatedEventHandler extends AbstractTaskEventHandler {
@Override
public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
TaskEntity task = (TaskEntity) ((FlowableEntityEvent) event).getEntity();
Map<String, Object> data = handleCommonTaskFields(task);
return createEventLogEntry(task.getProcessDefinitionId(), task.getProcessInstanceId(), task.getExecutionId(), task.getId(), data);
}
}
| apache-2.0 |
electrum/presto | core/trino-main/src/main/java/io/trino/sql/planner/iterative/rule/EliminateCrossJoins.java | 8572 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.sql.planner.iterative.rule;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.trino.Session;
import io.trino.matching.Captures;
import io.trino.matching.Pattern;
import io.trino.metadata.Metadata;
import io.trino.sql.analyzer.FeaturesConfig.JoinReorderingStrategy;
import io.trino.sql.planner.PlanNodeIdAllocator;
import io.trino.sql.planner.Symbol;
import io.trino.sql.planner.TypeAnalyzer;
import io.trino.sql.planner.iterative.Rule;
import io.trino.sql.planner.optimizations.joins.JoinGraph;
import io.trino.sql.planner.plan.FilterNode;
import io.trino.sql.planner.plan.JoinNode;
import io.trino.sql.planner.plan.PlanNode;
import io.trino.sql.planner.plan.PlanNodeId;
import io.trino.sql.tree.Expression;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.trino.SystemSessionProperties.getJoinReorderingStrategy;
import static io.trino.sql.analyzer.FeaturesConfig.JoinReorderingStrategy.AUTOMATIC;
import static io.trino.sql.analyzer.FeaturesConfig.JoinReorderingStrategy.ELIMINATE_CROSS_JOINS;
import static io.trino.sql.planner.iterative.rule.Util.restrictOutputs;
import static io.trino.sql.planner.plan.Patterns.join;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;
public class EliminateCrossJoins
implements Rule<JoinNode>
{
private static final Pattern<JoinNode> PATTERN = join();
private final Metadata metadata;
private final TypeAnalyzer typeAnalyzer;
public EliminateCrossJoins(Metadata metadata, TypeAnalyzer typeAnalyzer)
{
this.metadata = metadata;
this.typeAnalyzer = requireNonNull(typeAnalyzer, "typeAnalyzer is null");
}
@Override
public Pattern<JoinNode> getPattern()
{
return PATTERN;
}
@Override
public boolean isEnabled(Session session)
{
// we run this for cost-based reordering also for cases when some of the tables do not have statistics
JoinReorderingStrategy joinReorderingStrategy = getJoinReorderingStrategy(session);
return joinReorderingStrategy == ELIMINATE_CROSS_JOINS || joinReorderingStrategy == AUTOMATIC;
}
@Override
public Result apply(JoinNode node, Captures captures, Context context)
{
JoinGraph joinGraph = JoinGraph.buildFrom(metadata, node, context.getLookup(), context.getIdAllocator(), context.getSession(), typeAnalyzer, context.getSymbolAllocator().getTypes());
if (joinGraph.size() < 3 || !joinGraph.isContainsCrossJoin()) {
return Result.empty();
}
List<Integer> joinOrder = getJoinOrder(joinGraph);
if (isOriginalOrder(joinOrder)) {
return Result.empty();
}
PlanNode replacement = buildJoinTree(node.getOutputSymbols(), joinGraph, joinOrder, context.getIdAllocator());
return Result.ofPlanNode(replacement);
}
public static boolean isOriginalOrder(List<Integer> joinOrder)
{
for (int i = 0; i < joinOrder.size(); i++) {
if (joinOrder.get(i) != i) {
return false;
}
}
return true;
}
/**
* Given JoinGraph determine the order of joins between graph nodes
* by traversing JoinGraph. Any graph traversal algorithm could be used
* here (like BFS or DFS), but we use PriorityQueue to preserve
* original JoinOrder as mush as it is possible. PriorityQueue returns
* next nodes to join in order of their occurrence in original Plan.
*/
public static List<Integer> getJoinOrder(JoinGraph graph)
{
ImmutableList.Builder<PlanNode> joinOrder = ImmutableList.builder();
Map<PlanNodeId, Integer> priorities = new HashMap<>();
for (int i = 0; i < graph.size(); i++) {
priorities.put(graph.getNode(i).getId(), i);
}
PriorityQueue<PlanNode> nodesToVisit = new PriorityQueue<>(
graph.size(),
comparing(node -> priorities.get(node.getId())));
Set<PlanNode> visited = new HashSet<>();
nodesToVisit.add(graph.getNode(0));
while (!nodesToVisit.isEmpty()) {
PlanNode node = nodesToVisit.poll();
if (!visited.contains(node)) {
visited.add(node);
joinOrder.add(node);
for (JoinGraph.Edge edge : graph.getEdges(node)) {
nodesToVisit.add(edge.getTargetNode());
}
}
if (nodesToVisit.isEmpty() && visited.size() < graph.size()) {
// disconnected graph, find new starting point
Optional<PlanNode> firstNotVisitedNode = graph.getNodes().stream()
.filter(graphNode -> !visited.contains(graphNode))
.findFirst();
firstNotVisitedNode.ifPresent(nodesToVisit::add);
}
}
checkState(visited.size() == graph.size());
return joinOrder.build().stream()
.map(node -> priorities.get(node.getId()))
.collect(toImmutableList());
}
public static PlanNode buildJoinTree(List<Symbol> expectedOutputSymbols, JoinGraph graph, List<Integer> joinOrder, PlanNodeIdAllocator idAllocator)
{
requireNonNull(expectedOutputSymbols, "expectedOutputSymbols is null");
requireNonNull(idAllocator, "idAllocator is null");
requireNonNull(graph, "graph is null");
joinOrder = ImmutableList.copyOf(requireNonNull(joinOrder, "joinOrder is null"));
checkArgument(joinOrder.size() >= 2);
PlanNode result = graph.getNode(joinOrder.get(0));
Set<PlanNodeId> alreadyJoinedNodes = new HashSet<>();
alreadyJoinedNodes.add(result.getId());
for (int i = 1; i < joinOrder.size(); i++) {
PlanNode rightNode = graph.getNode(joinOrder.get(i));
alreadyJoinedNodes.add(rightNode.getId());
ImmutableList.Builder<JoinNode.EquiJoinClause> criteria = ImmutableList.builder();
for (JoinGraph.Edge edge : graph.getEdges(rightNode)) {
PlanNode targetNode = edge.getTargetNode();
if (alreadyJoinedNodes.contains(targetNode.getId())) {
criteria.add(new JoinNode.EquiJoinClause(
edge.getTargetSymbol(),
edge.getSourceSymbol()));
}
}
result = new JoinNode(
idAllocator.getNextId(),
JoinNode.Type.INNER,
result,
rightNode,
criteria.build(),
result.getOutputSymbols(),
rightNode.getOutputSymbols(),
false,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
Optional.empty(),
ImmutableMap.of(),
Optional.empty());
}
List<Expression> filters = graph.getFilters();
for (Expression filter : filters) {
result = new FilterNode(
idAllocator.getNextId(),
result,
filter);
}
// If needed, introduce a projection to constrain the outputs to what was originally expected
// Some nodes are sensitive to what's produced (e.g., DistinctLimit node)
return restrictOutputs(idAllocator, result, ImmutableSet.copyOf(expectedOutputSymbols)).orElse(result);
}
}
| apache-2.0 |
ehsan/js-symbolic-executor | cvc3/java/src/cvc3/CLException.java | 232 | package cvc3;
import java.util.*;
/** mirrors CVC3::CLException */
class CLException extends Cvc3Exception {
private final static long serialVersionUID = 1L;
public CLException(String message) {
super(message);
}
}
| apache-2.0 |
trvajjala/interview-preparation | jsoup-practice/Section06/src/main/java/com/petehouston/jsoup/LogUtils.java | 288 | package com.petehouston.jsoup;
public class LogUtils {
public static final boolean LOG_MODE = true;
public static void d(String clsName, String methodName, String content) {
if(LOG_MODE) {
System.out.println(String.format("[%s:%s] %s", clsName, methodName, content));
}
}
}
| apache-2.0 |
davinash/geode | geode-junit/src/main/java/org/apache/geode/cache/query/Utils.java | 2978 | /*
* 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.
*/
/*
* Utils.java
*
* Created on March 11, 2005, 12:34 PM
*/
package org.apache.geode.cache.query;
import java.util.Collection;
import java.util.Iterator;
import parReg.query.unittest.NewPortfolio;
import org.apache.geode.cache.query.data.Portfolio;
import org.apache.geode.cache.query.data.PortfolioData;
import org.apache.geode.cache.query.data.Position;
public class Utils {
public static String printResult(Object r) {
StringBuffer sb = new StringBuffer();
sb.append("Search Results\n");
if (r == null) {
sb.append("Result is NULL");
return sb.toString();
} else if (r == QueryService.UNDEFINED) {
sb.append("Result is UNDEFINED");
return sb.toString();
}
sb.append("Type = " + r.getClass().getName()).append("\n");
if (r instanceof Collection) {
sb.append("Size = " + ((Collection) r).size() + "\n");
int cnt = 1;
Iterator iter = ((Collection) r).iterator();
while (iter.hasNext()) {
Object value = iter.next();
sb.append((cnt++) + " type = " + value.getClass().getName()).append("\n");
sb.append(" " + value + "\n");
}
} else
sb.append(r);
return sb.toString();
}
/**
* This function <br>
* 1. The Creates an array of PortfolioData objects
*
* @return PortFolioData Objects
*/
public static PortfolioData[] createPortfolioData(final int cnt, final int cntDest) {
PortfolioData[] portfolio = new PortfolioData[cntDest];
for (int k = cnt; k < cntDest; k++) {
portfolio[k] = new PortfolioData(k);
}
return portfolio;
}
public static Portfolio[] createPortfoliosAndPositions(int count) {
Position.cnt = 0; // reset Portfolio counter
Portfolio[] portfolios = new Portfolio[count];
for (int i = 0; i < count; i++) {
portfolios[i] = new Portfolio(i);
}
return portfolios;
}
public static NewPortfolio[] createNewPortfoliosAndPositions(int count) {
Position.cnt = 0; // reset Portfolio counter
NewPortfolio[] portfolios = new NewPortfolio[count];
for (int i = 0; i < count; i++) {
portfolios[i] = new NewPortfolio("" + i, i);
}
return portfolios;
}
}
| apache-2.0 |
gingerwizard/elasticsearch | server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesUsageAction.java | 3874 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.rest.action.admin.cluster;
import org.elasticsearch.action.admin.cluster.node.usage.NodesUsageRequest;
import org.elasticsearch.action.admin.cluster.node.usage.NodesUsageResponse;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.RestActions;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestNodesUsageAction extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_nodes/usage"),
new Route(GET, "/_nodes/{nodeId}/usage"),
new Route(GET, "/_nodes/usage/{metric}"),
new Route(GET, "/_nodes/{nodeId}/usage/{metric}"));
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
Set<String> metrics = Strings.tokenizeByCommaToSet(request.param("metric", "_all"));
NodesUsageRequest nodesUsageRequest = new NodesUsageRequest(nodesIds);
nodesUsageRequest.timeout(request.param("timeout"));
if (metrics.size() == 1 && metrics.contains("_all")) {
nodesUsageRequest.all();
} else if (metrics.contains("_all")) {
throw new IllegalArgumentException(String.format(Locale.ROOT, "request [%s] contains _all and individual metrics [%s]",
request.path(), request.param("metric")));
} else {
nodesUsageRequest.clear();
nodesUsageRequest.restActions(metrics.contains("rest_actions"));
nodesUsageRequest.aggregations(metrics.contains("aggregations"));
}
return channel -> client.admin().cluster().nodesUsage(nodesUsageRequest, new RestBuilderListener<NodesUsageResponse>(channel) {
@Override
public RestResponse buildResponse(NodesUsageResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
RestActions.buildNodesHeader(builder, channel.request(), response);
builder.field("cluster_name", response.getClusterName().value());
response.toXContent(builder, channel.request());
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}
@Override
public String getName() {
return "nodes_usage_action";
}
@Override
public boolean canTripCircuitBreaker() {
return false;
}
}
| apache-2.0 |
dongaihua/highlight-elasticsearch | src/main/java/org/elasticsearch/index/query/BoolFilterBuilder.java | 4994 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.query;
import org.apache.lucene.search.BooleanClause;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.ToXContent.Params;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A filter that matches documents matching boolean combinations of other filters.
*
*
*/
public class BoolFilterBuilder extends BaseFilterBuilder {
private ArrayList<FilterBuilder> mustClauses = new ArrayList<FilterBuilder>();
private ArrayList<FilterBuilder> mustNotClauses = new ArrayList<FilterBuilder>();
private ArrayList<FilterBuilder> shouldClauses = new ArrayList<FilterBuilder>();
private Boolean cache;
private String cacheKey;
private String filterName;
/**
* Adds a filter that <b>must</b> appear in the matching documents.
*/
public BoolFilterBuilder must(FilterBuilder filterBuilder) {
mustClauses.add(filterBuilder);
return this;
}
/**
* Adds a filter that <b>must not</b> appear in the matching documents.
*/
public BoolFilterBuilder mustNot(FilterBuilder filterBuilder) {
mustNotClauses.add(filterBuilder);
return this;
}
/**
* Adds a filter that <i>should</i> appear in the matching documents. For a boolean filter
* with no <tt>MUST</tt> clauses one or more <code>SHOULD</code> clauses must match a document
* for the BooleanQuery to match.
*/
public BoolFilterBuilder should(FilterBuilder filterBuilder) {
shouldClauses.add(filterBuilder);
return this;
}
/**
* Adds multiple <i>must</i> filters.
*/
public BoolFilterBuilder must(FilterBuilder... filterBuilders) {
for (FilterBuilder fb : filterBuilders) {
mustClauses.add(fb);
}
return this;
}
/**
* Adds multiple <i>must not</i> filters.
*/
public BoolFilterBuilder mustNot(FilterBuilder... filterBuilders) {
for (FilterBuilder fb : filterBuilders) {
mustNotClauses.add(fb);
}
return this;
}
/**
* Adds multiple <i>should</i> filters.
*/
public BoolFilterBuilder should(FilterBuilder... filterBuilders) {
for (FilterBuilder fb : filterBuilders) {
shouldClauses.add(fb);
}
return this;
}
/**
* Sets the filter name for the filter that can be used when searching for matched_filters per hit.
*/
public BoolFilterBuilder filterName(String filterName) {
this.filterName = filterName;
return this;
}
/**
* Should the filter be cached or not. Defaults to <tt>false</tt>.
*/
public BoolFilterBuilder cache(boolean cache) {
this.cache = cache;
return this;
}
public BoolFilterBuilder cacheKey(String cacheKey) {
this.cacheKey = cacheKey;
return this;
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject("bool");
doXArrayContent("must", mustClauses, builder, params);
doXArrayContent("must_not", mustNotClauses, builder, params);
doXArrayContent("should", shouldClauses, builder, params);
if (filterName != null) {
builder.field("_name", filterName);
}
if (cache != null) {
builder.field("_cache", cache);
}
if (cacheKey != null) {
builder.field("_cache_key", cacheKey);
}
builder.endObject();
}
private void doXArrayContent(String field, List<FilterBuilder> clauses, XContentBuilder builder, Params params) throws IOException {
if (clauses.isEmpty()) {
return;
}
if (clauses.size() == 1) {
builder.field(field);
clauses.get(0).toXContent(builder, params);
} else {
builder.startArray(field);
for (FilterBuilder clause : clauses) {
clause.toXContent(builder, params);
}
builder.endArray();
}
}
} | apache-2.0 |
pperalta/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridDhtTxPrepareResponse.java | 10326 | /*
* 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.ignite.internal.processors.cache.distributed.dht;
import java.io.Externalizable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectCollection;
import org.apache.ignite.internal.GridDirectMap;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheEntryInfo;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.distributed.GridDistributedTxPrepareResponse;
import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey;
import org.apache.ignite.internal.processors.cache.version.GridCacheVersion;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
/**
* DHT transaction prepare response.
*/
public class GridDhtTxPrepareResponse extends GridDistributedTxPrepareResponse {
/** */
private static final long serialVersionUID = 0L;
/** Evicted readers. */
@GridToStringInclude
@GridDirectCollection(IgniteTxKey.class)
private Collection<IgniteTxKey> nearEvicted;
/** Future ID. */
private IgniteUuid futId;
/** Mini future ID. */
private int miniId;
/** Invalid partitions by cache ID. */
@GridDirectMap(keyType = Integer.class, valueType = int[].class)
private Map<Integer, int[]> invalidParts;
/** Preload entries. */
@GridDirectCollection(GridCacheEntryInfo.class)
private List<GridCacheEntryInfo> preloadEntries;
/**
* Empty constructor required by {@link Externalizable}.
*/
public GridDhtTxPrepareResponse() {
// No-op.
}
/**
* @param part Partition.
* @param xid Xid version.
* @param futId Future ID.
* @param miniId Mini future ID.
* @param addDepInfo Deployment info flag.
*/
public GridDhtTxPrepareResponse(
int part,
GridCacheVersion xid,
IgniteUuid futId,
int miniId,
boolean addDepInfo) {
super(part, xid, addDepInfo);
assert futId != null;
assert miniId != 0;
this.futId = futId;
this.miniId = miniId;
}
/**
* @param part Partition.
* @param xid Xid version.
* @param futId Future ID.
* @param miniId Mini future ID.
* @param err Error.
* @param addDepInfo Deployment enabled.
*/
public GridDhtTxPrepareResponse(
int part,
GridCacheVersion xid,
IgniteUuid futId,
int miniId,
Throwable err,
boolean addDepInfo) {
super(part, xid, err, addDepInfo);
assert futId != null;
assert miniId != 0;
this.futId = futId;
this.miniId = miniId;
}
/**
* @return Evicted readers.
*/
Collection<IgniteTxKey> nearEvicted() {
return nearEvicted;
}
/**
* @param nearEvicted Evicted readers.
*/
public void nearEvicted(Collection<IgniteTxKey> nearEvicted) {
this.nearEvicted = nearEvicted;
}
/**
* @return Future ID.
*/
public IgniteUuid futureId() {
return futId;
}
/**
* @return Mini future ID.
*/
public int miniId() {
return miniId;
}
/**
* @return Map from cacheId to an array of invalid partitions.
*/
Map<Integer, int[]> invalidPartitionsByCacheId() {
return invalidParts;
}
/**
* @param invalidPartsByCacheId Map from cache ID to an array of invalid partitions.
*/
public void invalidPartitionsByCacheId(Map<Integer, Set<Integer>> invalidPartsByCacheId) {
this.invalidParts = CU.convertInvalidPartitions(invalidPartsByCacheId);
}
/**
* Gets preload entries found on backup node.
*
* @return Collection of entry infos need to be preloaded.
*/
Collection<GridCacheEntryInfo> preloadEntries() {
return preloadEntries == null ? Collections.<GridCacheEntryInfo>emptyList() : preloadEntries;
}
/**
* Adds preload entry.
*
* @param info Info to add.
*/
public void addPreloadEntry(GridCacheEntryInfo info) {
assert info.cacheId() != 0;
if (preloadEntries == null)
preloadEntries = new ArrayList<>();
preloadEntries.add(info);
}
/** {@inheritDoc} */
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
super.prepareMarshal(ctx);
if (nearEvicted != null) {
for (IgniteTxKey key : nearEvicted) {
GridCacheContext cctx = ctx.cacheContext(key.cacheId());
key.prepareMarshal(cctx);
}
}
if (preloadEntries != null) {
for (GridCacheEntryInfo info : preloadEntries) {
GridCacheContext cctx = ctx.cacheContext(info.cacheId());
info.marshal(cctx);
}
}
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
if (nearEvicted != null) {
for (IgniteTxKey key : nearEvicted) {
GridCacheContext cctx = ctx.cacheContext(key.cacheId());
key.finishUnmarshal(cctx, ldr);
}
}
if (preloadEntries != null) {
for (GridCacheEntryInfo info : preloadEntries) {
GridCacheContext cctx = ctx.cacheContext(info.cacheId());
info.unmarshal(cctx, ldr);
}
}
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 10:
if (!writer.writeIgniteUuid("futId", futId))
return false;
writer.incrementState();
case 11:
if (!writer.writeMap("invalidParts", invalidParts, MessageCollectionItemType.INT, MessageCollectionItemType.INT_ARR))
return false;
writer.incrementState();
case 12:
if (!writer.writeInt("miniId", miniId))
return false;
writer.incrementState();
case 13:
if (!writer.writeCollection("nearEvicted", nearEvicted, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
case 14:
if (!writer.writeCollection("preloadEntries", preloadEntries, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 10:
futId = reader.readIgniteUuid("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 11:
invalidParts = reader.readMap("invalidParts", MessageCollectionItemType.INT, MessageCollectionItemType.INT_ARR, false);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 12:
miniId = reader.readInt("miniId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 13:
nearEvicted = reader.readCollection("nearEvicted", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
case 14:
preloadEntries = reader.readCollection("preloadEntries", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridDhtTxPrepareResponse.class);
}
/** {@inheritDoc} */
@Override public short directType() {
return 35;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 15;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDhtTxPrepareResponse.class, this,
"super", super.toString());
}
}
| apache-2.0 |
dashorst/wicket | wicket-examples/src/main/java/org/apache/wicket/examples/kittenCaptcha/WicketApplication.java | 1341 | /*
* 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.wicket.examples.kittenCaptcha;
import org.apache.wicket.Page;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application. If you want to run this application without
* deploying, run the Start class.
*
*/
public class WicketApplication extends WebApplication
{
@Override
public Class<? extends Page> getHomePage()
{
return HomePage.class;
}
@Override
protected void init()
{
super.init();
getDebugSettings().setDevelopmentUtilitiesEnabled(true);
}
}
| apache-2.0 |
paarsar/guiceberry | doc/tutorial/test/junit4/tutorial_0_basic/Example5CustomSelectorTest.java | 2750 | package junit4.tutorial_0_basic;
import static junit.framework.Assert.assertEquals;
import com.google.guiceberry.GuiceBerryEnvSelector;
import com.google.guiceberry.GuiceBerryModule;
import com.google.guiceberry.TestDescription;
import com.google.guiceberry.junit4.GuiceBerryRule;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Module;
import org.junit.Rule;
import org.junit.Test;
public class Example5CustomSelectorTest {
@Rule
public final GuiceBerryRule guiceBerry = new GuiceBerryRule(new MyGuiceBerryEnvSelector());
/**
* This selector returns FakeGuiceBerryEnv.class whenever the "testFake"
* method is executed, and RealGuiceBerryEnv.class whenever the "testReal"
* method is used.
*
* <p>Therefore, even though the testFake and testReal methods are identical,
* their server.getName()s return different values.
*
* <p>This is not necessarily a particularly useful usage of
* {@link GuiceBerryEnvSelector}s, but it makes for a nice compact tutorial
* example.
*/
private static final class MyGuiceBerryEnvSelector implements GuiceBerryEnvSelector {
public Class<? extends Module> guiceBerryEnvToUse(TestDescription testDescription) {
String name = testDescription.getName();
if (name.endsWith("testFake")) {
return FakeGuiceBerryEnv.class;
} else if (name.endsWith("testReal")) {
return RealGuiceBerryEnv.class;
} else {
throw new IllegalArgumentException();
}
}
}
/**
* The version of the Server injected depends on which GuiceBerryEnv is
* used. If the {@link FakeGuiceBerryEnv} is used, this will be the "fake". If
* the {@link RealGuiceBerryEnv} is used, this will be the "real".
*/
@Inject
private Server server;
@Test
public void testFake() throws Exception {
assertEquals("fake", server.getName());
}
@Test
public void testReal() throws Exception {
assertEquals("real", server.getName());
}
public static final class FakeGuiceBerryEnv extends AbstractModule {
@Override
protected void configure() {
install(new GuiceBerryModule());
bind(Server.class).to(FakeServer.class);
}
}
public static final class RealGuiceBerryEnv extends AbstractModule {
@Override
protected void configure() {
install(new GuiceBerryModule());
bind(Server.class).to(RealServer.class);
}
}
private interface Server {
String getName();
}
private static final class RealServer implements Server {
public String getName() {
return "real";
}
}
private static final class FakeServer implements Server {
public String getName() {
return "fake";
}
}
}
| apache-2.0 |
kingthorin/zap-extensions | addOns/pscanrulesAlpha/src/main/java/org/zaproxy/zap/extension/pscanrulesAlpha/InPageBannerInfoLeakScanRule.java | 5034 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2018 The ZAP Development Team
*
* 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.zaproxy.zap.extension.pscanrulesAlpha;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.htmlparser.jericho.Source;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpStatusCode;
import org.zaproxy.addon.commonlib.CommonAlertTag;
import org.zaproxy.zap.extension.pscan.PluginPassiveScanner;
/**
* In Page Banner Information Leak passive scan rule https://github.com/zaproxy/zaproxy/issues/178
*
* @author kingthorin+owaspzap@gmail.com
*/
public class InPageBannerInfoLeakScanRule extends PluginPassiveScanner {
private static final Logger LOGGER = LogManager.getLogger(InPageBannerInfoLeakScanRule.class);
private static final int PLUGIN_ID = 10009;
private static final String MESSAGE_PREFIX = "pscanalpha.inpagebanner.";
private static final Map<String, String> ALERT_TAGS =
CommonAlertTag.toMap(
CommonAlertTag.OWASP_2021_A05_SEC_MISCONFIG,
CommonAlertTag.OWASP_2017_A06_SEC_MISCONFIG,
CommonAlertTag.WSTG_V42_INFO_02_FINGERPRINT_WEB_SERVER);
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
long start = System.currentTimeMillis();
int statusCode = msg.getResponseHeader().getStatusCode();
// If LOW and 200 then check or if isClientError or isServerError check
if ((this.getAlertThreshold().equals(AlertThreshold.LOW)
&& (HttpStatusCode.isSuccess(statusCode) || getHelper().isPage200(msg)))
|| (getHelper().isClientError(msg) || getHelper().isServerError(msg))) {
for (BannerPattern patt : BannerPattern.values()) {
Matcher bannerMatcher = patt.getPattern().matcher(msg.getResponseBody().toString());
boolean found = bannerMatcher.find();
if (found) {
raiseAlert(
Alert.RISK_LOW, Alert.CONFIDENCE_HIGH, bannerMatcher.group(), msg, id);
break;
}
}
}
LOGGER.debug("\tScan of record {} took {} ms", id, System.currentTimeMillis() - start);
}
@Override
public int getPluginId() {
return PLUGIN_ID;
}
@Override
public String getName() {
return Constant.messages.getString(MESSAGE_PREFIX + "name");
}
@Override
public Map<String, String> getAlertTags() {
return ALERT_TAGS;
}
private void raiseAlert(int risk, int confidence, String evidence, HttpMessage msg, int id) {
newAlert()
.setRisk(risk)
.setConfidence(confidence)
.setDescription(Constant.messages.getString(MESSAGE_PREFIX + "desc"))
.setOtherInfo(Constant.messages.getString(MESSAGE_PREFIX + "other"))
.setSolution(Constant.messages.getString(MESSAGE_PREFIX + "soln"))
.setReference(Constant.messages.getString(MESSAGE_PREFIX + "refs"))
.setEvidence(evidence) // Evidence - Return the in page banner
.setCweId(200) // CWE Id: 200 - Information Exposure
.setWascId(13) // WASC Id: 13 - Information Leakage
.raise();
}
public enum BannerPattern {
TOMCAT_PATTERN(Pattern.compile("Tomcat\\/\\d\\.\\d\\.\\d{1,2}", Pattern.CASE_INSENSITIVE)),
APACHE_PATTERN(Pattern.compile("Apache\\/\\d\\.\\d\\.\\d{1,2}", Pattern.CASE_INSENSITIVE)),
NGINX_PATTERN(
Pattern.compile("nginx\\/\\d\\.\\d{1,2}\\.\\d{1,2}", Pattern.CASE_INSENSITIVE)),
JETTY_PATTERN(Pattern.compile("Jetty:\\/\\/\\d\\.\\d{1,2}", Pattern.CASE_INSENSITIVE)),
SQUID_PATTERN(Pattern.compile("squid\\/\\d\\.\\d{1,2}", Pattern.CASE_INSENSITIVE));
private Pattern pattern;
private BannerPattern(Pattern pattern) {
this.pattern = pattern;
}
public Pattern getPattern() {
return pattern;
}
}
}
| apache-2.0 |
jvz/spring-boot | spring-boot-tools/spring-boot-loader/src/test/java/org/springframework/boot/loader/archive/JarFileArchiveTests.java | 3984 | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.loader.archive;
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.springframework.boot.loader.TestJarCreator;
import org.springframework.boot.loader.archive.Archive.Entry;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link JarFileArchive}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
public class JarFileArchiveTests {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
private File rootJarFile;
private JarFileArchive archive;
private String rootJarFileUrl;
@Before
public void setup() throws Exception {
setup(false);
}
private void setup(boolean unpackNested) throws Exception {
this.rootJarFile = this.temporaryFolder.newFile();
this.rootJarFileUrl = this.rootJarFile.toURI().toString();
TestJarCreator.createTestJar(this.rootJarFile, unpackNested);
this.archive = new JarFileArchive(this.rootJarFile);
}
@Test
public void getManifest() throws Exception {
assertThat(this.archive.getManifest().getMainAttributes().getValue("Built-By"))
.isEqualTo("j1");
}
@Test
public void getEntries() throws Exception {
Map<String, Archive.Entry> entries = getEntriesMap(this.archive);
assertThat(entries.size()).isEqualTo(10);
}
@Test
public void getUrl() throws Exception {
URL url = this.archive.getUrl();
assertThat(url.toString()).isEqualTo("jar:" + this.rootJarFileUrl + "!/");
}
@Test
public void getNestedArchive() throws Exception {
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString())
.isEqualTo("jar:" + this.rootJarFileUrl + "!/nested.jar!/");
}
@Test
public void getNestedUnpackedArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
Archive nested = this.archive.getNestedArchive(entry);
assertThat(nested.getUrl().toString()).startsWith("file:");
assertThat(nested.getUrl().toString()).endsWith("/nested.jar");
}
@Test
public void unpackedLocationsAreUniquePerArchive() throws Exception {
setup(true);
Entry entry = getEntriesMap(this.archive).get("nested.jar");
URL firstNested = this.archive.getNestedArchive(entry).getUrl();
setup(true);
entry = getEntriesMap(this.archive).get("nested.jar");
URL secondNested = this.archive.getNestedArchive(entry).getUrl();
assertThat(secondNested).isNotEqualTo(firstNested);
}
@Test
public void unpackedLocationsFromSameArchiveShareSameParent() throws Exception {
setup(true);
File nested = new File(this.archive
.getNestedArchive(getEntriesMap(this.archive).get("nested.jar")).getUrl()
.toURI());
File anotherNested = new File(
this.archive
.getNestedArchive(
getEntriesMap(this.archive).get("another-nested.jar"))
.getUrl().toURI());
assertThat(nested.getParent()).isEqualTo(anotherNested.getParent());
}
private Map<String, Archive.Entry> getEntriesMap(Archive archive) {
Map<String, Archive.Entry> entries = new HashMap<String, Archive.Entry>();
for (Archive.Entry entry : archive) {
entries.put(entry.getName(), entry);
}
return entries;
}
}
| apache-2.0 |
pradheeps/flyway | flyway-core/src/test/java/org/flywaydb/core/internal/dbsupport/sqlserver/SQLServerSqlStatementBuilderSmallTest.java | 1931 | /*
* Copyright 2010-2017 Boxfuse GmbH
*
* 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.flywaydb.core.internal.dbsupport.sqlserver;
import org.flywaydb.core.internal.util.StringUtils;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Test for SQLServerSqlStatementBuilder.
*/
public class SQLServerSqlStatementBuilderSmallTest {
/**
* Class under test.
*/
private SQLServerSqlStatementBuilder statementBuilder = new SQLServerSqlStatementBuilder();
@Test
public void go() {
String sqlScriptSource = "DROP VIEW dbo.TESTVIEW\n" +
"GO\n";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
@Test
public void likeNoSpace() {
String sqlScriptSource = "ALTER TRIGGER CUSTOMER_INSERT ON CUSTOMER AFTER\n" +
"INSERT AS\n" +
"BEGIN\n" +
" SELECT TOP 1 1 FROM CUSTOMER WHERE [name] LIKE'%test';\n" +
"END\n" +
"GO";
String[] lines = StringUtils.tokenizeToStringArray(sqlScriptSource, "\n");
for (String line : lines) {
statementBuilder.addLine(line);
}
assertTrue(statementBuilder.isTerminated());
}
} | apache-2.0 |
ueshin/apache-flink | flink-end-to-end-tests/flink-high-parallelism-iterations-test/src/main/java/org/apache/flink/batch/HighParallelismIterationsTestProgram.java | 2981 | /*
* 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.flink.batch;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.aggregation.Aggregations;
import org.apache.flink.api.java.io.DiscardingOutputFormat;
import org.apache.flink.api.java.operators.DeltaIteration;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.examples.java.graph.ConnectedComponents;
import org.apache.flink.examples.java.graph.util.ConnectedComponentsData;
/**
* This test starts a cluster with 100 task managers and runs connected components
* with a parallelism of 100.
*/
public class HighParallelismIterationsTestProgram {
public static void main(String[] args) throws Exception {
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
env.getConfig().disableSysoutLogging();
// read vertex and edge data
DataSet<Long> vertices = ConnectedComponentsData.getDefaultVertexDataSet(env)
.rebalance();
DataSet<Tuple2<Long, Long>> edges = ConnectedComponentsData.getDefaultEdgeDataSet(env)
.rebalance()
.flatMap(new ConnectedComponents.UndirectEdge());
// assign the initial components (equal to the vertex id)
DataSet<Tuple2<Long, Long>> verticesWithInitialId = vertices
.map(new ConnectedComponents.DuplicateValue<>());
// open a delta iteration
DeltaIteration<Tuple2<Long, Long>, Tuple2<Long, Long>> iteration =
verticesWithInitialId.iterateDelta(verticesWithInitialId, 100, 0);
// apply the step logic: join with the edges, select the minimum neighbor,
// update if the component of the candidate is smaller
DataSet<Tuple2<Long, Long>> changes = iteration.getWorkset().join(edges)
.where(0).equalTo(0)
.with(new ConnectedComponents.NeighborWithComponentIDJoin())
.groupBy(0).aggregate(Aggregations.MIN, 1)
.join(iteration.getSolutionSet())
.where(0).equalTo(0)
.with(new ConnectedComponents.ComponentIdFilter());
// close the delta iteration (delta and new workset are identical)
DataSet<Tuple2<Long, Long>> result = iteration.closeWith(changes, changes);
result.output(new DiscardingOutputFormat<>());
env.execute();
}
}
| apache-2.0 |
royclarkson/spring-boot | spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/ReactiveHealthIndicatorRegistryFactoryTests.java | 2122 | /*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.health;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ReactiveHealthIndicatorRegistryFactory}.
*
* @author Stephane Nicoll
*/
@Deprecated
class ReactiveHealthIndicatorRegistryFactoryTests {
private static final Health UP = new Health.Builder().status(Status.UP).build();
private static final Health DOWN = new Health.Builder().status(Status.DOWN).build();
private final ReactiveHealthIndicatorRegistryFactory factory = new ReactiveHealthIndicatorRegistryFactory();
@Test
void defaultHealthIndicatorNameFactory() {
ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry(
Collections.singletonMap("myHealthIndicator", () -> Mono.just(UP)), null);
assertThat(registry.getAll()).containsOnlyKeys("my");
}
@Test
void healthIndicatorIsAdapted() {
ReactiveHealthIndicatorRegistry registry = this.factory.createReactiveHealthIndicatorRegistry(
Collections.singletonMap("test", () -> Mono.just(UP)), Collections.singletonMap("regular", () -> DOWN));
assertThat(registry.getAll()).containsOnlyKeys("test", "regular");
StepVerifier.create(registry.get("regular").health()).consumeNextWith((h) -> {
assertThat(h.getStatus()).isEqualTo(Status.DOWN);
assertThat(h.getDetails()).isEmpty();
}).verifyComplete();
}
}
| apache-2.0 |
WIgor/hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestHostsFileReader.java | 11248 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.*;
import static org.junit.Assert.*;
/*
* Test for HostsFileReader.java
*
*/
public class TestHostsFileReader {
// Using /test/build/data/tmp directory to store temprory files
final String HOSTS_TEST_DIR = GenericTestUtils.getTestDir().getAbsolutePath();
File EXCLUDES_FILE = new File(HOSTS_TEST_DIR, "dfs.exclude");
File INCLUDES_FILE = new File(HOSTS_TEST_DIR, "dfs.include");
String excludesFile = HOSTS_TEST_DIR + "/dfs.exclude";
String includesFile = HOSTS_TEST_DIR + "/dfs.include";
private String excludesXmlFile = HOSTS_TEST_DIR + "/dfs.exclude.xml";
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
// Delete test files after running tests
EXCLUDES_FILE.delete();
INCLUDES_FILE.delete();
}
/*
* 1.Create dfs.exclude,dfs.include file
* 2.Write host names per line
* 3.Write comments starting with #
* 4.Close file
* 5.Compare if number of hosts reported by HostsFileReader
* are equal to the number of hosts written
*/
@Test
public void testHostsFileReader() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.write("#DFS-Hosts-excluded\n");
efw.write("somehost1\n");
efw.write("#This-is-comment\n");
efw.write("somehost2\n");
efw.write("somehost3 # host3\n");
efw.write("somehost4\n");
efw.write("somehost4 somehost5\n");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.write("somehost1\n");
ifw.write("somehost2\n");
ifw.write("somehost3\n");
ifw.write("#This-is-comment\n");
ifw.write("somehost4 # host4\n");
ifw.write("somehost4 somehost5\n");
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
assertEquals(5, includesLen);
assertEquals(5, excludesLen);
assertTrue(hfp.getHosts().contains("somehost5"));
assertFalse(hfp.getHosts().contains("host3"));
assertTrue(hfp.getExcludedHosts().contains("somehost5"));
assertFalse(hfp.getExcludedHosts().contains("host4"));
// test for refreshing hostreader wit new include/exclude host files
String newExcludesFile = HOSTS_TEST_DIR + "/dfs1.exclude";
String newIncludesFile = HOSTS_TEST_DIR + "/dfs1.include";
efw = new FileWriter(newExcludesFile);
ifw = new FileWriter(newIncludesFile);
efw.write("#DFS-Hosts-excluded\n");
efw.write("node1\n");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.write("node2\n");
ifw.close();
hfp.refresh(newIncludesFile, newExcludesFile);
assertTrue(hfp.getExcludedHosts().contains("node1"));
assertTrue(hfp.getHosts().contains("node2"));
Set<String> hostsList = new HashSet<String>();
Set<String> excludeList = new HashSet<String>();
hfp.getHostDetails(hostsList, excludeList);
assertTrue(excludeList.contains("node1"));
assertTrue(hostsList.contains("node2"));
}
/*
* Test creating a new HostsFileReader with nonexistent files
*/
@Test
public void testCreateHostFileReaderWithNonexistentFile() throws Exception {
try {
new HostsFileReader(
HOSTS_TEST_DIR + "/doesnt-exist",
HOSTS_TEST_DIR + "/doesnt-exist");
Assert.fail("Should throw FileNotFoundException");
} catch (FileNotFoundException ex) {
// Exception as expected
}
}
/*
* Test refreshing an existing HostsFileReader with an includes file that no longer exists
*/
@Test
public void testRefreshHostFileReaderWithNonexistentFile() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.close();
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
assertTrue(INCLUDES_FILE.delete());
try {
hfp.refresh();
Assert.fail("Should throw FileNotFoundException");
} catch (FileNotFoundException ex) {
// Exception as expected
}
}
/*
* Test for null file
*/
@Test
public void testHostFileReaderWithNull() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.close();
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
// TestCase1: Check if lines beginning with # are ignored
assertEquals(0, includesLen);
assertEquals(0, excludesLen);
// TestCase2: Check if given host names are reported by getHosts and
// getExcludedHosts
assertFalse(hfp.getHosts().contains("somehost5"));
assertFalse(hfp.getExcludedHosts().contains("somehost5"));
}
/*
* Check if only comments can be written to hosts file
*/
@Test
public void testHostFileReaderWithCommentsOnly() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.write("#DFS-Hosts-excluded\n");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
assertEquals(0, includesLen);
assertEquals(0, excludesLen);
assertFalse(hfp.getHosts().contains("somehost5"));
assertFalse(hfp.getExcludedHosts().contains("somehost5"));
}
/*
* Test if spaces are allowed in host names
*/
@Test
public void testHostFileReaderWithSpaces() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.write("#DFS-Hosts-excluded\n");
efw.write(" somehost somehost2");
efw.write(" somehost3 # somehost4");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.write(" somehost somehost2");
ifw.write(" somehost3 # somehost4");
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
assertEquals(3, includesLen);
assertEquals(3, excludesLen);
assertTrue(hfp.getHosts().contains("somehost3"));
assertFalse(hfp.getHosts().contains("somehost5"));
assertFalse(hfp.getHosts().contains("somehost4"));
assertTrue(hfp.getExcludedHosts().contains("somehost3"));
assertFalse(hfp.getExcludedHosts().contains("somehost5"));
assertFalse(hfp.getExcludedHosts().contains("somehost4"));
}
/*
* Test if spaces , tabs and new lines are allowed
*/
@Test
public void testHostFileReaderWithTabs() throws Exception {
FileWriter efw = new FileWriter(excludesFile);
FileWriter ifw = new FileWriter(includesFile);
efw.write("#DFS-Hosts-excluded\n");
efw.write(" \n");
efw.write(" somehost \t somehost2 \n somehost4");
efw.write(" somehost3 \t # somehost5");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.write(" \n");
ifw.write(" somehost \t somehost2 \n somehost4");
ifw.write(" somehost3 \t # somehost5");
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
assertEquals(4, includesLen);
assertEquals(4, excludesLen);
assertTrue(hfp.getHosts().contains("somehost2"));
assertFalse(hfp.getHosts().contains("somehost5"));
assertTrue(hfp.getExcludedHosts().contains("somehost2"));
assertFalse(hfp.getExcludedHosts().contains("somehost5"));
}
/*
* Test if timeout values are provided in HostFile
*/
@Test
public void testHostFileReaderWithTimeout() throws Exception {
FileWriter efw = new FileWriter(excludesXmlFile);
FileWriter ifw = new FileWriter(includesFile);
efw.write("<?xml version=\"1.0\"?>\n");
efw.write("<!-- yarn.nodes.exclude -->\n");
efw.write("<hosts>\n");
efw.write("<host><name>host1</name></host>\n");
efw.write("<host><name>host2</name><timeout>123</timeout></host>\n");
efw.write("<host><name>host3</name><timeout>-1</timeout></host>\n");
efw.write("<host><name>10000</name></host>\n");
efw.write("<host><name>10001</name><timeout>123</timeout></host>\n");
efw.write("<host><name>10002</name><timeout>-1</timeout></host>\n");
efw.write("<host><name>host4,host5, host6</name>" +
"<timeout>1800</timeout></host>\n");
efw.write("</hosts>\n");
efw.close();
ifw.write("#Hosts-in-DFS\n");
ifw.write(" \n");
ifw.write(" somehost \t somehost2 \n somehost4");
ifw.write(" somehost3 \t # somehost5");
ifw.close();
HostsFileReader hfp = new HostsFileReader(includesFile, excludesXmlFile);
int includesLen = hfp.getHosts().size();
int excludesLen = hfp.getExcludedHosts().size();
assertEquals(4, includesLen);
assertEquals(9, excludesLen);
Set<String> includes = new HashSet<String>();
Map<String, Integer> excludes = new HashMap<String, Integer>();
hfp.getHostDetails(includes, excludes);
assertTrue(excludes.containsKey("host1"));
assertTrue(excludes.containsKey("host2"));
assertTrue(excludes.containsKey("host3"));
assertTrue(excludes.containsKey("10000"));
assertTrue(excludes.containsKey("10001"));
assertTrue(excludes.containsKey("10002"));
assertTrue(excludes.containsKey("host4"));
assertTrue(excludes.containsKey("host5"));
assertTrue(excludes.containsKey("host6"));
assertTrue(excludes.get("host1") == null);
assertTrue(excludes.get("host2") == 123);
assertTrue(excludes.get("host3") == -1);
assertTrue(excludes.get("10000") == null);
assertTrue(excludes.get("10001") == 123);
assertTrue(excludes.get("10002") == -1);
assertTrue(excludes.get("host4") == 1800);
assertTrue(excludes.get("host5") == 1800);
assertTrue(excludes.get("host6") == 1800);
}
}
| apache-2.0 |
hekonsek/fabric8 | sandbox/itests/common/src/main/java/io/fabric8/itests/support/WaitForProvisionTask.java | 2062 | /**
* Copyright 2005-2014 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.itests.support;
import io.fabric8.api.Container;
import java.util.concurrent.Callable;
/**
* A {@link Callable} that waits for the {@link Container} to provision.
*/
public class WaitForProvisionTask implements Callable<Boolean> {
private final Long provisionTimeOut;
private final Container container;
private final String status;
public WaitForProvisionTask(Container container, String status, Long provisionTimeOut) {
this.provisionTimeOut = provisionTimeOut;
this.container = container;
this.status = status;
}
@Override
public Boolean call() throws Exception {
for (long t = 0; (!isComplete(container, status) && t < provisionTimeOut); t += 2000L) {
if (container.getProvisionException() != null) {
return false;
}
Thread.sleep(2000L);
System.out.println("Container:" + container.getId() + " Alive:" + container.isAlive() + " Status:" + container.getProvisionStatus() + " SSH URL:" + container.getSshUrl());
}
if (!isComplete(container, status)) {
return false;
}
return true;
}
private boolean isComplete(Container container, String status) {
return container.isAlive()
&& (container.getProvisionStatus().equals(status) || !container.isManaged())
&& container.getSshUrl() != null;
}
}
| apache-2.0 |
gstevey/gradle | subprojects/dependency-management/src/main/java/org/gradle/api/internal/artifacts/configurations/TasksFromProjectDependencies.java | 2340 | /*
* Copyright 2014 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.internal.artifacts.configurations;
import org.gradle.api.Task;
import org.gradle.api.artifacts.DependencySet;
import org.gradle.api.artifacts.ProjectDependency;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.internal.tasks.AbstractTaskDependency;
import org.gradle.api.internal.tasks.TaskDependencyResolveContext;
import org.gradle.initialization.ProjectAccessListener;
import java.util.Set;
class TasksFromProjectDependencies extends AbstractTaskDependency {
private final String taskName;
private final DependencySet dependencies;
private final ProjectAccessListener projectAccessListener;
public TasksFromProjectDependencies(String taskName, DependencySet dependencies, ProjectAccessListener projectAccessListener) {
this.taskName = taskName;
this.dependencies = dependencies;
this.projectAccessListener = projectAccessListener;
}
@Override
public void visitDependencies(TaskDependencyResolveContext context) {
resolveProjectDependencies(context, dependencies.withType(ProjectDependency.class));
}
void resolveProjectDependencies(TaskDependencyResolveContext context, Set<ProjectDependency> projectDependencies) {
for (ProjectDependency projectDependency : projectDependencies) {
projectAccessListener.beforeResolvingProjectDependency((ProjectInternal) projectDependency.getDependencyProject());
Task nextTask = projectDependency.getDependencyProject().getTasks().findByName(taskName);
if (nextTask != null) {
context.add(nextTask);
}
}
}
public String getTaskName() {
return taskName;
}
}
| apache-2.0 |
gilberto-torrezan/gwt-material | gwt-material/src/main/java/gwt/material/design/client/constants/WavesType.java | 1440 | package gwt.material.design.client.constants;
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 GwtMaterialDesign
* %%
* 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.
* #L%
*/
import com.google.gwt.dom.client.Style;
import gwt.material.design.client.base.helper.EnumHelper;
/**
* @author Ben DOl
*/
public enum WavesType implements Type, Style.HasCssName {
DEFAULT("waves-default"),
LIGHT("waves-light"),
RED("waves-red"),
YELLOW("waves-yellow"),
ORANGE("waves-orange"),
PURPLE("waves-purple"),
GREEN("waves-green"),
TEAL("waves-teal");
private final String cssClass;
WavesType(final String cssClass) {
this.cssClass = cssClass;
}
@Override
public String getCssName() {
return cssClass;
}
public static WavesType fromStyleName(final String styleName) {
return EnumHelper.fromStyleName(styleName, WavesType.class, DEFAULT);
}
}
| apache-2.0 |
eayun/ovirt-engine | backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/AddNetworkVDSCommand.java | 4857 | package org.ovirt.engine.core.vdsbroker.vdsbroker;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.errors.EngineError;
import org.ovirt.engine.core.common.vdscommands.NetworkVdsmVDSCommandParameters;
import org.ovirt.engine.core.utils.NetworkUtils;
import org.ovirt.engine.core.utils.transaction.NoOpTransactionCompletionListener;
public class AddNetworkVDSCommand<P extends NetworkVdsmVDSCommandParameters> extends VdsBrokerCommand<P> {
public AddNetworkVDSCommand(P parameters) {
super(parameters);
}
@Override
protected void executeVdsBrokerCommand() {
registerRollbackHandler(new CustomTransactionCompletionListener());
String networkName = (getParameters().getNetworkName() == null) ? "" : getParameters()
.getNetworkName();
String vlanId = (getParameters().getVlanId() != null) ? getParameters().getVlanId().toString()
: "";
String bond = (getParameters().getBondName() == null) ? "" : getParameters().getBondName();
String[] nics = (getParameters().getNics() == null) ? new String[] {} : getParameters().getNics();
Map<String, String> options = new HashMap<String, String>();
switch (getParameters().getBootProtocol()) {
case DHCP:
options.put(VdsProperties.BOOT_PROTOCOL, VdsProperties.DHCP);
break;
case STATIC_IP:
if (!StringUtils.isEmpty(getParameters().getInetAddr())) {
options.put(VdsProperties.IP_ADDRESS, getParameters().getInetAddr());
}
if (!StringUtils.isEmpty(getParameters().getNetworkMask())) {
options.put(VdsProperties.NETMASK, getParameters().getNetworkMask());
}
if (!StringUtils.isEmpty(getParameters().getGateway())) {
options.put(VdsProperties.GATEWAY, getParameters().getGateway());
}
break;
default:
break;
}
options.put(VdsProperties.STP, (getParameters().getStp()) ? "yes" : "no");
if (!StringUtils.isEmpty(getParameters().getBondingOptions())) {
options.put(VdsProperties.BONDING_OPTIONS, getParameters().getBondingOptions());
}
options.put(VdsProperties.STP, (getParameters().getStp()) ? "yes" : "no");
// options[VdsProperties.force] = "true";
options.put("bridged", Boolean.toString(getParameters().isVmNetwork()));
Network network = getParameters().getNetwork();
if (network != null) {
if (network.getMtu() == 0) {
options.put("mtu", NetworkUtils.getDefaultMtu().toString());
} else {
options.put("mtu", String.valueOf(network.getMtu()));
}
}
status = getBroker().addNetwork(networkName, vlanId, bond, nics, options);
proceedProxyReturnValue();
}
private class CustomTransactionCompletionListener extends NoOpTransactionCompletionListener {
@Override
public void onRollback() {
try {
// We check for "Done" status because we want to be sure that we made the net change, or in case of empty
// response (which means the call to VDSM failed on timeout).
// 1. If we failed VDSM revert the change so we don't need to do anything.
// 2. If we are in transaction first command was AddNetworkCommand (end successfully), second command fails,
// we want to revert the network change (that is why we check for Done).
// 3. If the call to VDSM timeout out we assume it had succeeded and try to remove the network.
// 3.1. If the timeout was a failure to call the VDSM in the first place, then probably the call to delete
// the network will timeout also.
if (getReturnValueFromBroker() == null || EngineError.Done == getReturnValueFromStatus(getReturnStatus())) {
P parameters = getParameters();
String network = (parameters.getNetworkName() == null) ? "" : parameters.getNetworkName();
String vlanId = (parameters.getVlanId() != null) ? parameters.getVlanId().toString() : "";
String bond = (parameters.getBondName() == null) ? "" : parameters.getBondName();
String[] nics = (parameters.getNics() == null) ? new String[] {} : parameters.getNics();
status = getBroker().delNetwork(network, vlanId, bond, nics);
}
} catch (RuntimeException ex) {
log.error("Exception in Rollback executeVdsBrokerCommand", ex);
}
}
}
}
| apache-2.0 |
StrategyObject/fop | test/java/org/apache/fop/pdf/PDFNullTestCase.java | 1638 | /*
* 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.
*/
/* $Id$ */
package org.apache.fop.pdf;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test case for {@link PDFNull}.
*/
public class PDFNullTestCase extends PDFObjectTestCase {
/**
* Test outputInline() - test that "null" is printed to the output stream.
*/
@Test
public void testOutputInline() throws IOException {
PDFNull obj = PDFNull.INSTANCE;
ByteArrayOutputStream out = new ByteArrayOutputStream();
StringBuilder text = new StringBuilder();
obj.outputInline(out, text);
assertEquals("null", text.toString());
// Ensure previously written text is not discarded
obj.outputInline(out, text);
assertEquals("nullnull", text.toString());
}
}
| apache-2.0 |
madhav123/gkmaster | accounting/src/main/java/org/mifos/platform/accounting/tally/message/TallyMessageBuilderException.java | 1065 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.platform.accounting.tally.message;
public class TallyMessageBuilderException extends Exception {
/**
*
*/
private static final long serialVersionUID = -5128349116273003625L;
public TallyMessageBuilderException(String message) {
super(message);
}
}
| apache-2.0 |
smmribeiro/intellij-community | java/java-tests/testData/inspection/dataFlow/fixture/ThisInEnumSubclass.java | 195 | public class ThisInEnumSubclass {
enum MyEnum {
A, B, C {
void test() {
if (<warning descr="Condition 'this == C' is always 'true'">this == C</warning>) {}
}
}
}
} | apache-2.0 |
marianosz/azure-mobile-services | sdk/android/src/sdk/src/com/microsoft/windowsazure/mobileservices/RefreshRegistrationInformationCallback.java | 402 | package com.microsoft.windowsazure.mobileservices;
/**
* Callback to invoke after Refreshing the Registration Information
*/
interface RefreshRegistrationInformationCallback {
/**
* Method to execute when the response is ready to be processed
*
* @param exception
* An exception representing the error, in case there was one
*/
public void onRefresh(Exception exception);
}
| apache-2.0 |
praveev/druid | java-util/src/main/java/io/druid/java/util/common/parsers/JavaScriptParser.java | 2929 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.java.util.common.parsers;
import com.google.common.base.Function;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ScriptableObject;
import java.util.List;
import java.util.Map;
/**
*/
public class JavaScriptParser implements Parser<String, Object>
{
private static Function<Object, Object> compile(String function)
{
final ContextFactory contextFactory = ContextFactory.getGlobal();
final Context context = contextFactory.enterContext();
context.setOptimizationLevel(9);
final ScriptableObject scope = context.initStandardObjects();
final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null);
Context.exit();
return new Function<Object, Object>()
{
@Override
public Object apply(Object input)
{
// ideally we need a close() function to discard the context once it is not used anymore
Context cx = Context.getCurrentContext();
if (cx == null) {
cx = contextFactory.enterContext();
}
final Object res = fn.call(cx, scope, scope, new Object[]{input});
return res != null ? Context.toObject(res, scope) : null;
}
};
}
private final Function<Object, Object> fn;
public JavaScriptParser(
final String function
)
{
this.fn = compile(function);
}
public Function<Object, Object> getFn()
{
return fn;
}
@Override
public Map<String, Object> parse(String input)
{
try {
final Object compiled = fn.apply(input);
if (!(compiled instanceof Map)) {
throw new ParseException("JavaScript parsed value must be in {key: value} format!");
}
return (Map) compiled;
}
catch (Exception e) {
throw new ParseException(e, "Unable to parse row [%s]", input);
}
}
@Override
public void setFieldNames(Iterable<String> fieldNames)
{
throw new UnsupportedOperationException();
}
@Override
public List<String> getFieldNames()
{
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
goodwinnk/intellij-community | java/openapi/src/com/intellij/openapi/projectRoots/JavaSdk.java | 1613 | /*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.openapi.projectRoots;
import com.intellij.openapi.application.ApplicationManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public abstract class JavaSdk extends SdkType implements JavaSdkType {
public static JavaSdk getInstance() {
return ApplicationManager.getApplication().getComponent(JavaSdk.class);
}
public JavaSdk(@NotNull String name) {
super(name);
}
@NotNull
public final Sdk createJdk(@NotNull String jdkName, @NotNull String jreHome) {
return createJdk(jdkName, jreHome, true);
}
@NotNull
public abstract Sdk createJdk(String jdkName, @NotNull String home, boolean isJre);
@Nullable
public abstract JavaSdkVersion getVersion(@NotNull Sdk sdk);
public abstract boolean isOfVersionOrHigher(@NotNull Sdk sdk, @NotNull JavaSdkVersion version);
/** @deprecated use {@link JdkUtil#checkForJdk} (to be removed in IDEA 2019) */
@Deprecated
public static boolean checkForJdk(@NotNull File file) {
return JdkUtil.checkForJdk(file);
}
/** @deprecated use {@link JdkUtil#checkForJre} (to be removed in IDEA 2019) */
@Deprecated
public static boolean checkForJre(@NotNull String file) {
return JdkUtil.checkForJre(file);
}
/** @deprecated use {@link JavaSdkVersion#fromVersionString} (to be removed in IDEA 2019) */
@Deprecated
public abstract JavaSdkVersion getVersion(@NotNull String versionString);
} | apache-2.0 |
mariamKh/robovm-ios-bindings | google-play-game-services/src/org/robovm/bindings/gpgs/GPGMultiplayerConfig.java | 1079 | package org.robovm.bindings.gpgs;
import org.robovm.apple.foundation.NSArray;
import org.robovm.apple.foundation.NSObject;
import org.robovm.objc.annotation.NativeClass;
import org.robovm.objc.annotation.Property;
@NativeClass()
public class GPGMultiplayerConfig extends NSObject {
@Property(selector = "exclusiveBitMask")
public native long getExclusiveBitMask();
@Property(selector = "invitedPlayerIds")
public native String getInvitedPlayerIDs();
@Property(selector = "setInvitedPlayerIDs:")
public native void setInvitedPlayerIDs (NSArray pIDs);
@Property(selector = "maxAutoMatchingPlayers")
public native int getMaxAutoMatchingPlayers();
@Property(selector = "setMaxAutoMatchingPlayers:", strongRef = true)
public native void setMaxAutoMatchingPlayers (int pMaxPlayers);
@Property(selector = "minAutoMatchingPlayers")
public native int getMinAutoMatchingPlayers();
@Property(selector = "setMinAutoMatchingPlayers:", strongRef = true)
public native void setMinAutoMatchingPlayers (int pMinPlayers);
@Property(selector = "variant")
public native int getVariant();
}
| apache-2.0 |
JingchengDu/hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-client/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/reader/EntityTypeReader.java | 6954 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.timelineservice.storage.reader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
import org.apache.hadoop.hbase.filter.PageFilter;
import org.apache.hadoop.yarn.api.records.timelineservice.TimelineEntity;
import org.apache.hadoop.yarn.server.timelineservice.reader.TimelineReaderContext;
import org.apache.hadoop.yarn.server.timelineservice.storage.common.HBaseTimelineStorageUtils;
import org.apache.hadoop.yarn.server.timelineservice.storage.common.Separator;
import org.apache.hadoop.yarn.server.timelineservice.storage.entity.EntityRowKey;
import org.apache.hadoop.yarn.server.timelineservice.storage.entity.EntityRowKeyPrefix;
import org.apache.hadoop.yarn.server.timelineservice.storage.entity.EntityTableRW;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
/**
* Timeline entity reader for listing all available entity types given one
* reader context. Right now only supports listing all entity types within one
* YARN application.
*/
public final class EntityTypeReader extends AbstractTimelineStorageReader {
private static final Logger LOG =
LoggerFactory.getLogger(EntityTypeReader.class);
private static final EntityTableRW ENTITY_TABLE = new EntityTableRW();
public EntityTypeReader(TimelineReaderContext context) {
super(context);
}
/**
* Reads a set of timeline entity types from the HBase storage for the given
* context.
*
* @param hbaseConf HBase Configuration.
* @param conn HBase Connection.
* @return a set of <cite>TimelineEntity</cite> objects, with only type field
* set.
* @throws IOException if any exception is encountered while reading entities.
*/
public Set<String> readEntityTypes(Configuration hbaseConf,
Connection conn) throws IOException {
validateParams();
augmentParams(hbaseConf, conn);
Set<String> types = new TreeSet<>();
TimelineReaderContext context = getContext();
EntityRowKeyPrefix prefix = new EntityRowKeyPrefix(context.getClusterId(),
context.getUserId(), context.getFlowName(), context.getFlowRunId(),
context.getAppId());
byte[] currRowKey = prefix.getRowKeyPrefix();
byte[] nextRowKey = prefix.getRowKeyPrefix();
nextRowKey[nextRowKey.length - 1]++;
FilterList typeFilterList = new FilterList();
typeFilterList.addFilter(new FirstKeyOnlyFilter());
typeFilterList.addFilter(new KeyOnlyFilter());
typeFilterList.addFilter(new PageFilter(1));
LOG.debug("FilterList created for scan is - {}", typeFilterList);
int counter = 0;
while (true) {
try (ResultScanner results =
getResult(hbaseConf, conn, typeFilterList, currRowKey, nextRowKey)) {
TimelineEntity entity = parseEntityForType(results.next());
if (entity == null) {
break;
}
++counter;
if (!types.add(entity.getType())) {
LOG.warn("Failed to add type " + entity.getType()
+ " to the result set because there is a duplicated copy. ");
}
String currType = entity.getType();
if (LOG.isDebugEnabled()) {
LOG.debug("Current row key: " + Arrays.toString(currRowKey));
LOG.debug("New entity type discovered: " + currType);
}
currRowKey = getNextRowKey(prefix.getRowKeyPrefix(), currType);
}
}
LOG.debug("Scanned {} records for {} types", counter, types.size());
return types;
}
@Override
protected void validateParams() {
if (getContext() == null) {
throw new NullPointerException("context shouldn't be null");
}
if (getContext().getClusterId() == null) {
throw new NullPointerException("clusterId shouldn't be null");
}
if (getContext().getAppId() == null) {
throw new NullPointerException("appId shouldn't be null");
}
}
/**
* Gets the possibly next row key prefix given current prefix and type.
*
* @param currRowKeyPrefix The current prefix that contains user, cluster,
* flow, run, and application id.
* @param entityType Current entity type.
* @return A new prefix for the possibly immediately next row key.
*/
private static byte[] getNextRowKey(byte[] currRowKeyPrefix,
String entityType) {
if (currRowKeyPrefix == null || entityType == null) {
return null;
}
byte[] entityTypeEncoded = Separator.QUALIFIERS.join(
Separator.encode(entityType, Separator.SPACE, Separator.TAB,
Separator.QUALIFIERS),
Separator.EMPTY_BYTES);
byte[] currRowKey
= new byte[currRowKeyPrefix.length + entityTypeEncoded.length];
System.arraycopy(currRowKeyPrefix, 0, currRowKey, 0,
currRowKeyPrefix.length);
System.arraycopy(entityTypeEncoded, 0, currRowKey, currRowKeyPrefix.length,
entityTypeEncoded.length);
return HBaseTimelineStorageUtils.calculateTheClosestNextRowKeyForPrefix(
currRowKey);
}
private ResultScanner getResult(Configuration hbaseConf, Connection conn,
FilterList filterList, byte[] startPrefix, byte[] endPrefix)
throws IOException {
Scan scan = new Scan()
.withStartRow(startPrefix)
.withStopRow(endPrefix)
.setFilter(filterList)
.setSmall(true);
return ENTITY_TABLE.getResultScanner(hbaseConf, conn, scan);
}
private TimelineEntity parseEntityForType(Result result)
throws IOException {
if (result == null || result.isEmpty()) {
return null;
}
TimelineEntity entity = new TimelineEntity();
EntityRowKey newRowKey = EntityRowKey.parseRowKey(result.getRow());
entity.setType(newRowKey.getEntityType());
return entity;
}
}
| apache-2.0 |
bsspirit/kettle-4.4.0-stable | src-core/org/pentaho/di/core/gui/ScrollBarInterface.java | 1040 | /*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.core.gui;
public interface ScrollBarInterface {
public void setThumb(int thumb);
public int getSelection();
}
| apache-2.0 |
bitium/directory-kerby | kerby-pkix/src/main/java/org/apache/kerby/x509/type/AlgorithmIdentifier.java | 2496 | /**
* 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.kerby.x509.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1Any;
import org.apache.kerby.asn1.type.Asn1ObjectIdentifier;
import org.apache.kerby.asn1.type.Asn1SequenceType;
import org.apache.kerby.asn1.type.Asn1Type;
/**
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*/
public class AlgorithmIdentifier extends Asn1SequenceType {
protected enum AlgorithmIdentifierField implements EnumType {
ALGORITHM,
PARAMETERS;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[]{
new Asn1FieldInfo(AlgorithmIdentifierField.ALGORITHM, Asn1ObjectIdentifier.class),
new Asn1FieldInfo(AlgorithmIdentifierField.PARAMETERS, Asn1Any.class)
};
public AlgorithmIdentifier() {
super(fieldInfos);
}
public String getAlgorithm() {
return getFieldAsObjId(AlgorithmIdentifierField.ALGORITHM);
}
public void setAlgorithm(String algorithm) {
setFieldAsObjId(AlgorithmIdentifierField.ALGORITHM, algorithm);
}
public <T extends Asn1Type> T getParametersAs(Class<T> t) {
return getFieldAsAny(AlgorithmIdentifierField.PARAMETERS, t);
}
public void setParameters(Asn1Type parameters) {
setFieldAsAny(AlgorithmIdentifierField.PARAMETERS, parameters);
}
} | apache-2.0 |
apereo/cas | support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/ticket/device/OAuth20DefaultDeviceUserCodeFactory.java | 2005 | package org.apereo.cas.ticket.device;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.ticket.ExpirationPolicyBuilder;
import org.apereo.cas.ticket.Ticket;
import org.apereo.cas.ticket.UniqueTicketIdGenerator;
import org.apereo.cas.util.RandomUtils;
import lombok.RequiredArgsConstructor;
import lombok.val;
/**
* Default OAuth device token factory.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@RequiredArgsConstructor
public class OAuth20DefaultDeviceUserCodeFactory implements OAuth20DeviceUserCodeFactory {
/**
* Default instance for the ticket id generator.
*/
protected final UniqueTicketIdGenerator deviceTokenIdGenerator;
/**
* ExpirationPolicy for refresh tokens.
*/
protected final ExpirationPolicyBuilder<OAuth20DeviceToken> expirationPolicy;
/**
* Length of the generated user code.
*/
protected final int userCodeLength;
/**
* Services manager.
*/
protected final ServicesManager servicesManager;
@Override
public OAuth20DeviceUserCode createDeviceUserCode(final OAuth20DeviceToken deviceToken) {
val userCode = generateDeviceUserCode(RandomUtils.randomAlphanumeric(userCodeLength));
val expirationPolicyToUse = OAuth20DeviceTokenUtils.determineExpirationPolicyForService(servicesManager,
expirationPolicy, deviceToken.getService());
val deviceUserCode = new OAuth20DefaultDeviceUserCode(userCode, deviceToken.getId(), expirationPolicyToUse);
deviceToken.assignUserCode(deviceUserCode);
return deviceUserCode;
}
@Override
public String generateDeviceUserCode(final String providedCode) {
val prefix = OAuth20DeviceUserCode.PREFIX + '-';
if (providedCode.startsWith(prefix)) {
return providedCode;
}
return prefix + providedCode.toUpperCase();
}
@Override
public Class<? extends Ticket> getTicketType() {
return OAuth20DeviceUserCode.class;
}
}
| apache-2.0 |
apache/maven-plugins | maven-ear-plugin/src/main/java/org/apache/maven/plugins/ear/EarExecutionContext.java | 3574 | package org.apache.maven.plugins.ear;
/*
* 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.
*/
import org.apache.maven.plugins.ear.util.ArtifactRepository;
import org.apache.maven.plugins.ear.util.ArtifactTypeMappingService;
import org.apache.maven.project.MavenProject;
/**
* Contains various runtime parameters used to customize the generated EAR file.
*
* @author <a href="snicoll@apache.org">Stephane Nicoll</a>
* @version $Id: EarExecutionContext.java 1755538 2016-08-08 20:32:12Z rfscholte $
*/
public class EarExecutionContext
{
private String defaultLibBundleDir;
private JbossConfiguration jbossConfiguration;
private String outputFileNameMapping;
private ArtifactRepository artifactRepository;
/**
* @param project {@link MavenProject}
* @param mainArtifactId The artifactId.
* @param defaultLibBundleDir The defaultLibBundleDir.
* @param jbossConfiguration {@link JbossConfiguration}
* @param fileNameMappingName file name mapping.
* @param typeMappingService {@link ArtifactTypeMappingService}
*/
public EarExecutionContext( MavenProject project, String mainArtifactId, String defaultLibBundleDir,
JbossConfiguration jbossConfiguration, String fileNameMappingName,
ArtifactTypeMappingService typeMappingService )
{
initialize( project, mainArtifactId, defaultLibBundleDir, jbossConfiguration, fileNameMappingName,
typeMappingService );
}
/**
* @return {@link #defaultLibBundleDir}
*/
public String getDefaultLibBundleDir()
{
return defaultLibBundleDir;
}
/**
* @return {@link #jbossConfiguration}
*/
public boolean isJbossConfigured()
{
return jbossConfiguration != null;
}
/**
* @return {@link #fileNameMapping}
*/
public String getOutputFileNameMapping()
{
return outputFileNameMapping;
}
/**
* @return {@link #artifactRepository}
*/
public ArtifactRepository getArtifactRepository()
{
return artifactRepository;
}
private void initialize( MavenProject project, String mainArtifactId, String defaultLibBundleDir,
JbossConfiguration jbossConfiguration, String outputFileNameMapping,
ArtifactTypeMappingService typeMappingService )
{
this.artifactRepository = new ArtifactRepository( project.getArtifacts(), mainArtifactId, typeMappingService );
this.defaultLibBundleDir = defaultLibBundleDir;
this.jbossConfiguration = jbossConfiguration;
this.outputFileNameMapping = outputFileNameMapping;
}
}
| apache-2.0 |
emre-aydin/hazelcast | hazelcast/src/test/java/com/hazelcast/cp/internal/datastructures/countdownlatch/CountDownLatchBasicTest.java | 1671 | /*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.hazelcast.cp.internal.datastructures.countdownlatch;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.cp.ICountDownLatch;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.internal.util.RandomPicker;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class CountDownLatchBasicTest extends AbstractCountDownLatchBasicTest {
@Override
protected String getName() {
return "latch@group";
}
@Override
protected HazelcastInstance[] createInstances() {
return newInstances(3);
}
@Override
protected ICountDownLatch createLatch(String name) {
HazelcastInstance instance = instances[RandomPicker.getInt(instances.length)];
return instance.getCPSubsystem().getCountDownLatch(name);
}
}
| apache-2.0 |
JakFlew/lemon | src/main/java/com/mossle/bridge/userrepo/MockUserRepoConnector.java | 694 | package com.mossle.bridge.userrepo;
import java.util.Collections;
import java.util.List;
import com.mossle.api.userrepo.UserRepoConnector;
import com.mossle.api.userrepo.UserRepoDTO;
public class MockUserRepoConnector implements UserRepoConnector {
private UserRepoDTO userRepoDto = new UserRepoDTO();
public MockUserRepoConnector() {
userRepoDto.setId("1");
userRepoDto.setCode("default");
}
public UserRepoDTO findById(String id) {
return userRepoDto;
}
public UserRepoDTO findByCode(String code) {
return userRepoDto;
}
public List<UserRepoDTO> findAll() {
return Collections.singletonList(userRepoDto);
}
}
| apache-2.0 |
jiaqifeng/pinpoint | profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/classreading/ClassReaderWrapper.java | 9298 | /**
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
* <p>
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* <p>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.navercorp.pinpoint.profiler.instrument.classreading;
import com.navercorp.pinpoint.common.util.Assert;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author jaehong.kim
*/
public class ClassReaderWrapper {
// wrapped ASM ClassReader.
private final ClassReader classReader;
// need readAttributes.
private final List<String> annotationInternalNames = new ArrayList<String>();
private boolean innerClass = false;
// bytecodes of the class.
public ClassReaderWrapper(final byte[] classBinary) {
this(classBinary, false);
}
public ClassReaderWrapper(final byte[] classBinary, final boolean readAttributes) {
Assert.requireNonNull(classBinary, "classBinary must not be null");
this.classReader = new ClassReader(classBinary);
if (readAttributes) {
readAttributes();
}
}
public ClassReaderWrapper(final ClassLoader classLoader, final String classInternalName) throws IOException {
this(classLoader, classInternalName, false);
}
// classloader and class internal name.
public ClassReaderWrapper(final ClassLoader classLoader, final String classInternalName, final boolean readAttributes) throws IOException {
Assert.requireNonNull(classInternalName, "classInternalName must not be null");
ClassLoader cl = classLoader;
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
if (cl == null) {
// system fail.
throw new IOException("system classloader is null.");
}
}
final InputStream in = cl.getResourceAsStream(classInternalName + ".class");
if (in == null) {
throw new IOException("not found class. classLoader=" + cl + ", classInternalName=" + classInternalName);
}
try {
this.classReader = new ClassReader(in);
if (readAttributes) {
readAttributes();
}
} finally {
try {
in.close();
} catch (IOException ignored) {
}
}
}
// class's access flags.
public int getAccess() {
return this.classReader.getAccess();
}
// class version.
public int getVersion() {
return this.classReader.readShort(6);
}
public String getSuperClassInternalName() {
return this.classReader.getSuperName();
}
public String getClassInternalName() {
return this.classReader.getClassName();
}
public List<String> getInterfaceInternalNames() {
return Arrays.asList(this.classReader.getInterfaces());
}
public byte[] getClassBinary() {
return this.classReader.b;
}
public List<String> getAnnotationInternalNames() {
return this.annotationInternalNames;
}
public boolean isInnerClass() {
return this.innerClass;
}
public boolean isInterface() {
return (this.classReader.getAccess() & Opcodes.ACC_INTERFACE) != 0;
}
public boolean isAnnotation() {
return (this.classReader.getAccess() & Opcodes.ACC_ANNOTATION) != 0;
}
public boolean isSynthetic() {
return (this.classReader.getAccess() & Opcodes.ACC_SYNTHETIC) != 0;
}
private void readAttributes() {
final char[] c = new char[this.classReader.getMaxStringLength()]; // buffer used to read strings
int u = getAttributes();
int anns = 0;
int ianns = 0;
for (int i = this.classReader.readUnsignedShort(u); i > 0; --i) {
final String attrName = this.classReader.readUTF8(u + 2, c);
if ("EnclosingMethod".equals(attrName)) {
// is inner class.
if (this.classReader.readClass(u + 8, c) != null) {
this.innerClass = true;
}
} else if ("RuntimeVisibleAnnotations".equals(attrName)) {
// annotation.
anns = u + 8;
} else if ("RuntimeInvisibleAnnotations".equals(attrName)) {
// annotation.
ianns = u + 8;
}
u += 6 + this.classReader.readInt(u + 4);
}
if (anns != 0) {
readAnnotationInternalName(anns, c);
}
if (ianns != 0) {
readAnnotationInternalName(ianns, c);
}
}
/**
* Returns the start index of the attribute_info structure of this class.
*
* @return the start index of the attribute_info structure of this class.
*/
private int getAttributes() {
// skips the header
int header = this.classReader.header;
int u = header + 8 + this.classReader.readUnsignedShort(header + 6) * 2;
// skips fields and methods
for (int i = this.classReader.readUnsignedShort(u); i > 0; --i) {
for (int j = this.classReader.readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + this.classReader.readInt(u + 12);
}
u += 8;
}
u += 2;
for (int i = this.classReader.readUnsignedShort(u); i > 0; --i) {
for (int j = this.classReader.readUnsignedShort(u + 8); j > 0; --j) {
u += 6 + this.classReader.readInt(u + 12);
}
u += 8;
}
// the attribute_info structure starts just after the methods
return u + 2;
}
private void readAnnotationInternalName(int annotationIndex, final char[] buf) {
for (int i = this.classReader.readUnsignedShort(annotationIndex), v = annotationIndex + 2; i > 0; --i) {
final String annotationDesc = this.classReader.readUTF8(v, buf);
final Type type = Type.getType(annotationDesc);
if (type.getSort() == Type.OBJECT) {
final String internalName = type.getInternalName();
if (internalName != null) {
this.annotationInternalNames.add(internalName);
}
}
v = readAnnotationValues(v + 2, buf, true);
}
}
private int readAnnotationValues(int v, final char[] buf, final boolean named) {
int i = this.classReader.readUnsignedShort(v);
v += 2;
if (named) {
for (; i > 0; --i) {
v = readAnnotationValue(v + 2, buf);
}
} else {
for (; i > 0; --i) {
v = readAnnotationValue(v, buf);
}
}
return v;
}
private int readAnnotationValue(int v, final char[] buf) {
switch (this.classReader.b[v] & 0xFF) {
case 'e': // enum_const_value
return v + 5;
case '@': // annotation_value
return readAnnotationValues(v + 3, buf, true);
case '[': // array_value
return readAnnotationValues(v + 1, buf, false);
default:
return v + 3;
}
}
public String toString() {
StringBuilder sb = new StringBuilder().append("{");
sb.append("access=").append(classReader.getAccess()).append(", ");
sb.append("name=").append(classReader.getClassName()).append(", ");
sb.append("interfaces=").append(Arrays.asList(classReader.getInterfaces())).append(", ");
sb.append("super=").append(classReader.getSuperName());
sb.append("}");
return sb.toString();
}
} | apache-2.0 |
youngwookim/presto | presto-main/src/main/java/io/prestosql/operator/PageTransportErrorException.java | 1036 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.prestosql.operator;
import io.prestosql.spi.PrestoException;
import static io.prestosql.spi.StandardErrorCode.PAGE_TRANSPORT_ERROR;
public class PageTransportErrorException
extends PrestoException
{
public PageTransportErrorException(String message)
{
super(PAGE_TRANSPORT_ERROR, message);
}
public PageTransportErrorException(String message, Throwable cause)
{
super(PAGE_TRANSPORT_ERROR, message, cause);
}
}
| apache-2.0 |
mcculls/guice | core/src/com/google/inject/spi/ProviderWithDependencies.java | 968 | /*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject.spi;
import com.google.inject.Provider;
/**
* A provider with dependencies on other injected types. If a {@link Provider} has dependencies that
* aren't specified in injections, this interface should be used to expose all dependencies.
*
* @since 2.0
*/
public interface ProviderWithDependencies<T> extends Provider<T>, HasDependencies {}
| apache-2.0 |
robin13/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/dataframe/stats/classification/ValidationLoss.java | 3491 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
package org.elasticsearch.xpack.core.ml.dataframe.stats.classification;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.xpack.core.ml.dataframe.stats.common.FoldValues;
import org.elasticsearch.xpack.core.ml.utils.ToXContentParams;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class ValidationLoss implements ToXContentObject, Writeable {
public static final ParseField LOSS_TYPE = new ParseField("loss_type");
public static final ParseField FOLD_VALUES = new ParseField("fold_values");
public static ValidationLoss fromXContent(XContentParser parser, boolean ignoreUnknownFields) {
return createParser(ignoreUnknownFields).apply(parser, null);
}
@SuppressWarnings("unchecked")
private static ConstructingObjectParser<ValidationLoss, Void> createParser(boolean ignoreUnknownFields) {
ConstructingObjectParser<ValidationLoss, Void> parser = new ConstructingObjectParser<>("classification_validation_loss",
ignoreUnknownFields,
a -> new ValidationLoss((String) a[0], (List<FoldValues>) a[1]));
parser.declareString(ConstructingObjectParser.constructorArg(), LOSS_TYPE);
parser.declareObjectArray(ConstructingObjectParser.constructorArg(),
(p, c) -> FoldValues.fromXContent(p, ignoreUnknownFields), FOLD_VALUES);
return parser;
}
private final String lossType;
private final List<FoldValues> foldValues;
public ValidationLoss(String lossType, List<FoldValues> values) {
this.lossType = Objects.requireNonNull(lossType);
this.foldValues = Objects.requireNonNull(values);
}
public ValidationLoss(StreamInput in) throws IOException {
lossType = in.readString();
foldValues = in.readList(FoldValues::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(lossType);
out.writeList(foldValues);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(LOSS_TYPE.getPreferredName(), lossType);
if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false)) {
builder.field(FOLD_VALUES.getPreferredName(), foldValues);
}
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ValidationLoss that = (ValidationLoss) o;
return Objects.equals(lossType, that.lossType) && Objects.equals(foldValues, that.foldValues);
}
@Override
public int hashCode() {
return Objects.hash(lossType, foldValues);
}
}
| apache-2.0 |