repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
highsource/hyperjaxb3 | ejb/plugin/src/main/java/org/jvnet/hyperjaxb3/xjc/generator/bean/field/SingleEnumValueWrappingField.java | 1306 | package org.jvnet.hyperjaxb3.xjc.generator.bean.field;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JOp;
import com.sun.tools.xjc.generator.bean.ClassOutlineImpl;
import com.sun.tools.xjc.model.CEnumLeafInfo;
import com.sun.tools.xjc.model.CPropertyInfo;
import com.sun.tools.xjc.model.Aspect;
public class SingleEnumValueWrappingField extends AbstractWrappingField {
private final CEnumLeafInfo enumType;
private final JClass enumClass;
public SingleEnumValueWrappingField(ClassOutlineImpl context,
CPropertyInfo prop, CPropertyInfo core) {
super(context, prop, core);
// Single
assert !core.isCollection();
// Builtin
assert core.ref().size() == 1;
assert core.ref().iterator().next() instanceof CEnumLeafInfo;
this.enumType = (CEnumLeafInfo) core.ref().iterator().next();
this.enumClass = this.enumType.toType(context.parent(), Aspect.EXPOSED);
}
@Override
protected JExpression unwrap(JExpression source) {
return JOp.cond(source.eq(JExpr._null()), JExpr._null(), source
.invoke("value"));
}
@Override
protected JExpression wrap(JExpression target) {
return JOp.cond(target.eq(JExpr._null()), JExpr._null(), this.enumClass
.staticInvoke("fromValue").arg(target));
}
}
| bsd-2-clause |
EPapadopoulou/PersoNIS | privacy-policy-management/src/main/java/org/societies/privacytrust/privacyprotection/privacypolicy/PrivacyAgreementManagerInternal.java | 12189 | /**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.privacytrust.privacyprotection.privacypolicy;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.societies.api.comm.xmpp.interfaces.ICommManager;
import org.societies.api.context.CtxException;
import org.societies.api.context.model.CtxAssociation;
import org.societies.api.context.model.CtxAssociationIdentifier;
import org.societies.api.context.model.CtxAssociationTypes;
import org.societies.api.context.model.CtxAttribute;
import org.societies.api.context.model.CtxAttributeTypes;
import org.societies.api.context.model.CtxEntity;
import org.societies.api.context.model.CtxEntityIdentifier;
import org.societies.api.context.model.CtxEntityTypes;
import org.societies.api.context.model.CtxIdentifier;
import org.societies.api.context.model.CtxModelType;
import org.societies.api.context.model.util.SerialisationHelper;
import org.societies.api.identity.IIdentity;
import org.societies.api.identity.Requestor;
import org.societies.api.internal.context.broker.ICtxBroker;
import org.societies.api.internal.privacytrust.privacyprotection.model.privacypolicy.AgreementEnvelope;
import org.societies.api.internal.privacytrust.privacyprotection.util.model.privacypolicy.AgreementEnvelopeUtils;
import org.societies.api.privacytrust.privacy.model.PrivacyException;
import org.societies.privacytrust.privacyprotection.api.IPrivacyAgreementManagerInternal;
/**
* @author Olivier Maridat (Trialog)
* @date 5 déc. 2011
*/
public class PrivacyAgreementManagerInternal implements IPrivacyAgreementManagerInternal {
private static Logger LOG = LoggerFactory.getLogger(PrivacyAgreementManagerInternal.class.getSimpleName());
ICommManager commManager;
ICtxBroker ctxBroker;
/*
* (non-Javadoc)
* @see org.societies.privacytrust.privacyprotection.api.IPrivacyAgreementManagerInternal#updateAgreement(org.societies.api.identity.Requestor, org.societies.api.internal.privacytrust.privacyprotection.model.privacypolicy.AgreementEnvelope)
*/
@Override
public CtxIdentifier updateAgreement(Requestor requestor, AgreementEnvelope agreement) throws PrivacyException {
// -- Verify
if (null == requestor || null == requestor.getRequestorId()) {
throw new PrivacyException("Not enought information to search a privacy policy agreement. Requestor needed.");
}
// Dependency injection not ready
if (!isDepencyInjectionDone()) {
throw new PrivacyException("[Dependency Injection] PolicyAgreementManagerInternal not ready");
}
// -- Update Agreement
String requestorId = getRequestorId(requestor);
CtxIdentifier agreementId = null;
try {
// Retrieve existing id (if possible)
List<CtxIdentifier> agreementIdList = ctxBroker.lookup(CtxModelType.ATTRIBUTE, requestorId).get();
CtxAttribute agreementData = null;
// - Creation
if (null == agreementIdList || agreementIdList.size() <= 0) {
// Retrieve the context entity: Privacy Policy Agreement
List<CtxIdentifier> agreementEntityIdList = ctxBroker.lookup(CtxModelType.ENTITY, CtxEntityTypes.PRIVACY_POLICY_AGREEMENT).get();
// Create it if necessary
CtxEntityIdentifier agreementEntityId = null;
if (null == agreementEntityIdList || agreementEntityIdList.size() <= 0) {
agreementEntityId = createPolicyAgreementEntity();
}
else {
agreementEntityId = (CtxEntityIdentifier) agreementEntityIdList.get(0);
}
// Create the new context attribute to store the agreement
agreementData = ctxBroker.createAttribute(agreementEntityId, requestorId).get();
agreementId = agreementData.getId();
LOG.debug("Created attribute: "+agreementData.getType());
}
// - Update
else {
agreementId = agreementIdList.get(0);
// Retrieve the existing context attribute to store the agreement
agreementData = (CtxAttribute) ctxBroker.retrieve(agreementId).get();
LOG.debug("Updated attribute:"+agreementData.getType());
}
// - Save the agreement
agreementData.setBinaryValue(SerialisationHelper.serialise(AgreementEnvelopeUtils.toAgreementEnvelopeBean(agreement)));
ctxBroker.update(agreementData);
} catch (CtxException e) {
LOG.error("[Error updateAgreement] Can't find the agreement. Context error.", e);
} catch (IOException e) {
LOG.error("[Error updateAgreement] Can't find the agreement. IO error.", e);
} catch (InterruptedException e) {
LOG.error("[Error updateAgreement] Can't find the agreement.", e);
} catch (ExecutionException e) {
LOG.error("[Error updateAgreement] Can't find the agreement.", e);
}
return agreementId;
}
/*
* (non-Javadoc)
* @see org.societies.privacytrust.privacyprotection.api.IPrivacyAgreementManagerInternal#deleteAgreement(org.societies.api.identity.Requestor)
*/
@Override
public boolean deleteAgreement(Requestor requestor) throws PrivacyException {
// -- Verify
if (null == requestor || null == requestor.getRequestorId()) {
throw new PrivacyException("Not enought information to search a privacy policy agreement. Requestor needed.");
}
// Dependency injection not ready
if (!isDepencyInjectionDone()) {
throw new PrivacyException("[Dependency Injection] PolicyAgreementManagerInternal not ready");
}
// -- Delete agreement
try {
// - Retrieve existing id (if possible)
String requestorId = getRequestorId(requestor);
List<CtxIdentifier> agreementIdList = ctxBroker.lookup(CtxModelType.ATTRIBUTE, requestorId).get();
CtxIdentifier agreementId = null;
// No agreement for this requestor
if (null == agreementIdList || agreementIdList.size() <= 0) {
return true;
}
else {
agreementId = agreementIdList.get(0);
}
// - Remove from context
ctxBroker.remove(agreementId);
return true;
} catch (CtxException e) {
LOG.error("[Error deleteAgreement] Can't find the agreement. Context error.", e);
} catch (InterruptedException e) {
LOG.error("[Error deleteAgreement] Can't find the agreement.", e);
} catch (ExecutionException e) {
LOG.error("[Error deleteAgreement] Can't find the agreement.", e);
}
return false;
}
// -- Private methods
/**
* Util method to create a context agreement entity
* @return The id of the agreement entity
* @throws PrivacyException
*/
private CtxEntityIdentifier createPolicyAgreementEntity() throws PrivacyException {
try {
// -- Retrieve the CSS Entity
CtxEntity css = ctxBroker.retrieveCssOperator().get();
if (null == css) {
throw new PrivacyException("Error can't retrieve CSS Operator Entity in Context.");
}
// -- Create the Agreement Entity
CtxEntity agreementEntity = ctxBroker.createEntity(CtxEntityTypes.PRIVACY_POLICY_AGREEMENT).get();
// -- Retrieve and update the relevant association
Set<CtxAssociationIdentifier> hasPrivacyPolicyAgreementsList = css.getAssociations(CtxAssociationTypes.HAS_PRIVACY_POLICY_AGREEMENTS);
CtxAssociation hasPrivacyPolicyAgreements = null;
// Create it if necessary
if (null == hasPrivacyPolicyAgreementsList || hasPrivacyPolicyAgreementsList.size() <= 0) {
hasPrivacyPolicyAgreements = ctxBroker.createAssociation(CtxAssociationTypes.HAS_PRIVACY_POLICY_AGREEMENTS).get();
hasPrivacyPolicyAgreements.setParentEntity(css.getId());
}
else {
hasPrivacyPolicyAgreements = (CtxAssociation) ctxBroker.retrieve(hasPrivacyPolicyAgreementsList.iterator().next()).get();
}
// Add the agreement entity to this association
hasPrivacyPolicyAgreements.addChildEntity(agreementEntity.getId());
// TODO: add link to CIS entity or 3P service entity? I don't know yet.
ctxBroker.update(hasPrivacyPolicyAgreements);
return agreementEntity.getId();
} catch (CtxException e) {
LOG.error("[Error createPolicyAgreementEntity] Can't find the agreement. Context error.", e);
} catch (InterruptedException e) {
LOG.error("[Error createPolicyAgreementEntity] Can't find the agreement.", e);
} catch (ExecutionException e) {
LOG.error("[Error createPolicyAgreementEntity] Can't find the agreement.", e);
}
return null;
}
/**
* To find the real relevant requestor id
* @param requestor
* @return
* @throws PrivacyException
*/
public static String getRequestorId(Requestor requestor) throws PrivacyException {
if (null == requestor) {
throw new PrivacyException("Bad requestor, can't store the agreement in the context.");
}
return CtxAttributeTypes.PRIVACY_POLICY_AGREEMENT+requestor.hashCode();
}
/**
* To find the agreement id on the context
* @param requestor
* @param ownerId
* @return
* @throws PrivacyException
*/
public static String getAgreementIdOnCtx(Requestor requestor, IIdentity ownerId) throws PrivacyException {
if (null == requestor) {
throw new PrivacyException("Bad requestor, can't store the agreement in the context.");
}
return CtxAttributeTypes.PRIVACY_POLICY_AGREEMENT+requestor.hashCode()+ownerId.hashCode();
}
// -- Dependency Injection
public void setCommManager(ICommManager commManager) {
this.commManager = commManager;
LOG.info("[DependencyInjection] ICommManager injected");
}
public void setCtxBroker(ICtxBroker ctxBroker) {
this.ctxBroker = ctxBroker;
LOG.info("[DependencyInjection] ICtxBroker injected");
}
private boolean isDepencyInjectionDone() {
return isDepencyInjectionDone(0);
}
private boolean isDepencyInjectionDone(int level) {
if (null == ctxBroker) {
LOG.info("[Dependency Injection] Missing ICtxBorker");
return false;
}
if (level == 0 || level == 1) {
if (null == commManager) {
LOG.info("[Dependency Injection] Missing ICommManager");
return false;
}
if (null == commManager.getIdManager()) {
LOG.info("[Dependency Injection] Missing IIdentityManager");
return false;
}
}
return true;
}
}
| bsd-2-clause |
kephale/imagej-ops | src/main/java/net/imglib2/ops/function/real/RealMinFunction.java | 2285 | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2015 Board of Regents of the University of
* Wisconsin-Madison, University of Konstanz and Brian Northan.
* %%
* 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.
*
* 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 HOLDERS 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.
* #L%
*/
package net.imglib2.ops.function.real;
import net.imglib2.ops.function.Function;
import net.imglib2.type.numeric.RealType;
/**
* Computes the minimum value another function takes on across a region.
*
* @author Barry DeZonia
* @deprecated Use net.imagej.ops instead.
*/
@Deprecated
public class RealMinFunction<T extends RealType<T>>
extends
AbstractRealStatFunction<T>
{
// -- constructor --
public RealMinFunction(Function<long[],T> otherFunc)
{
super(otherFunc);
}
// -- abstract method overrides --
@Override
protected double value(StatCalculator<T> calc) {
return calc.min();
}
// -- Function methods --
@Override
public RealMinFunction<T> copy() {
return new RealMinFunction<T>(otherFunc.copy());
}
}
| bsd-2-clause |
thehutch/Fusion | API/src/main/java/me/thehutch/fusion/api/util/hashing/LongTripleHash.java | 1695 | /*
* This file is part of API, licensed under the Apache 2.0 License.
*
* Copyright (c) 2014 thehutch.
*
* 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 me.thehutch.fusion.api.util.hashing;
import me.thehutch.fusion.api.maths.Vector2;
import me.thehutch.fusion.api.maths.Vector3;
/**
* @author thehutch
*/
public class LongTripleHash {
private LongTripleHash() {
}
public static long hash(Vector2 vec) {
return hash(vec.getFloorX(), vec.getFloorY(), 0);
}
public static long hash(Vector3 vec) {
return hash(vec.getFloorX(), vec.getFloorY(), vec.getFloorZ());
}
public static long hash(int x, int y, int z) {
return ((long) ((x >> 11) & 0x100000 | x & 0xFFFFF)) << 42 | ((long) ((y >> 11) & 0x100000 | y & 0xFFFFF)) << 21 | ((z >> 11) & 0x100000 | z & 0xFFFFF);
}
public static int key1(long hash) {
return keyInt((hash >> 42) & 0x1FFFFF);
}
public static int key2(long hash) {
return keyInt((hash >> 21) & 0x1FFFFF);
}
public static int key3(long hash) {
return keyInt(hash & 0x1FFFFF);
}
private static int keyInt(long key) {
return (int) (key - ((key & 0x100000) << 1));
}
}
| bsd-2-clause |
jayantk/jklol | src/com/jayantkrish/jklol/ccg/CcgBinaryRule.java | 10306 | package com.jayantkrish.jklol.ccg;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import com.jayantkrish.jklol.ccg.lambda.ExpressionParser;
import com.jayantkrish.jklol.ccg.lambda2.Expression2;
import com.jayantkrish.jklol.ccg.lambda2.StaticAnalysis;
import com.jayantkrish.jklol.util.CsvParser;
/**
* A binary combination rule applicable to two adjacent CCG
* categories. These rules represent operations like type-changing,
* in addition to the standard CCG application/combination rules.
* For example, {@code CcgBinaryRule} can be used to absorb
* punctuation marks.
* <p>
* Each combination rule matches a pair of adjacent
* {@code SyntacticCategory}s, and returns a new category for their
* span. The returned category may inherit some of its semantics from
* one of the combined categories. In addition, the semantics of the
* returned category may be augmented with additional unfilled
* dependencies. The inherited semantics enable {@code CcgBinaryRule}
* to capture comma conjunction (for example).
*
* @author jayantk
*/
public class CcgBinaryRule implements Serializable {
private static final long serialVersionUID = 2L;
private final HeadedSyntacticCategory leftSyntax;
private final HeadedSyntacticCategory rightSyntax;
private final HeadedSyntacticCategory parentSyntax;
// Logical form for this rule. The logical form is a function of
// type (left lf -> (right lf -> result))
private final Expression2 logicalForm;
// Unfilled dependencies created by this rule.
private final String[] subjects;
private final HeadedSyntacticCategory[] subjectSyntacticCategories;
private final int[] argumentNumbers;
// The variables each dependency accepts.
private final int[] objects;
private final Combinator.Type type;
public CcgBinaryRule(HeadedSyntacticCategory leftSyntax, HeadedSyntacticCategory rightSyntax,
HeadedSyntacticCategory returnSyntax, Expression2 logicalForm, List<String> subjects,
List<HeadedSyntacticCategory> subjectSyntaxes, List<Integer> argumentNumbers,
List<Integer> objects, Combinator.Type type) {
this.leftSyntax = leftSyntax;
this.rightSyntax = rightSyntax;
this.parentSyntax = returnSyntax;
this.logicalForm = logicalForm;
Preconditions.checkArgument(logicalForm == null ||
StaticAnalysis.isLambda(logicalForm, 0) && StaticAnalysis.getLambdaArguments(logicalForm, 0).size() >= 2,
"Illegal logical form for binary rule: " + logicalForm);
this.subjects = subjects.toArray(new String[0]);
this.subjectSyntacticCategories = subjectSyntaxes.toArray(new HeadedSyntacticCategory[0]);
this.argumentNumbers = Ints.toArray(argumentNumbers);
this.objects = Ints.toArray(objects);
this.type = Preconditions.checkNotNull(type);
}
/**
* Parses a binary rule from a line in comma-separated format. The
* expected fields, in order, are:
* <ul>
* <li>The headed syntactic categories to combine and return:
* <code>(left syntax) (right syntax) (return syntax)</code>
* <li>(optional) Logical form for the rule.
* <li>(optional) Additional unfilled dependencies, in standard
* format:
* <code>(predicate) (argument number) (argument variable)</code>
* </ul>
*
* For example, ", NP{0} NP{0}" is a binary rule that allows an NP
* to absorb a comma on the left. Or, "conj{2} (S{0}\NP{1}){0}
* ((S{0}\NP{1}){0}\(S{0}\NP{1}){0}){2}" allows the "conj" type to
* conjoin verb phrases of type (S\NP).
*
* @param line
* @return
*/
public static CcgBinaryRule parseFrom(String line) {
String[] chunks = new CsvParser(',', CsvParser.DEFAULT_QUOTE,
CsvParser.NULL_ESCAPE).parseLine(line.trim());
Preconditions.checkArgument(chunks.length >= 1);
String[] syntacticParts = chunks[0].split(" ");
Preconditions.checkArgument(syntacticParts.length == 3);
HeadedSyntacticCategory leftSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[0]);
HeadedSyntacticCategory rightSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[1]);
HeadedSyntacticCategory returnSyntax = HeadedSyntacticCategory.parseFrom(syntacticParts[2]);
Expression2 logicalForm = null;
if (chunks.length >= 2 && chunks[1].trim().length() > 0) {
logicalForm = ExpressionParser.expression2().parse(chunks[1]);
}
// Parse the type of combinator, if one is given.
Combinator.Type type = Combinator.Type.OTHER;
if (chunks.length >= 3) {
type = Combinator.Type.valueOf(chunks[2]);
}
// Parse any dependencies, if given.
List<String> subjects = Lists.newArrayList();
List<HeadedSyntacticCategory> subjectSyntacticCategories = Lists.newArrayList();
List<Integer> argNums = Lists.newArrayList();
List<Integer> objects = Lists.newArrayList();
if (chunks.length >= 4) {
for (int i = 3; i < chunks.length; i++) {
String[] newDeps = chunks[i].split(" ");
Preconditions.checkArgument(newDeps.length == 3);
subjects.add(newDeps[0]);
subjectSyntacticCategories.add(rightSyntax.getCanonicalForm());
argNums.add(Integer.parseInt(newDeps[1]));
objects.add(Integer.parseInt(newDeps[2]));
}
}
return new CcgBinaryRule(leftSyntax, rightSyntax, returnSyntax, logicalForm,
subjects, subjectSyntacticCategories, argNums, objects, type);
}
/**
* Reads in a collection of unary and binary rules, adding the rules
* to {@code binaryRules} and {@code unaryRules}, respectively.
*
* @param unfilteredRuleLines
* @param binaryRules
* @param unaryRules
*/
public static void parseBinaryAndUnaryRules(Iterable<String> unfilteredRuleLines,
List<CcgBinaryRule> binaryRules, List<CcgUnaryRule> unaryRules) {
for (String line : unfilteredRuleLines) {
// System.out.println(line);
if (!line.startsWith("#")) {
try {
binaryRules.add(CcgBinaryRule.parseFrom(line));
} catch (IllegalArgumentException e) {
unaryRules.add(CcgUnaryRule.parseFrom(line));
}
}
}
}
/**
* Gets the expected syntactic type that should occur on the left
* side in order to instantiate this rule. The returned type may not
* be in canonical form.
*
* @return
*/
public HeadedSyntacticCategory getLeftSyntacticType() {
return leftSyntax;
}
/**
* Gets the expected syntactic type that should occur on the right
* side in order to instantiate this rule. The returned type may not
* be in canonical form.
*
* @return
*/
public HeadedSyntacticCategory getRightSyntacticType() {
return rightSyntax;
}
/**
* Gets the syntactic type that is produced by this rule. The
* returned type may not be in canonical form.
*
* @return
*/
public HeadedSyntacticCategory getParentSyntacticType() {
return parentSyntax;
}
/**
* Gets a lambda calculus representation of the function of this
* operation. The returned function accepts two arguments: the left
* and right logical forms, in that order.
*
* @return
*/
public Expression2 getLogicalForm() {
return logicalForm;
}
/**
* Gets the list of subjects of the dependencies instantiated by
* this rule.
*
* @return
*/
public String[] getSubjects() {
return subjects;
}
public HeadedSyntacticCategory[] getSubjectSyntacticCategories() {
return subjectSyntacticCategories;
}
/**
* Gets the list of argument numbers of the dependencies
* instantiated by this rule.
*
* @return
*/
public int[] getArgumentNumbers() {
return argumentNumbers;
}
/**
* Gets the list of object variable numbers of the dependencies
* instantiated by this rule.
*
* @return
*/
public int[] getObjects() {
return objects;
}
/**
* Gets the type of combinator represented by this rule.
*
* @return
*/
public Combinator.Type getCombinatorType() {
if (type == null) {
// This check is included for backward compatibility with
// serialized BinaryCombinators that do not include the
// type field.
return Combinator.Type.OTHER;
} else {
return type;
}
}
@Override
public String toString() {
return leftSyntax + " " + rightSyntax + " -> " + parentSyntax + ", " + Arrays.toString(subjects);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(argumentNumbers);
result = prime * result + ((leftSyntax == null) ? 0 : leftSyntax.hashCode());
result = prime * result + ((logicalForm == null) ? 0 : logicalForm.hashCode());
result = prime * result + Arrays.hashCode(objects);
result = prime * result + ((parentSyntax == null) ? 0 : parentSyntax.hashCode());
result = prime * result + ((rightSyntax == null) ? 0 : rightSyntax.hashCode());
result = prime * result + Arrays.hashCode(subjects);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CcgBinaryRule other = (CcgBinaryRule) obj;
if (!Arrays.equals(argumentNumbers, other.argumentNumbers))
return false;
if (leftSyntax == null) {
if (other.leftSyntax != null)
return false;
} else if (!leftSyntax.equals(other.leftSyntax))
return false;
if (logicalForm == null) {
if (other.logicalForm != null)
return false;
} else if (!logicalForm.equals(other.logicalForm))
return false;
if (!Arrays.equals(objects, other.objects))
return false;
if (parentSyntax == null) {
if (other.parentSyntax != null)
return false;
} else if (!parentSyntax.equals(other.parentSyntax))
return false;
if (rightSyntax == null) {
if (other.rightSyntax != null)
return false;
} else if (!rightSyntax.equals(other.rightSyntax))
return false;
if (!Arrays.equals(subjects, other.subjects))
return false;
return true;
}
}
| bsd-2-clause |
opf-labs/jhove2 | src/main/java/uk/gov/nationalarchives/droid/binFileReader/FileByteReader.java | 14697 | /*
* Copyright The National Archives 2005-2006. All rights reserved.
* See Licence.txt for full licence details.
*
* Developed by:
* Tessella Support Services plc
* 3 Vineyard Chambers
* Abingdon, OX14 3PX
* United Kingdom
* http://www.tessella.com
*
* Tessella/NPD/4826
* PRONOM 5a
*
* $Id: FileByteReader.java,v 1.8 2006/03/13 15:15:28 linb Exp $
*
* $Log: FileByteReader.java,v $
* Revision 1.8 2006/03/13 15:15:28 linb
* Changed copyright holder from Crown Copyright to The National Archives.
* Added reference to licence.txt
* Changed dates to 2005-2006
*
* Revision 1.7 2006/02/09 15:34:10 linb
* Updates to javadoc and code following the code review
*
* Revision 1.5 2006/02/09 15:31:23 linb
* Updates to javadoc and code following the code review
*
* Revision 1.5 2006/02/09 13:17:42 linb
* Changed StreamByteReader to InputStreamByteReader
* Refactored common code from UrlByteReader and InputStreamByteReader into new class StreamByteReader, from which they both inherit
* Updated javadoc
*
* Revision 1.4 2006/02/09 12:14:16 linb
* Changed some javadoc to allow it to be created cleanly
*
* Revision 1.3 2006/02/08 08:56:35 linb
* - Added header comments
*
* * *****************************************
* S. Morrissey For JHOVE2 Date 09/12/2009
* refactored to use IAnalaysis Controller for constants,
* and AnalysisControllerUtil for static methods
*
*/
package uk.gov.nationalarchives.droid.binFileReader;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import uk.gov.nationalarchives.droid.IdentificationFile;
import uk.gov.nationalarchives.droid.JHOVE2IAnalysisController;
/**
* The <code>FileByteReader</code> class is a <code>ByteReader</code> that
* reads its data from a file.
* <p/>
* <p>This class can have two files associated with it: The file represented by it
* (its <code>IdentificationFile</code>) and a (possibly different) backing file.
* The purpose of this separation is so that this object can represent a URL that
* has been downloaded or an InputStream that has been saved to disk.
*
* @author linb
*/
public class FileByteReader extends AbstractByteReader {
// added for jHOVE2
boolean isTempFile = false;
// added for jHOVE2
FileByteReader(IdentificationFile theIDFile, boolean readFile, String filePath, boolean isTempFile) {
super(theIDFile);
this.file = new File(filePath);
if (readFile) {
this.readFile();
}
this.isTempFile = isTempFile;
}
/**
* Creates a new instance of FileByteReader
* <p/>
* <p>This constructor can set the <code>IdentificationFile</code> to
* a different file than the actual file used. For example, if <code>theIDFile</code>
* is a URL or stream, and is too big to be buffered in memory, it could be written
* to a temporary file. This file would then be used as a backing file to store
* the data.
*
* @param theIDFile the file represented by this object
* @param readFile <code>true</code> if the file is to be read
* @param filePath the backing file (containing the data)
*/
FileByteReader(IdentificationFile theIDFile, boolean readFile, String filePath) {
// super(theIDFile);
// this.file = new File(filePath);
// if (readFile) {
// this.readFile();
// }
// changed for JHOVE2
this(theIDFile, readFile, filePath, false);
}
/**
* Creates a new instance of FileByteReader
* <p/>
* <p>This constructor uses the same file to contain the data as is specified by
* <code>theIDFile</code>.
*
* @param theIDFile the source file from which the bytes will be read.
* @param readFile <code>true</code> if the file is to be read
*/
FileByteReader(IdentificationFile theIDFile, boolean readFile) {
this(theIDFile, readFile, theIDFile.getFilePath());
}
private int randomFileBufferSize = JHOVE2IAnalysisController.FILE_BUFFER_SIZE;
private boolean isRandomAccess = false;
protected byte[] fileBytes;
private long numBytes;
private long fileMarker;
private RandomAccessFile randomAccessFile = null;
private long rAFoffset = 0L;
private static final int MIN_RAF_BUFFER_SIZE = 1000000;
private static final int RAF_BUFFER_REDUCTION_FACTOR = 2;
private File file;
public boolean isRandomAccess() {
return isRandomAccess;
}
public int getRandomFileBufferSize() {
return randomFileBufferSize;
}
public RandomAccessFile getRandomAccessFile() {
return randomAccessFile;
}
/**
* Reads in the binary file specified.
* <p/>
* <p>If there are any problems reading in the file, it gets classified as unidentified,
* with an explanatory warning message.
*/
private void readFile() {
//If file is not readable or is empty, then it gets classified
//as unidentified (with an explanatory warning)
if (!file.exists()) {
this.setErrorIdent();
this.setIdentificationWarning("File does not exist");
return;
}
if (!file.canRead()) {
this.setErrorIdent();
this.setIdentificationWarning("File cannot be read");
return;
}
if (file.isDirectory()) {
this.setErrorIdent();
this.setIdentificationWarning("This is a directory, not a file");
return;
}
FileInputStream binStream;
try {
binStream = new FileInputStream(file);
} catch (FileNotFoundException ex) {
this.setErrorIdent();
this.setIdentificationWarning("File disappeared or cannot be read");
return;
}
BufferedInputStream buffStream = null;
try {
int numBytes = binStream.available();
if (numBytes > 0) {
fileBytes = new byte[numBytes];
buffStream = new BufferedInputStream(binStream);
int len = buffStream.read(fileBytes, 0, numBytes);
if (len != numBytes) {
//This means that all bytes were not successfully read
this.setErrorIdent();
this.setIdentificationWarning("Error reading file: " + len + " bytes read from file when " + numBytes + " were expected");
} else if (buffStream.read() != -1) {
//This means that the end of the file was not reached
this.setErrorIdent();
this.setIdentificationWarning("Error reading file: Unable to read to the end");
} else {
this.numBytes = (long) numBytes;
}
} else {
//If file is empty , status is error
//this.setErrorIdent();
this.numBytes = 0L;
this.setIdentificationWarning("Zero-length file");
}
isRandomAccess = false;
} catch (IOException e) {
this.setErrorIdent();
this.setIdentificationWarning("Error reading file: " + e.toString());
} catch (OutOfMemoryError e) {
try {
randomAccessFile = new RandomAccessFile(file, "r");
isRandomAccess = true;
//record the file size
numBytes = randomAccessFile.length();
//try reading in a buffer
randomAccessFile.seek(0L);
boolean tryAgain = true;
while (tryAgain) {
try {
fileBytes = new byte[randomFileBufferSize];
randomAccessFile.read(fileBytes);
tryAgain = false;
} catch (OutOfMemoryError e4) {
randomFileBufferSize = randomFileBufferSize / RAF_BUFFER_REDUCTION_FACTOR;
if (randomFileBufferSize < MIN_RAF_BUFFER_SIZE) {
throw e4;
}
}
}
rAFoffset = 0L;
} catch (FileNotFoundException e2) {
this.setErrorIdent();
this.setIdentificationWarning("File disappeared or cannot be read");
} catch (Exception e2) {
this.setErrorIdent();
this.setIdentificationWarning("Error reading file: " + e2.toString());
}
} finally {
if (buffStream != null) {
try {
buffStream.close();
} catch (IOException e) {
this.setErrorIdent();
this.setIdentificationWarning("Unable to close file: " + e.getMessage());
}
}
if (binStream != null) {
try {
binStream.close();
} catch (IOException e) {
this.setErrorIdent();
this.setIdentificationWarning("Unable to close file: " + e.getMessage());
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
this.setErrorIdent();
this.setIdentificationWarning("Unable to close file: " + e.getMessage());
}
}
}
}
/**
* Position the file marker at a given byte position.
* <p/>
* <p>The file marker is used to record how far through the file
* the byte sequence matching algorithm has got.
*
* @param markerPosition The byte number in the file at which to position the marker
*/
public void setFileMarker(long markerPosition) {
if ((markerPosition < -1L) || (markerPosition > this.getNumBytes())) {
throw new IllegalArgumentException(" Unable to place a fileMarker at byte "
+ Long.toString(markerPosition) + " in file " + this.myIDFile.getFilePath() + " (size = " + Long.toString(this.getNumBytes()) + " bytes)");
} else {
this.fileMarker = markerPosition;
}
}
/**
* Gets the current position of the file marker.
*
* @return the current position of the file marker
*/
public long getFileMarker() {
return this.fileMarker;
}
/**
* Get a byte from file
*
* @param fileIndex position of required byte in the file
* @return the byte at position <code>fileIndex</code> in the file
*/
public byte getByte(long fileIndex) {
byte theByte = 0;
if (isRandomAccess) {
//If the file is being read via random acces,
//then read byte from buffer, otherwise read in a new buffer.
long theArrayIndex = fileIndex - rAFoffset;
if (fileIndex >= rAFoffset && theArrayIndex < randomFileBufferSize) {
theByte = fileBytes[(int) (theArrayIndex)];
} else {
try {
//Create a new buffer:
/*
//When a new buffer is created, the requesting file position is
//taken to be the middle of the buffer. This is so that it will
//perform equally well whether the file is being examined from
//start to end or from end to start
rAFoffset = fileIndex - (myRAFbuffer/2);
if(rAFoffset<0L) {
rAFoffset = 0L;
}
System.out.println(" re-read file buffer");
randomAccessFile.seek(rAFoffset);
randomAccessFile.read(fileBytes);
theByte = fileBytes[(int)(fileIndex-rAFoffset)];
*/
if (fileIndex < randomFileBufferSize) {
rAFoffset = 0L;
} else if (fileIndex < rAFoffset) {
rAFoffset = fileIndex - randomFileBufferSize + 1;
} else {
rAFoffset = fileIndex;
}
//System.out.println(" re-read file buffer from "+rAFoffset+ " for "+myRAFbuffer+" bytes");
//System.out.println(" seek start");
randomAccessFile.seek(rAFoffset);
//System.out.println(" read start");
randomAccessFile.read(fileBytes);
//System.out.println(fileIndex);
//System.out.println(" read end");
theByte = fileBytes[(int) (fileIndex - rAFoffset)];
} catch (Exception e) {
//
}
}
} else {
//If the file is not being read by random access, then the byte should be in the buffer array
if (fileBytes != null) {
theByte = fileBytes[(int) fileIndex];
}
}
return theByte;
}
/**
* Returns the number of bytes in the file
*/
public long getNumBytes() {
return numBytes;
}
/**
* Returns the byte array buffer
*
* @return the buffer associated with the file
*/
public byte[] getbuffer() {
return fileBytes;
}
/**
* Closes any input files that are open.
*/
public void close() {
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
this.setErrorIdent();
this.setIdentificationWarning("Unable to close file: " + e.getMessage());
}
randomAccessFile = null;
}
// added for JHOVE2
if (this.file != null && this.isTempFile){
try{
file.delete();
}
catch(Exception e){
}
}
// end added for JHOVE2
}
}
| bsd-2-clause |
LuNaTeCs-316/LuNaCV | src/org/lunatecs316/frc2014/vision/AcquireSampleImages.java | 2286 | package org.lunatecs316.frc2014.vision;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
/**
* Utility to capture sample images from the camera and save them to the disk
* @author Domenic
*/
public class AcquireSampleImages {
private VideoCapture camera;
private Mat frame;
private int saveCount = 0;
public void run() {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
camera = new VideoCapture("http://10.3.16.11/mjpg/video.mjpg");
frame = new Mat();
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setLayout(new BoxLayout(window.getContentPane(), BoxLayout.Y_AXIS));
CVMatPanel imagePanel = new CVMatPanel(320, 240);
window.getContentPane().add(imagePanel);
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
saveImage();
}
});
window.getContentPane().add(saveButton);
window.pack();
window.setVisible(true);
while (true) {
if (camera.isOpened()) {
if (camera.read(frame)) {
imagePanel.showMat(frame);
} else {
System.err.println("Error: unable to read image from camera");
}
} else {
System.err.println("Error: camera not open");
}
}
}
public void saveImage() {
File f = null;
String filename = null;
do {
filename = "sample_images/image" + ++saveCount + ".jpg";
System.out.println(filename);
f = new File(filename);
} while (f.isFile());
Highgui.imwrite(filename, frame);
}
public static void main(String[] args) {
new AcquireSampleImages().run();
}
}
| bsd-2-clause |
TheGreenMachine/Zephyr-Java | src/com/edinarobotics/utils/autonomous/DebuggingStepWrapper.java | 1024 | package com.edinarobotics.utils.autonomous;
/**
*
*/
public class DebuggingStepWrapper extends AutonomousStep{
private AutonomousStep wrappedStep;
private String name;
public DebuggingStepWrapper(AutonomousStep wrappedStep, String name){
this.wrappedStep = wrappedStep;
this.name = name;
}
public DebuggingStepWrapper(AutonomousStep wrappedStep){
this(wrappedStep, "default");
}
public void start(){
printMessage("Called start");
wrappedStep.start();
}
public void run(){
printMessage("Called run");
wrappedStep.run();
}
public void stop(){
printMessage("Called stop");
wrappedStep.stop();
}
public boolean isFinished(){
boolean finished = wrappedStep.isFinished();
printMessage("Called isFinished - "+finished);
return finished;
}
private void printMessage(String message){
System.out.println(name+": "+message);
}
}
| bsd-3-clause |
TEAM4456/MechStorm2016 | src/org/usfirst/frc4456/mechstorm2016/commands/SesawAuto.java | 1706 | package org.usfirst.frc4456.mechstorm2016.commands;
import org.usfirst.frc4456.mechstorm2016.Robot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class SesawAuto extends Command {
boolean endCommand = false;
public SesawAuto() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
Timer timer = new Timer();
timer.start();
while(!timer.hasPeriodPassed(.5)){
Robot.drive.setspeed(.4);
Robot.arm.setarm(0.22);
}
Robot.drive.setspeed(0);
Robot.arm.setarm(0);
timer.stop();
timer.reset();
timer.start();
while(!timer.hasPeriodPassed(.5)){
Robot.arm.setarm(0.3);
}
Robot.arm.setarm(0);
timer.stop();
timer.reset();
/*
while(!timer.hasPeriodPassed(2)){
Robot.drive.setspeed(.7);
Robot.arm.setarm(-0.1);
}
Robot.drive.setspeed(0);
timer.stop();
timer.reset();
*/
endCommand = true;
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
if(endCommand == true){
System.out.println("Finished");
return true;
}
else{
return false;
}
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| bsd-3-clause |
ninjin/corbit | src/main/java/corbit/commons/io/MaltReader.java | 4237 | /*
* Corbit, a text analyzer
*
* Copyright (c) 2010-2012, Jun Hatori
* 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 names of the authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package corbit.commons.io;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.Normalizer;
import java.util.Arrays;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import corbit.commons.dict.TagDictionary;
import corbit.commons.util.Statics;
import corbit.commons.word.ArcLabel;
import corbit.commons.word.IndexWord;
import corbit.commons.word.ParsedSentence;
import corbit.commons.word.SentenceBuilder;
public class MaltReader extends ParseReader
{
public MaltReader(String sFile, TagDictionary dict)
{
super(sFile, dict.generateTagSet(), new TreeSet<String>(Arrays.asList(dict.getArcLabels())));
}
@Override protected void iterate() throws InterruptedException
{
int iLine = 0;
FileEnum fe = new FileEnum(m_sFile);
try
{
while (fe.hasNext())
{
SentenceBuilder sb = new SentenceBuilder(m_posSet, m_labelSet);
int index = 0;
while (true)
{
String l = Statics.trimSpecial(fe.next());
++iLine;
if (l.length() == 0)
break;
Pattern re = Pattern.compile("(.*?)\t(.*?)\t(.*?)\t(.*?)");
Matcher mc = re.matcher(l);
if (!mc.matches() || mc.groupCount() < 4)
{
System.err.println(String.format("Error found at line %d. Skipping.", iLine));
sb = null;
break;
}
String sForm = Normalizer.normalize(mc.group(1), Normalizer.Form.NFKC);
String sPos = mc.group(2);
int iHead = Integer.parseInt(mc.group(3)) - 1;
ArcLabel label = ArcLabel.getLabel(mc.group(4));
sb.addWord(index, sForm, sPos, iHead, label);
index++;
}
if (sb != null)
yieldReturn(sb.compile());
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
fe.shutdown();
}
}
public static void maltToDep(String sFile, String sOutFile, TagDictionary dict) throws IOException
{
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(sOutFile), "UTF-8"));
MaltReader mr = new MaltReader(sFile, dict);
try
{
while (mr.hasNext())
{
ParsedSentence s = mr.next();
for (int i = 0; i < s.size(); ++i)
{
IndexWord dw = s.get(i);
pw.print(String.format("%d:(%d)_(%s)_(%s)_(%s) ",
dw.index, dw.head, dw.form, dw.tag, dw.arclabel));
}
pw.println();
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
mr.shutdown();
}
pw.close();
}
}
| bsd-3-clause |
sergescc/OSCARS_MPC_SERVLET | src/service/UserSession.java | 1225 | package service;
import java.util.Hashtable;
import java.util.Map;
public class UserSession {
private static long sessionIdSequence = 1L;
private static final Map<Long, String> pendingSessions = new Hashtable<>();
private static final Map<Long, UserSession> activeSessions = new Hashtable<>();
private String username;
private long sessionId;
public UserSession(String username)
{
this.setUsername(username);
}
public static long loadSession(String username)
{
long id = UserSession.sessionIdSequence++;
UserSession.pendingSessions.put(id, username);
return id;
}
public static boolean activateSession(Long id, String username)
{
if (pendingSessions.containsKey(id))
{
if (pendingSessions.get(id).equalsIgnoreCase(username));
{
UserSession.activeSessions.put(id,new UserSession(username));
UserSession.pendingSessions.remove(id);
return true;
}
}
return false;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getSessionId() {
return sessionId;
}
public void setSessionId(long sessionId) {
this.sessionId = sessionId;
}
}
| bsd-3-clause |
asamgir/openspecimen | WEB-INF/src/com/krishagni/catissueplus/rest/controller/CollectionProtocolsController.java | 11775 |
package com.krishagni.catissueplus.rest.controller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolSummary;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierDetail;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp.OP;
import com.krishagni.catissueplus.core.biospecimen.events.CpQueryCriteria;
import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail.WorkflowDetail;
import com.krishagni.catissueplus.core.biospecimen.repository.CpListCriteria;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.Operation;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.Resource;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import edu.common.dynamicextensions.nutility.IoUtil;
@Controller
@RequestMapping("/collection-protocols")
public class CollectionProtocolsController {
@Autowired
private CollectionProtocolService cpSvc;
@Autowired
private HttpServletRequest httpServletRequest;
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<CollectionProtocolSummary> getCollectionProtocols(
@RequestParam(value = "query", required = false)
String searchStr,
@RequestParam(value = "title", required = false)
String title,
@RequestParam(value = "piId", required = false)
Long piId,
@RequestParam(value = "repositoryName", required = false)
String repositoryName,
@RequestParam(value = "startAt", required = false, defaultValue = "0")
int startAt,
@RequestParam(value = "maxResults", required = false, defaultValue = "100")
int maxResults,
@RequestParam(value = "chkPrivilege", required = false, defaultValue = "true")
boolean chkPrivlege,
@RequestParam(value = "detailedList", required = false, defaultValue = "false")
boolean detailedList) {
CpListCriteria crit = new CpListCriteria()
.query(searchStr)
.title(title)
.piId(piId)
.repositoryName(repositoryName)
.includePi(detailedList)
.includeStat(detailedList)
.startAt(startAt)
.maxResults(maxResults);
ResponseEvent<List<CollectionProtocolSummary>> resp = cpSvc.getProtocols(getRequest(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail getCollectionProtocol(@PathVariable("id") Long cpId) {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.getCollectionProtocol(getRequest(crit));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value = "/{id}/definition")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void getCpDefFile(@PathVariable("id") Long cpId, HttpServletResponse response)
throws JsonProcessingException {
CpQueryCriteria crit = new CpQueryCriteria();
crit.setId(cpId);
crit.setFullObject(true);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.getCollectionProtocol(getRequest(crit));
resp.throwErrorIfUnsuccessful();
CollectionProtocolDetail cp = resp.getPayload();
ObjectMapper mapper = new ObjectMapper();
FilterProvider filters = new SimpleFilterProvider().addFilter("withoutId", SimpleBeanPropertyFilter.serializeAllExcept("id"));
String def = mapper.writer(filters).withDefaultPrettyPrinter().writeValueAsString(cp);
response.setContentType("application/json");
response.setHeader("Content-Disposition", "attachment;filename=CpDef_" + cpId + ".json");
InputStream in = null;
try {
in = new ByteArrayInputStream(def.getBytes());
IoUtil.copy(in, response.getOutputStream());
} catch (IOException e) {
throw new RuntimeException("Error sending file", e);
} finally {
IoUtil.close(in);
}
}
@RequestMapping(method = RequestMethod.POST, value="/definition")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail importCpDef(@PathVariable("file") MultipartFile file)
throws IOException {
CollectionProtocolDetail cp = new ObjectMapper().readValue(file.getBytes(), CollectionProtocolDetail.class);
RequestEvent<CollectionProtocolDetail> req = new RequestEvent<CollectionProtocolDetail>(cp);
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.importCollectionProtocol(req);
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail createCollectionProtocol(@RequestBody CollectionProtocolDetail cp) {
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.createCollectionProtocol(getRequest(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail updateCollectionProtocol(@RequestBody CollectionProtocolDetail cp) {
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.updateCollectionProtocol(getRequest(cp));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/dependent-entities")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<DependentEntityDetail> getCpDependentEntities(@PathVariable Long id) {
ResponseEvent<List<DependentEntityDetail>> resp = cpSvc.getCpDependentEntities(getRequest(id));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.DELETE, value="/{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CollectionProtocolDetail deleteCollectionProtocol(@PathVariable Long id) {
ResponseEvent<CollectionProtocolDetail> resp = cpSvc.deleteCollectionProtocol(getRequest(id));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/consent-tiers")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<ConsentTierDetail> getConsentTiers(@PathVariable("id") Long cpId) {
ResponseEvent<List<ConsentTierDetail>> resp = cpSvc.getConsentTiers(getRequest(cpId));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.POST, value="/{id}/consent-tiers")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail addConsentTier(@PathVariable("id") Long cpId, @RequestBody ConsentTierDetail consentTier) {
return performConsentTierOp(OP.ADD, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}/consent-tiers/{tierId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail updateConsentTier(
@PathVariable("id") Long cpId,
@PathVariable("tierId") Long tierId,
@RequestBody ConsentTierDetail consentTier) {
consentTier.setId(tierId);
return performConsentTierOp(OP.UPDATE, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.DELETE, value="/{id}/consent-tiers/{tierId}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public ConsentTierDetail removeConsentTier(
@PathVariable("id") Long cpId,
@PathVariable("tierId") Long tierId) {
ConsentTierDetail consentTier = new ConsentTierDetail();
consentTier.setId(tierId);
return performConsentTierOp(OP.REMOVE, cpId, consentTier);
}
@RequestMapping(method = RequestMethod.GET, value="/{id}/workflows")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail getWorkflowCfg(@PathVariable("id") Long cpId) {
ResponseEvent<CpWorkflowCfgDetail> resp = cpSvc.getWorkflows(new RequestEvent<Long>(cpId));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
@RequestMapping(method = RequestMethod.PUT, value="/{id}/workflows")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public CpWorkflowCfgDetail saveWorkflowCfg(@PathVariable("id") Long cpId, @RequestBody List<WorkflowDetail> workflows) {
CpWorkflowCfgDetail input = new CpWorkflowCfgDetail();
input.setCpId(cpId);
for (WorkflowDetail workflow : workflows) {
input.getWorkflows().put(workflow.getName(), workflow);
}
ResponseEvent<CpWorkflowCfgDetail> resp = cpSvc.saveWorkflows(new RequestEvent<CpWorkflowCfgDetail>(input));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
//
// For UI work
//
@RequestMapping(method = RequestMethod.GET, value="/byop")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public List<CollectionProtocolSummary> getCpListByOp(
@RequestParam(value = "resource", required = true)
String resourceName,
@RequestParam(value = "op", required = true)
String opName,
@RequestParam(value = "siteName", required = false)
String[] siteNames,
@RequestParam(value = "title", required = false)
String searchTitle) {
List<String> inputSiteList = Collections.emptyList();
if (siteNames != null) {
inputSiteList = Arrays.asList(siteNames);
}
Resource resource = Resource.fromName(resourceName);
Operation op = Operation.fromName(opName);
List<CollectionProtocolSummary> emptyList = Collections.<CollectionProtocolSummary>emptyList();
ResponseEvent<List<CollectionProtocolSummary>> resp = new ResponseEvent<List<CollectionProtocolSummary>>(emptyList);
if (resource == Resource.PARTICIPANT && op == Operation.CREATE) {
resp = cpSvc.getRegisterEnabledCps(inputSiteList, searchTitle);
}
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
private ConsentTierDetail performConsentTierOp(OP op, Long cpId, ConsentTierDetail consentTier) {
ConsentTierOp req = new ConsentTierOp();
req.setConsentTier(consentTier);
req.setCpId(cpId);
req.setOp(op);
ResponseEvent<ConsentTierDetail> resp = cpSvc.updateConsentTier(getRequest(req));
resp.throwErrorIfUnsuccessful();
return resp.getPayload();
}
private <T> RequestEvent<T> getRequest(T payload) {
return new RequestEvent<T>(payload);
}
}
| bsd-3-clause |
Digot/GoMint | gomint-api/src/main/java/io/gomint/event/PlayerJoinEvent.java | 322 | package io.gomint.event;
import io.gomint.entity.Player;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
/**
* @author Digot
* @version 1.0
*/
@AllArgsConstructor
@Getter
public class PlayerJoinEvent extends Event {
private Player player;
@Setter private String joinMessage;
}
| bsd-3-clause |
PolyphasicDevTeam/NoMoreOversleeps | src/com/tinytimrob/ppse/nmo/integration/webui/WebTemplate.java | 2138 | package com.tinytimrob.ppse.nmo.integration.webui;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;
public class WebTemplate
{
public static final Configuration PARSER = new Configuration(Configuration.VERSION_2_3_23);
static
{
PARSER.setClassForTemplateLoading(WebTemplate.class, "/resources/ftl");
PARSER.setDefaultEncoding("UTF-8");
PARSER.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
PARSER.setLogTemplateExceptions(false);
PARSER.setDateFormat("dd MMM yyyy");
PARSER.setTimeFormat("hh:mm a");
PARSER.setDateTimeFormat("dd MMM yyyy, hh:mm a");
PARSER.setLocale(Locale.UK);
}
public static final void renderTemplate(String template, HttpServletResponse response, Object model) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, TemplateException, IOException
{
StringWriter writer = new StringWriter();
PARSER.getTemplate(template).process(model, writer);
response.getWriter().append(writer.toString());
}
public static final void renderTemplate(String template, HttpServletResponse response, Object model, Writer writer) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, TemplateException, IOException
{
StringWriter writer_ = new StringWriter();
PARSER.getTemplate(template).process(model, writer_);
writer.append(writer_.toString());
}
public static final String renderBody(String template, Object model) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, TemplateException, IOException
{
StringWriter writer = new StringWriter();
PARSER.getTemplate(template).process(model, writer);
return writer.toString();
}
}
| bsd-3-clause |
cisco/PDTool | PDToolModules/src/com/tibco/ps/deploytool/modules/ServerAttributeValueMapEntryValueType.java | 2640 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257
// 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: 2018.12.19 at 12:55:18 AM EST
//
package com.tibco.ps.deploytool.modules;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Server Attributes Value Map Entry Value Type
*
*
* <p>Java class for ServerAttributeValueMapEntryValueType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ServerAttributeValueMapEntryValueType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="type" type="{http://www.tibco.com/ps/deploytool/modules}AttributeTypeSimpleType" minOccurs="0"/>
* <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ServerAttributeValueMapEntryValueType", propOrder = {
"type",
"value"
})
public class ServerAttributeValueMapEntryValueType {
protected AttributeTypeSimpleType type;
protected String value;
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link AttributeTypeSimpleType }
*
*/
public AttributeTypeSimpleType getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link AttributeTypeSimpleType }
*
*/
public void setType(AttributeTypeSimpleType value) {
this.type = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
| bsd-3-clause |
danakj/chromium | chrome/android/java/src/org/chromium/chrome/browser/signin/AccountManagementFragment.java | 31734 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.signin;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.UserManager;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Pair;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.childaccounts.ChildAccountService;
import org.chromium.chrome.browser.preferences.ChromeBasePreference;
import org.chromium.chrome.browser.preferences.ManagedPreferenceDelegate;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.Preferences;
import org.chromium.chrome.browser.preferences.PreferencesLauncher;
import org.chromium.chrome.browser.preferences.SyncPreference;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.profiles.ProfileAccountManagementMetrics;
import org.chromium.chrome.browser.profiles.ProfileDownloader;
import org.chromium.chrome.browser.signin.SignOutDialogFragment.SignOutDialogListener;
import org.chromium.chrome.browser.signin.SigninManager.SignInStateObserver;
import org.chromium.chrome.browser.sync.ProfileSyncService;
import org.chromium.chrome.browser.sync.ProfileSyncService.SyncStateChangedListener;
import org.chromium.chrome.browser.sync.ui.SyncCustomizationFragment;
import org.chromium.components.sync.AndroidSyncSettings;
import org.chromium.components.sync.signin.AccountManagerHelper;
import org.chromium.components.sync.signin.ChromeSigninController;
import java.util.ArrayList;
import java.util.HashMap;
/**
* The settings screen with information and settings related to the user's accounts.
*
* This shows which accounts the user is signed in with, allows the user to sign out of Chrome,
* links to sync settings, has links to add accounts and go incognito, and shows parental settings
* if a child account is in use.
*
* Note: This can be triggered from a web page, e.g. a GAIA sign-in page.
*/
public class AccountManagementFragment extends PreferenceFragment
implements SignOutDialogListener, ProfileDownloader.Observer,
SyncStateChangedListener, SignInStateObserver,
ConfirmManagedSyncDataDialog.Listener {
private static final String TAG = "AcctManagementPref";
public static final String SIGN_OUT_DIALOG_TAG = "sign_out_dialog_tag";
private static final String CLEAR_DATA_PROGRESS_DIALOG_TAG = "clear_data_progress";
/**
* The key for an integer value in
* {@link Preferences#EXTRA_SHOW_FRAGMENT_ARGUMENTS} bundle to
* specify the correct GAIA service that has triggered the dialog.
* If the argument is not set, GAIA_SERVICE_TYPE_NONE is used as the origin of the dialog.
*/
public static final String SHOW_GAIA_SERVICE_TYPE_EXTRA = "ShowGAIAServiceType";
/**
* Account name preferences will be ordered sequentially, starting with this "order" value.
* This ensures that the account name preferences appear in the correct location in the
* preference fragment. See account_management_preferences.xml for details.
*/
private static final int FIRST_ACCOUNT_PREF_ORDER = 100;
/**
* SharedPreference name for the preference that disables signing out of Chrome.
* Signing out is forever disabled once Chrome signs the user in automatically
* if the device has a child account or if the device is an Android EDU device.
*/
private static final String SIGN_OUT_ALLOWED = "auto_signed_in_school_account";
private static final HashMap<String, Pair<String, Bitmap>> sToNamePicture =
new HashMap<String, Pair<String, Bitmap>>();
private static String sChildAccountId = null;
private static Bitmap sCachedBadgedPicture = null;
public static final String PREF_SIGN_OUT = "sign_out";
public static final String PREF_ADD_ACCOUNT = "add_account";
public static final String PREF_PARENTAL_SETTINGS = "parental_settings";
public static final String PREF_PARENT_ACCOUNTS = "parent_accounts";
public static final String PREF_CHILD_CONTENT = "child_content";
public static final String PREF_CHILD_SAFE_SITES = "child_safe_sites";
public static final String PREF_GOOGLE_ACTIVITY_CONTROLS = "google_activity_controls";
public static final String PREF_SYNC_SETTINGS = "sync_settings";
private int mGaiaServiceType;
private ArrayList<Preference> mAccountsListPreferences = new ArrayList<Preference>();
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
// Prevent sync from starting if it hasn't already to give the user a chance to change
// their sync settings.
ProfileSyncService syncService = ProfileSyncService.get();
if (syncService != null) {
syncService.setSetupInProgress(true);
}
mGaiaServiceType = AccountManagementScreenHelper.GAIA_SERVICE_TYPE_NONE;
if (getArguments() != null) {
mGaiaServiceType =
getArguments().getInt(SHOW_GAIA_SERVICE_TYPE_EXTRA, mGaiaServiceType);
}
AccountManagementScreenHelper.logEvent(
ProfileAccountManagementMetrics.VIEW,
mGaiaServiceType);
startFetchingAccountsInformation(getActivity(), Profile.getLastUsedProfile());
}
@Override
public void onResume() {
super.onResume();
SigninManager.get(getActivity()).addSignInStateObserver(this);
ProfileDownloader.addObserver(this);
ProfileSyncService syncService = ProfileSyncService.get();
if (syncService != null) {
syncService.addSyncStateChangedListener(this);
}
update();
}
@Override
public void onPause() {
super.onPause();
SigninManager.get(getActivity()).removeSignInStateObserver(this);
ProfileDownloader.removeObserver(this);
ProfileSyncService syncService = ProfileSyncService.get();
if (syncService != null) {
syncService.removeSyncStateChangedListener(this);
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Allow sync to begin syncing if it hasn't yet.
ProfileSyncService syncService = ProfileSyncService.get();
if (syncService != null) {
syncService.setSetupInProgress(false);
}
}
/**
* Initiate fetching the user accounts data (images and the full name).
* Fetched data will be sent to observers of ProfileDownloader.
*
* @param profile Profile to use.
*/
private static void startFetchingAccountsInformation(Context context, Profile profile) {
Account[] accounts = AccountManagerHelper.get(context).getGoogleAccounts();
for (int i = 0; i < accounts.length; i++) {
startFetchingAccountInformation(context, profile, accounts[i].name);
}
}
public void update() {
final Context context = getActivity();
if (context == null) return;
if (getPreferenceScreen() != null) getPreferenceScreen().removeAll();
ChromeSigninController signInController = ChromeSigninController.get(context);
if (!signInController.isSignedIn()) {
// The AccountManagementFragment can only be shown when the user is signed in. If the
// user is signed out, exit the fragment.
getActivity().finish();
return;
}
addPreferencesFromResource(R.xml.account_management_preferences);
String signedInAccountName =
ChromeSigninController.get(getActivity()).getSignedInAccountName();
String fullName = getCachedUserName(signedInAccountName);
if (TextUtils.isEmpty(fullName)) {
fullName = ProfileDownloader.getCachedFullName(Profile.getLastUsedProfile());
}
if (TextUtils.isEmpty(fullName)) fullName = signedInAccountName;
getActivity().setTitle(fullName);
configureSignOutSwitch();
configureAddAccountPreference();
configureChildAccountPreferences();
configureSyncSettings();
configureGoogleActivityControls();
updateAccountsList();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean canAddAccounts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return true;
UserManager userManager = (UserManager) getActivity()
.getSystemService(Context.USER_SERVICE);
return !userManager.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS);
}
private void configureSignOutSwitch() {
boolean isChildAccount = ChildAccountService.isChildAccount();
Preference signOutSwitch = findPreference(PREF_SIGN_OUT);
if (isChildAccount) {
getPreferenceScreen().removePreference(signOutSwitch);
} else {
signOutSwitch.setEnabled(getSignOutAllowedPreferenceValue(getActivity()));
signOutSwitch.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (!isVisible() || !isResumed()) return false;
if (ChromeSigninController.get(getActivity()).isSignedIn()
&& getSignOutAllowedPreferenceValue(getActivity())) {
AccountManagementScreenHelper.logEvent(
ProfileAccountManagementMetrics.TOGGLE_SIGNOUT,
mGaiaServiceType);
String managementDomain =
SigninManager.get(getActivity()).getManagementDomain();
if (managementDomain != null) {
// Show the 'You are signing out of a managed account' dialog.
ConfirmManagedSyncDataDialog.showSignOutFromManagedAccountDialog(
AccountManagementFragment.this, getFragmentManager(),
getResources(), managementDomain);
} else {
// Show the 'You are signing out' dialog.
SignOutDialogFragment signOutFragment = new SignOutDialogFragment();
Bundle args = new Bundle();
args.putInt(SHOW_GAIA_SERVICE_TYPE_EXTRA, mGaiaServiceType);
signOutFragment.setArguments(args);
signOutFragment.setTargetFragment(AccountManagementFragment.this, 0);
signOutFragment.show(getFragmentManager(), SIGN_OUT_DIALOG_TAG);
}
return true;
}
return false;
}
});
}
}
private void configureSyncSettings() {
final Preferences preferences = (Preferences) getActivity();
final Account account = ChromeSigninController.get(getActivity()).getSignedInUser();
findPreference(PREF_SYNC_SETTINGS)
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (!isVisible() || !isResumed()) return false;
if (ProfileSyncService.get() == null) return true;
if (AndroidSyncSettings.isMasterSyncEnabled(preferences)) {
Bundle args = new Bundle();
args.putString(
SyncCustomizationFragment.ARGUMENT_ACCOUNT, account.name);
preferences.startFragment(
SyncCustomizationFragment.class.getName(), args);
} else {
openSyncSettingsPage(preferences);
}
return true;
}
});
}
private void configureGoogleActivityControls() {
Preference pref = findPreference(PREF_GOOGLE_ACTIVITY_CONTROLS);
pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Activity activity = getActivity();
((ChromeApplication) (activity.getApplicationContext()))
.createGoogleActivityController()
.openWebAndAppActivitySettings(activity,
ChromeSigninController.get(activity).getSignedInAccountName());
RecordUserAction.record("Signin_AccountSettings_GoogleActivityControlsClicked");
return true;
}
});
}
private void configureAddAccountPreference() {
ChromeBasePreference addAccount = (ChromeBasePreference) findPreference(PREF_ADD_ACCOUNT);
if (ChildAccountService.isChildAccount()) {
getPreferenceScreen().removePreference(addAccount);
} else {
addAccount.setTitle(getResources().getString(
R.string.account_management_add_account_title));
addAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
if (!isVisible() || !isResumed()) return false;
AccountManagementScreenHelper.logEvent(
ProfileAccountManagementMetrics.ADD_ACCOUNT,
mGaiaServiceType);
AccountAdder.getInstance().addAccount(
getActivity(), AccountAdder.ADD_ACCOUNT_RESULT);
// Return to the last opened tab if triggered from the content area.
if (mGaiaServiceType != AccountManagementScreenHelper.GAIA_SERVICE_TYPE_NONE) {
if (isAdded()) getActivity().finish();
}
return true;
}
});
addAccount.setManagedPreferenceDelegate(new ManagedPreferenceDelegate() {
@Override
public boolean isPreferenceControlledByPolicy(Preference preference) {
return !canAddAccounts();
}
});
}
}
private void configureChildAccountPreferences() {
Preference parentAccounts = findPreference(PREF_PARENT_ACCOUNTS);
Preference childContent = findPreference(PREF_CHILD_CONTENT);
Preference childSafeSites = findPreference(PREF_CHILD_SAFE_SITES);
if (ChildAccountService.isChildAccount()) {
Resources res = getActivity().getResources();
PrefServiceBridge prefService = PrefServiceBridge.getInstance();
String firstParent = prefService.getSupervisedUserCustodianEmail();
String secondParent = prefService.getSupervisedUserSecondCustodianEmail();
String parentText;
if (!secondParent.isEmpty()) {
parentText = res.getString(R.string.account_management_two_parent_names,
firstParent, secondParent);
} else if (!firstParent.isEmpty()) {
parentText = res.getString(R.string.account_management_one_parent_name,
firstParent);
} else {
parentText = res.getString(R.string.account_management_no_parental_data);
}
parentAccounts.setSummary(parentText);
parentAccounts.setSelectable(false);
final boolean unapprovedContentBlocked =
prefService.getDefaultSupervisedUserFilteringBehavior()
== PrefServiceBridge.SUPERVISED_USER_FILTERING_BLOCK;
final String contentText = res.getString(
unapprovedContentBlocked ? R.string.account_management_child_content_approved
: R.string.account_management_child_content_all);
childContent.setSummary(contentText);
childContent.setSelectable(false);
final String safeSitesText = res.getString(
prefService.isSupervisedUserSafeSitesEnabled()
? R.string.text_on : R.string.text_off);
childSafeSites.setSummary(safeSitesText);
childSafeSites.setSelectable(false);
} else {
PreferenceScreen prefScreen = getPreferenceScreen();
prefScreen.removePreference(findPreference(PREF_PARENTAL_SETTINGS));
prefScreen.removePreference(parentAccounts);
prefScreen.removePreference(childContent);
prefScreen.removePreference(childSafeSites);
}
}
private void openSyncSettingsPage(Activity activity) {
// TODO(crbug/557784): This needs to actually take the user to a specific account settings
// page. There doesn't seem to be an obvious way to do that at the moment, but should update
// this when we figure that out.
Intent intent = new Intent(Settings.ACTION_SYNC_SETTINGS);
intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] {"com.google"});
if (intent.resolveActivity(activity.getPackageManager()) == null) {
Log.w(TAG, "Unable to resolve activity for: %s", intent);
return;
}
activity.startActivity(intent);
}
private void updateAccountsList() {
PreferenceScreen prefScreen = getPreferenceScreen();
if (prefScreen == null) return;
for (int i = 0; i < mAccountsListPreferences.size(); i++) {
prefScreen.removePreference(mAccountsListPreferences.get(i));
}
mAccountsListPreferences.clear();
final Preferences activity = (Preferences) getActivity();
Account[] accounts = AccountManagerHelper.get(activity).getGoogleAccounts();
int nextPrefOrder = FIRST_ACCOUNT_PREF_ORDER;
for (Account account : accounts) {
ChromeBasePreference pref = new ChromeBasePreference(activity);
pref.setSelectable(false);
pref.setTitle(account.name);
boolean isChildAccount = ChildAccountService.isChildAccount();
pref.setIcon(new BitmapDrawable(getResources(),
isChildAccount ? getBadgedUserPicture(account.name, getResources()) :
getUserPicture(account.name, getResources())));
pref.setOrder(nextPrefOrder++);
prefScreen.addPreference(pref);
mAccountsListPreferences.add(pref);
}
}
// ProfileDownloader.Observer implementation:
@Override
public void onProfileDownloaded(String accountId, String fullName, String givenName,
Bitmap bitmap) {
updateUserNamePictureCache(accountId, fullName, bitmap);
updateAccountsList();
}
// SignOutDialogListener implementation:
/**
* This class must be public and static. Otherwise an exception will be thrown when Android
* recreates the fragment (e.g. after a configuration change).
*/
public static class ClearDataProgressDialog extends DialogFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Don't allow the dialog to be recreated by Android, since it wouldn't ever be
// dismissed after recreation.
if (savedInstanceState != null) dismiss();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setCancelable(false);
ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setTitle(getString(R.string.wiping_profile_data_title));
dialog.setMessage(getString(R.string.wiping_profile_data_message));
dialog.setIndeterminate(true);
return dialog;
}
}
@Override
public void onSignOutClicked() {
// In case the user reached this fragment without being signed in, we guard the sign out so
// we do not hit a native crash.
if (!ChromeSigninController.get(getActivity()).isSignedIn()) return;
final Activity activity = getActivity();
final DialogFragment clearDataProgressDialog = new ClearDataProgressDialog();
SigninManager.get(activity).signOut(null, new SigninManager.WipeDataHooks() {
@Override
public void preWipeData() {
clearDataProgressDialog.show(
activity.getFragmentManager(), CLEAR_DATA_PROGRESS_DIALOG_TAG);
}
@Override
public void postWipeData() {
if (clearDataProgressDialog.isAdded()) {
clearDataProgressDialog.dismissAllowingStateLoss();
}
}
});
AccountManagementScreenHelper.logEvent(
ProfileAccountManagementMetrics.SIGNOUT_SIGNOUT,
mGaiaServiceType);
}
@Override
public void onSignOutDialogDismissed(boolean signOutClicked) {
if (!signOutClicked) {
AccountManagementScreenHelper.logEvent(
ProfileAccountManagementMetrics.SIGNOUT_CANCEL,
mGaiaServiceType);
}
}
// ConfirmManagedSyncDataDialog.Listener implementation
@Override
public void onConfirm() {
onSignOutClicked();
}
@Override
public void onCancel() {
onSignOutDialogDismissed(false);
}
// ProfileSyncServiceListener implementation:
@Override
public void syncStateChanged() {
SyncPreference pref = (SyncPreference) findPreference(PREF_SYNC_SETTINGS);
if (pref != null) {
pref.updateSyncSummaryAndIcon();
}
// TODO(crbug/557784): Show notification for sync error
}
// SignInStateObserver implementation:
@Override
public void onSignedIn() {
update();
}
@Override
public void onSignedOut() {
update();
}
/**
* Open the account management UI.
* @param applicationContext An application context.
* @param profile A user profile.
* @param serviceType A signin::GAIAServiceType that triggered the dialog.
*/
public static void openAccountManagementScreen(
Context applicationContext, Profile profile, int serviceType) {
Intent intent = PreferencesLauncher.createIntentForSettingsPage(applicationContext,
AccountManagementFragment.class.getName());
Bundle arguments = new Bundle();
arguments.putInt(SHOW_GAIA_SERVICE_TYPE_EXTRA, serviceType);
intent.putExtra(Preferences.EXTRA_SHOW_FRAGMENT_ARGUMENTS, arguments);
applicationContext.startActivity(intent);
}
/**
* Converts a square user picture to a round user picture.
* @param bitmap A bitmap to convert.
* @return A rounded picture bitmap.
*/
public static Bitmap makeRoundUserPicture(Bitmap bitmap) {
if (bitmap == null) return null;
Bitmap output = Bitmap.createBitmap(
bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
canvas.drawARGB(0, 0, 0, 0);
paint.setAntiAlias(true);
paint.setColor(0xFFFFFFFF);
canvas.drawCircle(bitmap.getWidth() * 0.5f, bitmap.getHeight() * 0.5f,
bitmap.getWidth() * 0.5f, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* Creates a new image with the picture overlaid by the badge.
* @param userPicture A bitmap to overlay on.
* @param badge A bitmap to overlay with.
* @return A bitmap with the badge overlaying the {@code userPicture}.
*/
private static Bitmap overlayChildBadgeOnUserPicture(
Bitmap userPicture, Bitmap badge, Resources resources) {
assert userPicture.getWidth() == resources.getDimensionPixelSize(R.dimen.user_picture_size);
int borderSize = resources.getDimensionPixelOffset(R.dimen.badge_border_size);
int badgeRadius = resources.getDimensionPixelOffset(R.dimen.badge_radius);
// Create a larger image to accommodate the badge which spills the original picture.
int badgedPictureWidth =
resources.getDimensionPixelOffset(R.dimen.badged_user_picture_width);
int badgedPictureHeight =
resources.getDimensionPixelOffset(R.dimen.badged_user_picture_height);
Bitmap badgedPicture = Bitmap.createBitmap(badgedPictureWidth, badgedPictureHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(badgedPicture);
canvas.drawBitmap(userPicture, 0, 0, null);
// Cut a transparent hole through the background image.
// This will serve as a border to the badge being overlaid.
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
int badgeCenterX = badgedPictureWidth - badgeRadius;
int badgeCenterY = badgedPictureHeight - badgeRadius;
canvas.drawCircle(badgeCenterX, badgeCenterY, badgeRadius + borderSize, paint);
// Draw the badge
canvas.drawBitmap(badge, badgeCenterX - badgeRadius, badgeCenterY - badgeRadius, null);
return badgedPicture;
}
/**
* Updates the user name and picture in the cache.
* @param accountId User's account id.
* @param fullName User name.
* @param bitmap User picture.
*/
public static void updateUserNamePictureCache(
String accountId, String fullName, Bitmap bitmap) {
sChildAccountId = null;
sCachedBadgedPicture = null;
sToNamePicture.put(accountId,
new Pair<String, Bitmap>(fullName, makeRoundUserPicture(bitmap)));
}
/**
* @param accountId An account.
* @return A cached user name for a given account.
*/
public static String getCachedUserName(String accountId) {
Pair<String, Bitmap> pair = sToNamePicture.get(accountId);
return pair != null ? pair.first : null;
}
/**
* Gets the user picture for the account from the cache, or returns the default picture if
* unavailable.
*
* @param accountId A child account.
* @return A user picture with badge for a given child account.
*/
public static Bitmap getBadgedUserPicture(String accountId, Resources res) {
if (sChildAccountId != null) {
assert TextUtils.equals(accountId, sChildAccountId);
return sCachedBadgedPicture;
}
sChildAccountId = accountId;
Bitmap picture = getUserPicture(accountId, res);
Bitmap badge = BitmapFactory.decodeResource(res, R.drawable.ic_account_child);
sCachedBadgedPicture = overlayChildBadgeOnUserPicture(picture, badge, res);
return sCachedBadgedPicture;
}
/**
* Gets the user picture for the account from the cache, or returns the default picture if
* unavailable.
*
* @param accountId An account.
* @param resources The collection containing the application resources.
* @return A user picture for a given account.
*/
public static Bitmap getUserPicture(String accountId, Resources resources) {
Pair<String, Bitmap> pair = sToNamePicture.get(accountId);
return pair != null ? pair.second : BitmapFactory.decodeResource(resources,
R.drawable.account_management_no_picture);
}
/**
* Initiate fetching of an image and a picture of a given account. Fetched data will be sent to
* observers of ProfileDownloader.
*
* @param context A context.
* @param profile A profile.
* @param accountName An account name.
*/
public static void startFetchingAccountInformation(
Context context, Profile profile, String accountName) {
if (TextUtils.isEmpty(accountName)) return;
if (sToNamePicture.get(accountName) != null) return;
final int imageSidePixels =
context.getResources().getDimensionPixelOffset(R.dimen.user_picture_size);
ProfileDownloader.startFetchingAccountInfoFor(
context, profile, accountName, imageSidePixels, false);
}
/**
* Prefetch the primary account image and name.
*
* @param context A context to use.
* @param profile A profile to use.
*/
public static void prefetchUserNamePicture(Context context, Profile profile) {
final String accountName = ChromeSigninController.get(context).getSignedInAccountName();
if (TextUtils.isEmpty(accountName)) return;
if (sToNamePicture.get(accountName) != null) return;
ProfileDownloader.addObserver(new ProfileDownloader.Observer() {
@Override
public void onProfileDownloaded(String accountId, String fullName, String givenName,
Bitmap bitmap) {
if (TextUtils.equals(accountName, accountId)) {
updateUserNamePictureCache(accountId, fullName, bitmap);
ProfileDownloader.removeObserver(this);
}
}
});
startFetchingAccountInformation(context, profile, accountName);
}
/**
* @param context A context
* @return Whether the sign out is not disabled due to a child/EDU account.
*/
private static boolean getSignOutAllowedPreferenceValue(Context context) {
return ContextUtils.getAppSharedPreferences()
.getBoolean(SIGN_OUT_ALLOWED, true);
}
/**
* Sets the sign out allowed preference value.
*
* @param context A context
* @param isAllowed True if the sign out is not disabled due to a child/EDU account
*/
public static void setSignOutAllowedPreferenceValue(Context context, boolean isAllowed) {
ContextUtils.getAppSharedPreferences()
.edit()
.putBoolean(SIGN_OUT_ALLOWED, isAllowed)
.apply();
}
}
| bsd-3-clause |
NCIP/cacore-sdk | sdk-toolkit/example-project/junit/src/test/ws/O2OUnidirectionalWSTest.java | 6153 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC, SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk/LICENSE.txt for details.
*/
package test.ws;
import gov.nih.nci.cacoresdk.domain.onetoone.unidirectional.Address;
import gov.nih.nci.cacoresdk.domain.onetoone.unidirectional.Person;
import java.util.ArrayList;
import java.util.Collection;
public class O2OUnidirectionalWSTest extends SDKWSTestBase
{
public static String getTestCaseName()
{
return "One to One Unidirectional WS Test Case";
}
protected Collection<Class> getClasses() throws Exception
{
Collection<Class> mappedKlasses = new ArrayList<Class>();
mappedKlasses.add(Address.class);
mappedKlasses.add(Person.class);
return mappedKlasses;
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch1() throws Exception
{
Class targetClass = Person.class;
Person criteria = new Person();
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(5,results.length);
for (Object obj : results){
Person result = (Person)obj;
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getName());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
*
* @throws Exception
*/
public void testEntireObjectNestedSearch2() throws Exception
{
Class targetClass = Address.class;
Address criteria = new Address();
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(5,results.length);
for (Object obj : results){
Address result = (Address)obj;
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getZip());
}
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* erifies that the associated object is null
*
* @throws Exception
*/
public void testZeroAssociatedObjectsNestedSearch1() throws Exception
{
Class targetClass = Person.class;
Person criteria = new Person();
criteria.setId(new Integer(4));
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(1,results.length);
Person result = (Person)results[0];
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getName());
Object[] addressResults = getAssociationResults(result, "livesAt", 0);
assertEquals(0,addressResults.length);
}
/**
* Uses Nested Search Criteria for search to get associated object
* Verifies that the results are returned
* Verifies size of the result set is 0
*
* @throws Exception
*/
public void testZeroAssociatedObjectsNestedSearch2() throws Exception
{
Class targetClass = Address.class;
Person criteria = new Person();
criteria.setId(new Integer(4));
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(0,results.length);
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
* Verifies that the associated object has required Id
*
* @throws Exception
*/
public void testOneAssociatedObjectNestedSearch1() throws Exception
{
Class targetClass = Person.class;
Person criteria = new Person();
criteria.setId(new Integer(1));
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(1,results.length);
Person result = (Person)results[0];
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getName());
Object[] addressResults = getAssociationResults(result, "livesAt", 0);
assertEquals(1,addressResults.length);
Address address = (Address)addressResults[0];
assertNotNull(address);
assertNotNull(address.getId());
assertNotNull(address.getZip());
assertEquals(new Integer(1),address.getId());
}
/**
* Uses Nested Search Criteria for search to get associated object
* Verifies that the results are returned
* Verifies size of the result set
* Verifies that none of the attribute is null
* Verified the Id attribute's value of the returned object
*
* @throws Exception
*/
public void testOneAssociatedObjectNestedSearch2() throws Exception
{
Class targetClass = Address.class;
Person criteria = new Person();
criteria.setId(new Integer(1));
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(1,results.length);
Address address = (Address)results[0];
assertNotNull(address);
assertNotNull(address.getId());
assertNotNull(address.getZip());
assertEquals(new Integer(1),address.getId());
}
public void testGetAssociation() throws Exception
{
Class targetClass = Person.class;
Person criteria = new Person();
Object[] results = getQueryObjectResults(targetClass, criteria);
assertNotNull(results);
assertEquals(5,results.length);
Person result = (Person)results[0];
assertNotNull(result);
assertNotNull(result.getId());
assertNotNull(result.getName());
Object[] addressResults = getAssociationResults(result, "livesAt", 0);
assertEquals(1,addressResults.length);
Address address = (Address)addressResults[0];
assertNotNull(address);
assertNotNull(address.getId());
assertNotNull(address.getZip());
assertEquals(new Integer(1),address.getId());
}
}
| bsd-3-clause |
NCIP/edct-formbuilder | src/main/java/com/healthcit/cacure/xforms/uicontrols/htmlcontrols/HTMLMultiAnswerMultiChoiceControl.java | 1317 | /*L
* Copyright HealthCare IT, Inc.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/edct-formbuilder/LICENSE.txt for details.
*/
package com.healthcit.cacure.xforms.uicontrols.htmlcontrols;
import com.healthcit.cacure.businessdelegates.QuestionAnswerManager;
import com.healthcit.cacure.model.Answer;
import com.healthcit.cacure.model.TableElement;
import com.healthcit.cacure.xforms.XFormsConstants;
import com.healthcit.cacure.xforms.XFormsConstructionException;
import com.healthcit.cacure.xforms.XFormsUtils;
public class HTMLMultiAnswerMultiChoiceControl extends HTMLMultiAnswerAnyChoiceControl
{
public HTMLMultiAnswerMultiChoiceControl(TableElement fe, QuestionAnswerManager qaManager)
{
super(fe, qaManager);
}
@Override
protected String getSelectControlName()
{
return SELECT_TAG;
}
@Override
protected String getBaseCssClass(Answer answer)
{
return XFormsConstants.CSS_CLASS_ANSWER_RADIO;
}
@Override
protected String getControlTextRef()
{
if(formElement instanceof TableElement)
{
return XFormsUtils.getTableQuestionTextXPath((TableElement)formElement);
}
else
throw new XFormsConstructionException("Element is not a table '" + formElement.getUuid() + "'");
}
}
| bsd-3-clause |
iig-uni-freiburg/SEPIA | src/de/uni/freiburg/iig/telematik/sepia/parser/PNParsingFormat.java | 529 | package de.uni.freiburg.iig.telematik.sepia.parser;
import de.invation.code.toval.file.FileFormat;
import de.uni.freiburg.iig.telematik.sepia.serialize.formats.PNFF_PNML;
import de.uni.freiburg.iig.telematik.sepia.serialize.formats.PNFF_Petrify;
public enum PNParsingFormat {
PNML(new PNFF_PNML()),
PETRIFY(new PNFF_Petrify());
private FileFormat fileFormat = null;
private PNParsingFormat(FileFormat fileFormat){
this.fileFormat = fileFormat;
}
public FileFormat getFileFormat(){
return fileFormat;
}
}
| bsd-3-clause |
jason-p-pickering/dhis2-core | dhis-2/dhis-services/dhis-service-administration/src/main/java/org/hisp/dhis/appstore2/AppVersion.java | 3744 | package org.hisp.dhis.appstore2;
/*
* Copyright (c) 2004-2017, 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.
*/
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.io.FilenameUtils;
import java.util.Date;
/**
* Created by zubair@dhis2.org on 07.09.17.
*/
public class AppVersion
{
private String id;
private String version;
private String minDhisVersion;
private String maxDhisVersion;
private String downloadUrl;
private String demoUrl;
private Date created;
private Date lastUpdated;
public AppVersion()
{
}
@JsonIgnore
public String getFilename()
{
return FilenameUtils.getName( downloadUrl );
}
@JsonProperty
public String getVersion()
{
return version;
}
public void setVersion( String version )
{
this.version = version;
}
@JsonProperty
public String getMinDhisVersion()
{
return minDhisVersion;
}
public void setMinDhisVersion( String minDhisVersion )
{
this.minDhisVersion = minDhisVersion;
}
@JsonProperty
public String getMaxDhisVersion()
{
return maxDhisVersion;
}
public void setMaxDhisVersion( String maxDhisVersion )
{
this.maxDhisVersion = maxDhisVersion;
}
@JsonProperty
public String getDownloadUrl()
{
return downloadUrl;
}
public void setDownloadUrl( String downloadUrl )
{
this.downloadUrl = downloadUrl;
}
@JsonProperty
public String getDemoUrl()
{
return demoUrl;
}
public void setDemoUrl( String demoUrl )
{
this.demoUrl = demoUrl;
}
@JsonProperty
public Date getCreated()
{
return created;
}
public void setCreated( Date created )
{
this.created = created;
}
@JsonProperty
public String getId()
{
return id;
}
public void setId( String id )
{
this.id = id;
}
@JsonProperty
public Date getLastUpdated()
{
return lastUpdated;
}
public void setLastUpdated( Date lastUpdated )
{
this.lastUpdated = lastUpdated;
}
}
| bsd-3-clause |
crosg/Albianj2 | Albianj.Persistence/src/main/java/org/albianj/persistence/object/IFilterCondition.java | 4332 | /*
Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd.
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 Shanghai YUEWEN Information Technology Co., Ltd.
* 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 SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD.
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 REGENTS AND 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.
Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。
这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然:
* 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。
* 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。
* 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。
免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任,
包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、
无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、
偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等),
不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。
*/
package org.albianj.persistence.object;
public interface IFilterCondition extends ICondition {
public RelationalOperator getRelationalOperator();
public void setRelationalOperator(RelationalOperator relationalOperator);
public String getFieldName();
public void setFieldName(String fieldName);
public Class<?> getFieldClass();
public void setFieldClass(Class<?> cls);
public LogicalOperation getLogicalOperation();
public void setLogicalOperation(LogicalOperation logicalOperation);
public Object getValue();
public void setValue(Object value);
public void beginSub();
public void closeSub();
public boolean isBeginSub();
public boolean isCloseSub();
public boolean isAddition();
public void setAddition(boolean isAddition);
public void set(RelationalOperator ro, String fieldName, Class<?> cls,
LogicalOperation lo, Object v);
public void set(String fieldName, Class<?> cls, LogicalOperation lo,
Object v);
}
| bsd-3-clause |
konoha-project/dshell | src/dshell/lang/MultipleException.java | 845 | package dshell.lang;
import libbun.util.BArray;
public class MultipleException extends DShellException {
private static final long serialVersionUID = 164898266354483402L;
private DShellException[] exceptions;
transient private BArray<DShellException> exceptionArray;
public MultipleException(String message, DShellException[] exceptions) {
super(message);
int size = exceptions.length;
this.exceptions = new DShellException[size];
for(int i = 0; i < size; i++) {
this.exceptions[i] = exceptions[i];
}
}
public BArray<DShellException> getExceptions() {
if(this.exceptionArray == null) {
this.exceptionArray = new BArray<DShellException>(0, exceptions);
}
return this.exceptionArray;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + ": " + this.getExceptions().toString();
}
}
| bsd-3-clause |
wat-ze-hex/rocksdb | java/src/test/java/org/rocksdb/OptionsTest.java | 25740 | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
package org.rocksdb;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.ClassRule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class OptionsTest {
@ClassRule
public static final RocksMemoryResource rocksMemoryResource =
new RocksMemoryResource();
public static final Random rand = PlatformRandomHelper.
getPlatformSpecificRandomFactory();
@Test
public void setIncreaseParallelism() {
try (final Options opt = new Options()) {
final int threads = Runtime.getRuntime().availableProcessors() * 2;
opt.setIncreaseParallelism(threads);
}
}
@Test
public void writeBufferSize() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setWriteBufferSize(longValue);
assertThat(opt.writeBufferSize()).isEqualTo(longValue);
}
}
@Test
public void maxWriteBufferNumber() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMaxWriteBufferNumber(intValue);
assertThat(opt.maxWriteBufferNumber()).isEqualTo(intValue);
}
}
@Test
public void minWriteBufferNumberToMerge() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMinWriteBufferNumberToMerge(intValue);
assertThat(opt.minWriteBufferNumberToMerge()).isEqualTo(intValue);
}
}
@Test
public void numLevels() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setNumLevels(intValue);
assertThat(opt.numLevels()).isEqualTo(intValue);
}
}
@Test
public void levelZeroFileNumCompactionTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevelZeroFileNumCompactionTrigger(intValue);
assertThat(opt.levelZeroFileNumCompactionTrigger()).isEqualTo(intValue);
}
}
@Test
public void levelZeroSlowdownWritesTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevelZeroSlowdownWritesTrigger(intValue);
assertThat(opt.levelZeroSlowdownWritesTrigger()).isEqualTo(intValue);
}
}
@Test
public void levelZeroStopWritesTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevelZeroStopWritesTrigger(intValue);
assertThat(opt.levelZeroStopWritesTrigger()).isEqualTo(intValue);
}
}
@Test
public void targetFileSizeBase() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setTargetFileSizeBase(longValue);
assertThat(opt.targetFileSizeBase()).isEqualTo(longValue);
}
}
@Test
public void targetFileSizeMultiplier() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setTargetFileSizeMultiplier(intValue);
assertThat(opt.targetFileSizeMultiplier()).isEqualTo(intValue);
}
}
@Test
public void maxBytesForLevelBase() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxBytesForLevelBase(longValue);
assertThat(opt.maxBytesForLevelBase()).isEqualTo(longValue);
}
}
@Test
public void levelCompactionDynamicLevelBytes() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setLevelCompactionDynamicLevelBytes(boolValue);
assertThat(opt.levelCompactionDynamicLevelBytes())
.isEqualTo(boolValue);
}
}
@Test
public void maxBytesForLevelMultiplier() {
try (final Options opt = new Options()) {
final double doubleValue = rand.nextDouble();
opt.setMaxBytesForLevelMultiplier(doubleValue);
assertThat(opt.maxBytesForLevelMultiplier()).isEqualTo(doubleValue);
}
}
@Test
public void maxBytesForLevelMultiplierAdditional() {
try (final Options opt = new Options()) {
final int intValue1 = rand.nextInt();
final int intValue2 = rand.nextInt();
final int[] ints = new int[]{intValue1, intValue2};
opt.setMaxBytesForLevelMultiplierAdditional(ints);
assertThat(opt.maxBytesForLevelMultiplierAdditional()).isEqualTo(ints);
}
}
@Test
public void maxCompactionBytes() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxCompactionBytes(longValue);
assertThat(opt.maxCompactionBytes()).isEqualTo(longValue);
}
}
@Test
public void softRateLimit() {
try (final Options opt = new Options()) {
final double doubleValue = rand.nextDouble();
opt.setSoftRateLimit(doubleValue);
assertThat(opt.softRateLimit()).isEqualTo(doubleValue);
}
}
@Test
public void softPendingCompactionBytesLimit() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setSoftPendingCompactionBytesLimit(longValue);
assertThat(opt.softPendingCompactionBytesLimit()).isEqualTo(longValue);
}
}
@Test
public void hardRateLimit() {
try (final Options opt = new Options()) {
final double doubleValue = rand.nextDouble();
opt.setHardRateLimit(doubleValue);
assertThat(opt.hardRateLimit()).isEqualTo(doubleValue);
}
}
@Test
public void hardPendingCompactionBytesLimit() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setHardPendingCompactionBytesLimit(longValue);
assertThat(opt.hardPendingCompactionBytesLimit()).isEqualTo(longValue);
}
}
@Test
public void level0FileNumCompactionTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevel0FileNumCompactionTrigger(intValue);
assertThat(opt.level0FileNumCompactionTrigger()).isEqualTo(intValue);
}
}
@Test
public void level0SlowdownWritesTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevel0SlowdownWritesTrigger(intValue);
assertThat(opt.level0SlowdownWritesTrigger()).isEqualTo(intValue);
}
}
@Test
public void level0StopWritesTrigger() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setLevel0StopWritesTrigger(intValue);
assertThat(opt.level0StopWritesTrigger()).isEqualTo(intValue);
}
}
@Test
public void rateLimitDelayMaxMilliseconds() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setRateLimitDelayMaxMilliseconds(intValue);
assertThat(opt.rateLimitDelayMaxMilliseconds()).isEqualTo(intValue);
}
}
@Test
public void arenaBlockSize() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setArenaBlockSize(longValue);
assertThat(opt.arenaBlockSize()).isEqualTo(longValue);
}
}
@Test
public void disableAutoCompactions() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setDisableAutoCompactions(boolValue);
assertThat(opt.disableAutoCompactions()).isEqualTo(boolValue);
}
}
@Test
public void purgeRedundantKvsWhileFlush() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setPurgeRedundantKvsWhileFlush(boolValue);
assertThat(opt.purgeRedundantKvsWhileFlush()).isEqualTo(boolValue);
}
}
@Test
public void verifyChecksumsInCompaction() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setVerifyChecksumsInCompaction(boolValue);
assertThat(opt.verifyChecksumsInCompaction()).isEqualTo(boolValue);
}
}
@Test
public void maxSequentialSkipInIterations() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxSequentialSkipInIterations(longValue);
assertThat(opt.maxSequentialSkipInIterations()).isEqualTo(longValue);
}
}
@Test
public void inplaceUpdateSupport() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setInplaceUpdateSupport(boolValue);
assertThat(opt.inplaceUpdateSupport()).isEqualTo(boolValue);
}
}
@Test
public void inplaceUpdateNumLocks() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setInplaceUpdateNumLocks(longValue);
assertThat(opt.inplaceUpdateNumLocks()).isEqualTo(longValue);
}
}
@Test
public void memtablePrefixBloomSizeRatio() {
try (final Options opt = new Options()) {
final double doubleValue = rand.nextDouble();
opt.setMemtablePrefixBloomSizeRatio(doubleValue);
assertThat(opt.memtablePrefixBloomSizeRatio()).isEqualTo(doubleValue);
}
}
@Test
public void memtableHugePageSize() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMemtableHugePageSize(longValue);
assertThat(opt.memtableHugePageSize()).isEqualTo(longValue);
}
}
@Test
public void bloomLocality() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setBloomLocality(intValue);
assertThat(opt.bloomLocality()).isEqualTo(intValue);
}
}
@Test
public void maxSuccessiveMerges() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxSuccessiveMerges(longValue);
assertThat(opt.maxSuccessiveMerges()).isEqualTo(longValue);
}
}
@Test
public void minPartialMergeOperands() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMinPartialMergeOperands(intValue);
assertThat(opt.minPartialMergeOperands()).isEqualTo(intValue);
}
}
@Test
public void optimizeFiltersForHits() {
try (final Options opt = new Options()) {
final boolean aBoolean = rand.nextBoolean();
opt.setOptimizeFiltersForHits(aBoolean);
assertThat(opt.optimizeFiltersForHits()).isEqualTo(aBoolean);
}
}
@Test
public void createIfMissing() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setCreateIfMissing(boolValue);
assertThat(opt.createIfMissing()).
isEqualTo(boolValue);
}
}
@Test
public void createMissingColumnFamilies() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setCreateMissingColumnFamilies(boolValue);
assertThat(opt.createMissingColumnFamilies()).
isEqualTo(boolValue);
}
}
@Test
public void errorIfExists() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setErrorIfExists(boolValue);
assertThat(opt.errorIfExists()).isEqualTo(boolValue);
}
}
@Test
public void paranoidChecks() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setParanoidChecks(boolValue);
assertThat(opt.paranoidChecks()).
isEqualTo(boolValue);
}
}
@Test
public void maxTotalWalSize() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxTotalWalSize(longValue);
assertThat(opt.maxTotalWalSize()).
isEqualTo(longValue);
}
}
@Test
public void maxOpenFiles() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMaxOpenFiles(intValue);
assertThat(opt.maxOpenFiles()).isEqualTo(intValue);
}
}
@Test
public void useFsync() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setUseFsync(boolValue);
assertThat(opt.useFsync()).isEqualTo(boolValue);
}
}
@Test
public void dbLogDir() {
try (final Options opt = new Options()) {
final String str = "path/to/DbLogDir";
opt.setDbLogDir(str);
assertThat(opt.dbLogDir()).isEqualTo(str);
}
}
@Test
public void walDir() {
try (final Options opt = new Options()) {
final String str = "path/to/WalDir";
opt.setWalDir(str);
assertThat(opt.walDir()).isEqualTo(str);
}
}
@Test
public void deleteObsoleteFilesPeriodMicros() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setDeleteObsoleteFilesPeriodMicros(longValue);
assertThat(opt.deleteObsoleteFilesPeriodMicros()).
isEqualTo(longValue);
}
}
@Test
public void baseBackgroundCompactions() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setBaseBackgroundCompactions(intValue);
assertThat(opt.baseBackgroundCompactions()).
isEqualTo(intValue);
}
}
@Test
public void maxBackgroundCompactions() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMaxBackgroundCompactions(intValue);
assertThat(opt.maxBackgroundCompactions()).
isEqualTo(intValue);
}
}
@Test
public void maxSubcompactions() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMaxSubcompactions(intValue);
assertThat(opt.maxSubcompactions()).
isEqualTo(intValue);
}
}
@Test
public void maxBackgroundFlushes() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setMaxBackgroundFlushes(intValue);
assertThat(opt.maxBackgroundFlushes()).
isEqualTo(intValue);
}
}
@Test
public void maxLogFileSize() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxLogFileSize(longValue);
assertThat(opt.maxLogFileSize()).isEqualTo(longValue);
}
}
@Test
public void logFileTimeToRoll() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setLogFileTimeToRoll(longValue);
assertThat(opt.logFileTimeToRoll()).
isEqualTo(longValue);
}
}
@Test
public void keepLogFileNum() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setKeepLogFileNum(longValue);
assertThat(opt.keepLogFileNum()).isEqualTo(longValue);
}
}
@Test
public void maxManifestFileSize() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setMaxManifestFileSize(longValue);
assertThat(opt.maxManifestFileSize()).
isEqualTo(longValue);
}
}
@Test
public void tableCacheNumshardbits() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setTableCacheNumshardbits(intValue);
assertThat(opt.tableCacheNumshardbits()).
isEqualTo(intValue);
}
}
@Test
public void walSizeLimitMB() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setWalSizeLimitMB(longValue);
assertThat(opt.walSizeLimitMB()).isEqualTo(longValue);
}
}
@Test
public void walTtlSeconds() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setWalTtlSeconds(longValue);
assertThat(opt.walTtlSeconds()).isEqualTo(longValue);
}
}
@Test
public void manifestPreallocationSize() throws RocksDBException {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setManifestPreallocationSize(longValue);
assertThat(opt.manifestPreallocationSize()).
isEqualTo(longValue);
}
}
@Test
public void useDirectReads() {
try(final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setUseDirectReads(boolValue);
assertThat(opt.useDirectReads()).isEqualTo(boolValue);
}
}
@Test
public void useDirectWrites() {
try(final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setUseDirectWrites(boolValue);
assertThat(opt.useDirectWrites()).isEqualTo(boolValue);
}
}
@Test
public void allowMmapReads() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setAllowMmapReads(boolValue);
assertThat(opt.allowMmapReads()).isEqualTo(boolValue);
}
}
@Test
public void allowMmapWrites() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setAllowMmapWrites(boolValue);
assertThat(opt.allowMmapWrites()).isEqualTo(boolValue);
}
}
@Test
public void isFdCloseOnExec() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setIsFdCloseOnExec(boolValue);
assertThat(opt.isFdCloseOnExec()).isEqualTo(boolValue);
}
}
@Test
public void statsDumpPeriodSec() {
try (final Options opt = new Options()) {
final int intValue = rand.nextInt();
opt.setStatsDumpPeriodSec(intValue);
assertThat(opt.statsDumpPeriodSec()).isEqualTo(intValue);
}
}
@Test
public void adviseRandomOnOpen() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setAdviseRandomOnOpen(boolValue);
assertThat(opt.adviseRandomOnOpen()).isEqualTo(boolValue);
}
}
@Test
public void useAdaptiveMutex() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setUseAdaptiveMutex(boolValue);
assertThat(opt.useAdaptiveMutex()).isEqualTo(boolValue);
}
}
@Test
public void bytesPerSync() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setBytesPerSync(longValue);
assertThat(opt.bytesPerSync()).isEqualTo(longValue);
}
}
@Test
public void allowConcurrentMemtableWrite() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setAllowConcurrentMemtableWrite(boolValue);
assertThat(opt.allowConcurrentMemtableWrite()).isEqualTo(boolValue);
}
}
@Test
public void enableWriteThreadAdaptiveYield() {
try (final Options opt = new Options()) {
final boolean boolValue = rand.nextBoolean();
opt.setEnableWriteThreadAdaptiveYield(boolValue);
assertThat(opt.enableWriteThreadAdaptiveYield()).isEqualTo(boolValue);
}
}
@Test
public void writeThreadMaxYieldUsec() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setWriteThreadMaxYieldUsec(longValue);
assertThat(opt.writeThreadMaxYieldUsec()).isEqualTo(longValue);
}
}
@Test
public void writeThreadSlowYieldUsec() {
try (final Options opt = new Options()) {
final long longValue = rand.nextLong();
opt.setWriteThreadSlowYieldUsec(longValue);
assertThat(opt.writeThreadSlowYieldUsec()).isEqualTo(longValue);
}
}
@Test
public void env() {
try (final Options options = new Options();
final Env env = Env.getDefault()) {
options.setEnv(env);
assertThat(options.getEnv()).isSameAs(env);
}
}
@Test
public void linkageOfPrepMethods() {
try (final Options options = new Options()) {
options.optimizeUniversalStyleCompaction();
options.optimizeUniversalStyleCompaction(4000);
options.optimizeLevelStyleCompaction();
options.optimizeLevelStyleCompaction(3000);
options.optimizeForPointLookup(10);
options.prepareForBulkLoad();
}
}
@Test
public void compressionTypes() {
try (final Options options = new Options()) {
for (final CompressionType compressionType :
CompressionType.values()) {
options.setCompressionType(compressionType);
assertThat(options.compressionType()).
isEqualTo(compressionType);
assertThat(CompressionType.valueOf("NO_COMPRESSION")).
isEqualTo(CompressionType.NO_COMPRESSION);
}
}
}
@Test
public void compressionPerLevel() {
try (final ColumnFamilyOptions columnFamilyOptions =
new ColumnFamilyOptions()) {
assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty();
List<CompressionType> compressionTypeList =
new ArrayList<>();
for (int i = 0; i < columnFamilyOptions.numLevels(); i++) {
compressionTypeList.add(CompressionType.NO_COMPRESSION);
}
columnFamilyOptions.setCompressionPerLevel(compressionTypeList);
compressionTypeList = columnFamilyOptions.compressionPerLevel();
for (final CompressionType compressionType : compressionTypeList) {
assertThat(compressionType).isEqualTo(
CompressionType.NO_COMPRESSION);
}
}
}
@Test
public void differentCompressionsPerLevel() {
try (final ColumnFamilyOptions columnFamilyOptions =
new ColumnFamilyOptions()) {
columnFamilyOptions.setNumLevels(3);
assertThat(columnFamilyOptions.compressionPerLevel()).isEmpty();
List<CompressionType> compressionTypeList = new ArrayList<>();
compressionTypeList.add(CompressionType.BZLIB2_COMPRESSION);
compressionTypeList.add(CompressionType.SNAPPY_COMPRESSION);
compressionTypeList.add(CompressionType.LZ4_COMPRESSION);
columnFamilyOptions.setCompressionPerLevel(compressionTypeList);
compressionTypeList = columnFamilyOptions.compressionPerLevel();
assertThat(compressionTypeList.size()).isEqualTo(3);
assertThat(compressionTypeList).
containsExactly(
CompressionType.BZLIB2_COMPRESSION,
CompressionType.SNAPPY_COMPRESSION,
CompressionType.LZ4_COMPRESSION);
}
}
@Test
public void compactionStyles() {
try (final Options options = new Options()) {
for (final CompactionStyle compactionStyle :
CompactionStyle.values()) {
options.setCompactionStyle(compactionStyle);
assertThat(options.compactionStyle()).
isEqualTo(compactionStyle);
assertThat(CompactionStyle.valueOf("FIFO")).
isEqualTo(CompactionStyle.FIFO);
}
}
}
@Test
public void maxTableFilesSizeFIFO() {
try (final Options opt = new Options()) {
long longValue = rand.nextLong();
// Size has to be positive
longValue = (longValue < 0) ? -longValue : longValue;
longValue = (longValue == 0) ? longValue + 1 : longValue;
opt.setMaxTableFilesSizeFIFO(longValue);
assertThat(opt.maxTableFilesSizeFIFO()).
isEqualTo(longValue);
}
}
@Test
public void rateLimiterConfig() {
try (final Options options = new Options();
final Options anotherOptions = new Options()) {
final RateLimiterConfig rateLimiterConfig =
new GenericRateLimiterConfig(1000, 100 * 1000, 1);
options.setRateLimiterConfig(rateLimiterConfig);
// Test with parameter initialization
anotherOptions.setRateLimiterConfig(
new GenericRateLimiterConfig(1000));
}
}
@Test
public void rateLimiter() {
try (final Options options = new Options();
final Options anotherOptions = new Options()) {
final RateLimiter rateLimiter =
new RateLimiter(1000, 100 * 1000, 1);
options.setRateLimiter(rateLimiter);
// Test with parameter initialization
anotherOptions.setRateLimiter(
new RateLimiter(1000));
}
}
@Test
public void shouldSetTestPrefixExtractor() {
try (final Options options = new Options()) {
options.useFixedLengthPrefixExtractor(100);
options.useFixedLengthPrefixExtractor(10);
}
}
@Test
public void shouldSetTestCappedPrefixExtractor() {
try (final Options options = new Options()) {
options.useCappedPrefixExtractor(100);
options.useCappedPrefixExtractor(10);
}
}
@Test
public void shouldTestMemTableFactoryName()
throws RocksDBException {
try (final Options options = new Options()) {
options.setMemTableConfig(new VectorMemTableConfig());
assertThat(options.memTableFactoryName()).
isEqualTo("VectorRepFactory");
options.setMemTableConfig(
new HashLinkedListMemTableConfig());
assertThat(options.memTableFactoryName()).
isEqualTo("HashLinkedListRepFactory");
}
}
@Test
public void statistics() {
try (final Options options = new Options()) {
Statistics statistics = options.createStatistics().
statisticsPtr();
assertThat(statistics).isNotNull();
try (final Options anotherOptions = new Options()) {
statistics = anotherOptions.statisticsPtr();
assertThat(statistics).isNotNull();
}
}
}
}
| bsd-3-clause |
thejoshwolfe/jax | src/net/wolfesoftware/jax/ast/ImportStatement.java | 304 | package net.wolfesoftware.jax.ast;
public class ImportStatement extends SwitchElement
{
public ImportStatement(ParseElement content)
{
super(content);
}
public static final int TYPE = 0x30b40631;
public int getElementType()
{
return TYPE;
}
}
| bsd-3-clause |
NCIP/cagrid-core | caGrid/projects/service-tools/src/org/cagrid/tools/events/EventHandlingException.java | 1304 | /**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package org.cagrid.tools.events;
/**
* @author <A href="mailto:langella@bmi.osu.edu">Stephen Langella </A>
* @author <A href="mailto:oster@bmi.osu.edu">Scott Oster </A>
* @author <A href="mailto:hastings@bmi.osu.edu">Shannon Hastings </A>
* @author <A href="mailto:ervin@bmi.osu.edu">David Ervin</A>
*/
public class EventHandlingException extends Exception {
public EventHandlingException() {
// TODO Auto-generated constructor stub
}
public EventHandlingException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public EventHandlingException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public EventHandlingException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
| bsd-3-clause |
ninjin/corbit | src/main/java/corbit/tagdep/dict/CTBTagDictionary.java | 2798 | /*
* Corbit, a text analyzer
*
* Copyright (c) 2010-2012, Jun Hatori
* 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 names of the authors nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package corbit.tagdep.dict;
import java.util.Set;
import java.util.TreeSet;
public class CTBTagDictionary extends TagDictionary
{
private static final long serialVersionUID = 6692431815764780778L;
static final String[] ssCtbTags = { "AD", "AS", "BA", "CC", "CD", "CS",
"DEC", "DEG", "DER", "DEV", "DT", "ETC", "FW", "IJ", "JJ", "LB",
"LC", "M", "MSP", "NN", "NR", "NT", "OD", "ON", "P", "PN", "PU",
"SB", "SP", "VA", "VC", "VE", "VV", "URL" };
static final String[] ssOpenTags =
{ "AD", "CD", "FW", "JJ", "M", "MSP", "NN", "NR", "NT", "OD", "VA", "VV", "URL" };
static final String[] ssClosedTags = { "AS", "BA", "CC", "CS", "DEC", "DEG",
"DER", "DEV", "DT", "ETC", "IJ", "LB", "LC", "ON", "P", "PN", "PU",
"SB", "SP", "VC", "VE" };
public CTBTagDictionary(boolean bUseClosedTags)
{
super(
bUseClosedTags ? ssOpenTags : ssCtbTags,
bUseClosedTags ? ssClosedTags : null,
ssCtbTags
);
}
public static Set<String> copyTagSet()
{
Set<String> ss = new TreeSet<String>();
for (int i = 0; i < ssCtbTags.length; ++i)
ss.add(ssCtbTags[i]);
return ss;
}
}
| bsd-3-clause |
tlin-fei/ds4p | DS4P/access-control-service/xdsb-repository-client/src/main/java/gov/samhsa/acs/xdsb/repository/wsclient/adapter/RetrieveDocumentSetResponseFilter.java | 5543 | /*******************************************************************************
* Open Behavioral Health Information Technology Architecture (OBHITA.org)
*
* 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 <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package gov.samhsa.acs.xdsb.repository.wsclient.adapter;
import gov.samhsa.acs.common.namespace.PepNamespaceContext;
import gov.samhsa.acs.common.tool.DocumentXmlConverter;
import gov.samhsa.acs.xdsb.common.XdsbErrorFactory;
import ihe.iti.xds_b._2007.RetrieveDocumentSetResponse;
import ihe.iti.xds_b._2007.RetrieveDocumentSetResponse.DocumentResponse;
import java.util.LinkedList;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* The Class RetrieveDocumentSetResponseFilter.
*/
public class RetrieveDocumentSetResponseFilter {
/** The converter. */
private DocumentXmlConverter converter;
/** The xdsb error factory. */
private XdsbErrorFactory xdsbErrorFactory;
/**
* Instantiates a new retrieve document set response filter.
*/
public RetrieveDocumentSetResponseFilter() {
super();
}
/**
* Instantiates a new retrieve document set response filter.
*
* @param converter
* the converter
* @param xdsbErrorFactory
* the xdsb error factory
*/
public RetrieveDocumentSetResponseFilter(DocumentXmlConverter converter,
XdsbErrorFactory xdsbErrorFactory) {
super();
this.converter = converter;
this.xdsbErrorFactory = xdsbErrorFactory;
}
/**
* Filter by patient and author.
*
* @param response
* the response
* @param patientId
* the patient id
* @param authorNPI
* the author npi
* @return the retrieve document set response
* @throws Throwable
* the throwable
*/
public RetrieveDocumentSetResponse filterByPatientAndAuthor(
RetrieveDocumentSetResponse response, String patientId,
String authorNPI) throws Throwable {
LinkedList<DocumentResponse> removeList = new LinkedList<DocumentResponse>();
for (DocumentResponse docResponse : response.getDocumentResponse()) {
String docString = new String(docResponse.getDocument());
String xPathExpr = "//hl7:recordTarget/child::hl7:patientRole/child::hl7:id";
String attributeName = "extension";
String docPatientId = getAttributeValue(docString, xPathExpr,
attributeName);
xPathExpr = "//hl7:author/child::hl7:assignedAuthor/child::hl7:id";
attributeName = "extension";
String docAuthorNPI = getAttributeValue(docString, xPathExpr,
attributeName);
if (!patientId.equals(docPatientId)
|| !authorNPI.equals(docAuthorNPI)) {
removeList.add(docResponse);
}
}
if (removeList.size() > 0) {
response.getDocumentResponse().removeAll(removeList);
response = xdsbErrorFactory
.setRetrieveDocumentSetResponseRegistryErrorListFilteredByPatientAndAuthor(
response, removeList.size(), patientId, authorNPI);
}
return response;
}
/**
* Gets the attribute value.
*
* @param docString
* the doc string
* @param xPathExpr
* the x path expr
* @param attributeName
* the attribute name
* @return the attribute value
* @throws Exception
* the exception
* @throws XPathExpressionException
* the x path expression exception
*/
private String getAttributeValue(String docString, String xPathExpr,
String attributeName) throws Exception, XPathExpressionException {
Document doc = converter.loadDocument(docString);
// Create XPath instance
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
xpath.setNamespaceContext(new PepNamespaceContext());
Node node = (Node) xpath.evaluate(xPathExpr, doc, XPathConstants.NODE);
return node.getAttributes().getNamedItem(attributeName).getNodeValue();
}
}
| bsd-3-clause |
ut-osa/laminar | jikesrvm-3.0.0/rvm/src/org/jikesrvm/osr/bytecodes/LongStore.java | 1074 | /*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.jikesrvm.osr.bytecodes;
/**
* BC_LongStore: lstore, lstore_<n>
*/
public class LongStore extends PseudoBytecode {
private int bsize;
private byte[] codes;
private int lnum;
public LongStore(int local) {
this.lnum = local;
if (local <= 255) {
bsize = 2;
codes = makeOUcode(JBC_lstore, local);
} else {
bsize = 4;
codes = makeWOUUcode(JBC_lstore, local);
}
}
public byte[] getBytes() {
return codes;
}
public int getSize() {
return bsize;
}
public int stackChanges() {
return -2;
}
public String toString() {
return "lstore " + lnum;
}
}
| bsd-3-clause |
inceptus/inceptusRobot-2012 | src/org/inceptus/chassis/Drive.java | 2019 | package org.inceptus.chassis;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.RobotDrive.MotorType;
import org.inceptus.debug.Debug;
/**
*
* @author innoying
*/
public class Drive {
//Motors
private Jaguar leftFront;
private Jaguar rightFront;
private Jaguar leftRear;
private Jaguar rightRear;
//Drive
private RobotDrive robotDrive;
//accelerometer
//private ADXL345_I2C accelerometer;
//Gyro
private Gyro gyro;
//Initilize
public Drive(){
//Setup the drive motors
leftFront = new Jaguar(7);
rightFront = new Jaguar(8);
leftRear = new Jaguar(9);
rightRear = new Jaguar(10);
//Setup the Drive
robotDrive = new RobotDrive(leftFront, leftRear, rightFront, rightRear);
//Invert the motors
robotDrive.setInvertedMotor(MotorType.kFrontLeft, true);
robotDrive.setInvertedMotor(MotorType.kRearRight, false);
robotDrive.setInvertedMotor(MotorType.kFrontLeft, true);
robotDrive.setInvertedMotor(MotorType.kRearLeft, true);
}
public void driveWithValues(double x, double y, double rotation){
//Drive using values
robotDrive.mecanumDrive_Cartesian(-x, -y, -rotation, 0);
}
public void stop(){
//Stop the motors
robotDrive.stopMotor();
}
public void balance(){
final double ratio = .02;
double angle = gyro.getAngle();
double speed = (angle * ratio);
Debug.log(angle + "\t" + speed);
if (angle >= 5 && angle <= -5){
stop();
}else if(angle <= 35 && angle >= -35){
robotDrive.mecanumDrive_Cartesian(0.0, -speed, 0.0, 0.00);
}else{
stop();
}
}
}
| bsd-3-clause |
synergynet/synergynet2.5 | synergynet2.5/src/main/java/apps/lightrays/raytracer/scene/Camera.java | 4020 | package apps.lightrays.raytracer.scene;
import java.awt.Dimension;
/**
* The Class Camera.
*/
public class Camera {
/** The Constant FRONT. */
private static final Vector FRONT = new Vector(0, 0, 1);
/** The Constant LEFT. */
private static final Vector LEFT = new Vector(-1, 0, 0);
/** The Constant UP. */
private static final Vector UP = new Vector(0, 1, 0);
/** The right with scale. */
private Vector _dir, upWithScale, rightWithScale;
/** The eye position. */
private Vector eyePosition;
/** The fov. */
private double fov;
/** The front. */
private Vector front;
/** The left. */
private Vector left;
/** The lookat_target. */
private Vector lookat_target;
/** The up. */
private Vector up;
/** The viewport_xsize. */
private double viewport_xsize;
/** The viewport_ysize. */
private double viewport_ysize;
/**
* Instantiates a new camera.
*/
public Camera() {
this(new Dimension(640, 480));
}
/**
* Instantiates a new camera.
*
* @param viewport_size
* the viewport_size
*/
public Camera(Dimension viewport_size) {
eyePosition = new Vector(0, -5, 1);
up = new Vector(UP);
front = new Vector(FRONT);
left = new Vector(LEFT);
fov = 40;
viewport_xsize = viewport_size.getWidth();
viewport_ysize = viewport_size.getHeight();
updateVectors();
}
/**
* Generate ray.
*
* @param s
* the s
* @param x
* the x
* @param y
* the y
* @return the ray
*/
public final Ray generateRay(Scene s, double x, double y) {
double u, v;
// double mi_x, mi_y;
// 1. Convert integer image coordinates into values in the range [-0.5,
// 0.5]
u = (x - (viewport_xsize / 2.0)) / viewport_xsize;
v = ((viewport_ysize - y - 1) - (viewport_ysize / 2.0))
/ viewport_ysize;
Vector dv = upWithScale.multiplyNew(v);
Vector du = rightWithScale.multiplyNew(u);
Vector dir = dv.addNew(du).addNew(_dir);
// 3. Build up and return a ray with origin in the eye position and with
// calculated direction
Ray ray;
ray = new Ray(s, eyePosition.toPoint(), dir, 0);
return ray;
}
/**
* Generate supersampled rays.
*
* @param s
* the s
* @param x
* the x
* @param y
* the y
* @param side
* the side
* @param f
* the f
* @return the ray[][]
*/
public final Ray[][] generateSupersampledRays(Scene s, int x, int y,
int side, double f) {
Ray[][] r = new Ray[(side * 2) + 1][(side * 2) + 1];
for (int i = -side; i <= side; i++) {
for (int j = -side; j <= side; j++) {
int x_index = side + i;
int y_index = side + j;
r[x_index][y_index] = generateRay(s, x + (i / f), y + (j / f));
}
}
return r;
}
/**
* Sets the look at.
*
* @param focusedPosition
* the new look at
*/
public void setLookAt(Vector focusedPosition) {
this.lookat_target = new Vector(focusedPosition);
front = focusedPosition.subtractNew(eyePosition);
left = front.crossProductNew(UP);
// should we do something with up here?
updateVectors();
}
/**
* Sets the viewpoint.
*
* @param eyePosition
* the new viewpoint
*/
public void setViewpoint(Vector eyePosition) {
this.eyePosition = eyePosition;
// updateVectors(); // now done in setLookAt
if (lookat_target != null) {
setLookAt(lookat_target);
}
}
/**
* Sets the viewport size.
*
* @param size
* the new viewport size
*/
public void setViewportSize(Dimension size) {
viewport_xsize = size.getWidth();
viewport_ysize = size.getHeight();
updateVectors();
}
/**
* Update vectors.
*/
public void updateVectors() {
up.normalise();
left.normalise();
front.normalise();
double fovFactor = viewport_xsize / viewport_ysize;
_dir = front.multiplyNew(0.5);
upWithScale = up.multiplyNew(Math.tan(Math.toRadians(fov / 2)));
rightWithScale = left.multiplyNew(-fovFactor
* Math.tan(Math.toRadians(fov / 2)));
}
}
| bsd-3-clause |
NCIP/camod | software/camod/src/gov/nih/nci/camod/bean/PublicationBean.java | 3737 | /*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
/**
*
*/
package gov.nih.nci.camod.bean;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.util.DateUtils;
import gov.nih.nci.camod.util.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
/**
* Publication view bean
*
* @author tanq, pansu
*
*/
public class PublicationBean extends FileBean {
private static final String delimiter = ";";
private List<Author> authors = new ArrayList<Author>();
private Author theAuthor = new Author();
private String primaryAuthor;
protected String createdBy;
private String displayName = "";
public PublicationBean() {
domainFile = new XmlPublication();
domainFile.setUriExternal(false);
}
public PublicationBean(String id) {
domainFile.setId(new Long(id));
}
public PublicationBean(XmlPublication publication) {
super(publication);
this.domainFile = publication;
Collection<Author> authorCollection = publication.getAuthorCollection();
if (authorCollection != null && authorCollection.size() > 0) {
List<Author> authorslist = new ArrayList<Author>(authorCollection);
Collections.sort(authorslist, new Comparator<Author>() {
public int compare(Author o1, Author o2) {
return (int) (o1.getCreatedDate().compareTo(o2
.getCreatedDate()));
}
});
authors = authorslist;
}
}
public PublicationBean(XmlPublication publication, String[] sampleNames) {
this(publication);
}
/**
* Copy PubMed data from source PublicationBean to this PublicationBean.
*
* @param source
* @param taget
*/
public void copyPubMedFieldsFromPubMedXML(PublicationBean source) {
XmlPublication oldPub = (XmlPublication) this.getDomainFile();
XmlPublication xmlPub = (XmlPublication) source.getDomainFile();
oldPub.setPubMedId(xmlPub.getPubMedId());
oldPub.setDescription(xmlPub.getDescription());
oldPub.setTitle(xmlPub.getTitle());
oldPub.setJournalName(xmlPub.getJournalName());
oldPub.setStartPage(xmlPub.getStartPage());
oldPub.setEndPage(xmlPub.getEndPage());
oldPub.setVolume(xmlPub.getVolume());
oldPub.setYear(xmlPub.getYear());
this.setAuthors(source.getAuthors());
if (authors != null && authors.size() > 0 ) {
Author author = authors.get(0);
setPrimaryAuthor( author.getFirstName() + " " + author.getLastName() + " " + author.getInitial() );
}
}
public boolean equals(Object obj) {
boolean eq = false;
if (obj instanceof PublicationBean) {
PublicationBean c = (PublicationBean) obj;
Long thisId = this.domainFile.getId();
if (thisId != null && thisId.equals(c.getDomainFile().getId())) {
eq = true;
}
}
return eq;
}
/**
* @return the authors
*/
public List<Author> getAuthors() {
return authors;
}
/**
* @param authors
* the authors to set
*/
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
public Author getTheAuthor() {
return theAuthor;
}
public void setTheAuthor(Author theAuthor) {
this.theAuthor = theAuthor;
}
public void resetDomainCopy(String createdBy, XmlPublication copy) {
// don't need to reset anything because publications can be shared
}
public String getPrimaryAuthor() {
return primaryAuthor;
}
public void setPrimaryAuthor(String primaryAuthor) {
this.primaryAuthor = primaryAuthor;
}
}
| bsd-3-clause |
mikem2005/vijava | src/com/vmware/vim25/ProfileExecuteResult.java | 2861 | /*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. 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 VMWARE, INC. 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.vmware.vim25;
/**
@author Steve Jin (sjin@vmware.com)
*/
public class ProfileExecuteResult extends DynamicData
{
public String status;
public HostConfigSpec configSpec;
public String[] inapplicablePath;
public ProfileDeferredPolicyOptionParameter[] requireInput;
public ProfileExecuteError[] error;
public String getStatus()
{
return this.status;
}
public HostConfigSpec getConfigSpec()
{
return this.configSpec;
}
public String[] getInapplicablePath()
{
return this.inapplicablePath;
}
public ProfileDeferredPolicyOptionParameter[] getRequireInput()
{
return this.requireInput;
}
public ProfileExecuteError[] getError()
{
return this.error;
}
public void setStatus(String status)
{
this.status=status;
}
public void setConfigSpec(HostConfigSpec configSpec)
{
this.configSpec=configSpec;
}
public void setInapplicablePath(String[] inapplicablePath)
{
this.inapplicablePath=inapplicablePath;
}
public void setRequireInput(ProfileDeferredPolicyOptionParameter[] requireInput)
{
this.requireInput=requireInput;
}
public void setError(ProfileExecuteError[] error)
{
this.error=error;
}
} | bsd-3-clause |
vivin/GenericTree | src/test/java/net/vivin/TestGenericTree.java | 14869 | /*
Copyright 2010 Vivin Suresh Paliath
Distributed under the BSD License
*/
package net.vivin;
import org.testng.annotations.Test;
import java.util.*;
import static org.testng.Assert.*;
public class TestGenericTree {
@Test
public void TestRootIsNullOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertNull(tree.getRoot());
}
@Test
public void TestNumberOfNodesIsZeroOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertEquals(tree.getNumberOfNodes(), 0);
}
@Test
public void TestIsEmptyIsTrueOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertTrue(tree.isEmpty());
}
@Test
void TestExistsIsFalseOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
String dataToFind = "";
assertFalse(tree.exists(dataToFind));
}
@Test
void TestFindReturnsNullOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
String dataToFind = "";
assertNull(tree.find(dataToFind));
}
@Test
void TestPreOrderBuildReturnsNullListOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertNull(tree.build(GenericTreeTraversalOrderEnum.PRE_ORDER));
}
@Test
void TestPostOrderBuildReturnsNullListOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertNull(tree.build(GenericTreeTraversalOrderEnum.POST_ORDER));
}
@Test
void TestPreOrderBuildWithDepthReturnsNullMapOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertNull(tree.buildWithDepth(GenericTreeTraversalOrderEnum.PRE_ORDER));
}
@Test
void TestPostOrderBuildWithDepthReturnsNullMapOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertNull(tree.buildWithDepth(GenericTreeTraversalOrderEnum.POST_ORDER));
}
@Test
void TestToStringReturnsEmptyStringOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertEquals(tree.toString(), "");
}
@Test
void TestToStringWithDepthReturnsEmptyStringOnNewTreeCreation() {
GenericTree<String> tree = new GenericTree<String>();
assertEquals(tree.toStringWithDepth(), "");
}
@Test
void TestSetRootGetRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>();
tree.setRoot(root);
assertNotNull(tree.getRoot());
}
@Test
void TestNumberOfNodesIsOneWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>();
tree.setRoot(root);
assertEquals(tree.getNumberOfNodes(), 1);
}
@Test
void TestEmptyIsFalseWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>();
tree.setRoot(root);
assertFalse(tree.isEmpty());
}
@Test
void TestPreOrderBuildListSizeIsOneWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>("root");
tree.setRoot(root);
assertEquals(tree.build(GenericTreeTraversalOrderEnum.PRE_ORDER).size(), 1);
}
@Test
void TestPostOrderBuildListSizeIsOneWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>("root");
tree.setRoot(root);
assertEquals(tree.build(GenericTreeTraversalOrderEnum.POST_ORDER).size(), 1);
}
@Test
void TestPreOrderBuildWithDepthSizeIsOneWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>("root");
tree.setRoot(root);
assertEquals(tree.buildWithDepth(GenericTreeTraversalOrderEnum.PRE_ORDER).size(), 1);
}
@Test
void TestPostOrderBuildWithDepthSizeIsOneWithNonNullRoot() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> root = new GenericTreeNode<String>("root");
tree.setRoot(root);
assertEquals(tree.buildWithDepth(GenericTreeTraversalOrderEnum.POST_ORDER).size(), 1);
}
/*
Tree looks like:
A
/ \
B C
\
D
For the following tests
*/
@Test
void TestNumberOfNodes() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
assertEquals(tree.getNumberOfNodes(), 4);
}
@Test
void TestExistsReturnsTrue() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
String dataToFindD = "D";
assertTrue(tree.exists(dataToFindD));
}
@Test
void TestFindReturnsNonNull() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
String dataToFindD = "D";
assertNotNull(tree.find(dataToFindD));
}
@Test
void TestExistsReturnsFalse() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
String dataToFindE = "E";
assertFalse(tree.exists(dataToFindE));
}
@Test
void TestFindReturnsNull() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
String dataToFindE = "E";
assertNull(tree.find(dataToFindE));
}
// Pre-order traversal will give us A B C D
@Test
void TestPreOrderBuild() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
List<GenericTreeNode<String>> preOrderList = new ArrayList<GenericTreeNode<String>>();
preOrderList.add(new GenericTreeNode<String>("A"));
preOrderList.add(new GenericTreeNode<String>("B"));
preOrderList.add(new GenericTreeNode<String>("C"));
preOrderList.add(new GenericTreeNode<String>("D"));
// Instead of checking equalities on the lists themselves, we can check equality on the toString's
// they should generate the same toString's
assertEquals(tree.build(GenericTreeTraversalOrderEnum.PRE_ORDER).toString(), preOrderList.toString());
}
//Post-order traversal will give us B D C A
@Test
void TestPostOrderBuild() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
List<GenericTreeNode<String>> postOrderList = new ArrayList<GenericTreeNode<String>>();
postOrderList.add(new GenericTreeNode<String>("B"));
postOrderList.add(new GenericTreeNode<String>("D"));
postOrderList.add(new GenericTreeNode<String>("C"));
postOrderList.add(new GenericTreeNode<String>("A"));
// Instead of checking equalities on the lists themselves, we can check equality on the toString's
// they should generate the same toString's
assertEquals(tree.build(GenericTreeTraversalOrderEnum.POST_ORDER).toString(), postOrderList.toString());
}
//Pre-order traversal with depth will give us A:0, B:1, C:1, D:2
@Test
void TestPreOrderBuildWithDepth() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
Map<GenericTreeNode<String>, Integer> preOrderMapWithDepth = new LinkedHashMap<GenericTreeNode<String>, Integer>();
preOrderMapWithDepth.put(new GenericTreeNode<String>("A"), 0);
preOrderMapWithDepth.put(new GenericTreeNode<String>("B"), 1);
preOrderMapWithDepth.put(new GenericTreeNode<String>("C"), 1);
preOrderMapWithDepth.put(new GenericTreeNode<String>("D"), 2);
// Instead of checking equalities on the maps themselves, we can check equality on the toString's
// they should generate the same toString's
assertEquals(tree.buildWithDepth(GenericTreeTraversalOrderEnum.PRE_ORDER).toString(), preOrderMapWithDepth.toString());
}
//Post-order traversal with depth will give us B:1, D:2, C:1, A:0
@Test
void TestPostOrderBuildWithDepth() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
Map<GenericTreeNode<String>, Integer> postOrderMapWithDepth = new LinkedHashMap<GenericTreeNode<String>, Integer>();
postOrderMapWithDepth.put(new GenericTreeNode<String>("B"), 1);
postOrderMapWithDepth.put(new GenericTreeNode<String>("D"), 2);
postOrderMapWithDepth.put(new GenericTreeNode<String>("C"), 1);
postOrderMapWithDepth.put(new GenericTreeNode<String>("A"), 0);
// Instead of checking equalities on the maps themselves, we can check equality on the toString's
// they should generate the same toString's
assertEquals(tree.buildWithDepth(GenericTreeTraversalOrderEnum.POST_ORDER).toString(), postOrderMapWithDepth.toString());
}
//toString and toStringWithDepth both use pre-order traversal
@Test
void TestToString() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
List<GenericTreeNode<String>> preOrderList = new ArrayList<GenericTreeNode<String>>();
preOrderList.add(new GenericTreeNode<String>("A"));
preOrderList.add(new GenericTreeNode<String>("B"));
preOrderList.add(new GenericTreeNode<String>("C"));
preOrderList.add(new GenericTreeNode<String>("D"));
assertEquals(tree.toString(), preOrderList.toString());
}
@Test
void TestToStringWithDepth() {
GenericTree<String> tree = new GenericTree<String>();
GenericTreeNode<String> rootA = new GenericTreeNode<String>("A");
GenericTreeNode<String> childB = new GenericTreeNode<String>("B");
GenericTreeNode<String> childC = new GenericTreeNode<String>("C");
GenericTreeNode<String> childD = new GenericTreeNode<String>("D");
childC.addChild(childD);
rootA.addChild(childB);
rootA.addChild(childC);
tree.setRoot(rootA);
Map<GenericTreeNode<String>, Integer> preOrderMapWithDepth = new LinkedHashMap<GenericTreeNode<String>, Integer>();
preOrderMapWithDepth.put(new GenericTreeNode<String>("A"), 0);
preOrderMapWithDepth.put(new GenericTreeNode<String>("B"), 1);
preOrderMapWithDepth.put(new GenericTreeNode<String>("C"), 1);
preOrderMapWithDepth.put(new GenericTreeNode<String>("D"), 2);
assertEquals(tree.toStringWithDepth(), preOrderMapWithDepth.toString());
}
}
| bsd-3-clause |
NCIP/cacore-sdk-pre411 | src/gov/nih/nci/codegen/core/transformer/UML13CastorMappingTransformer.java | 23004 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details.
*/
package gov.nih.nci.codegen.core.transformer;
import gov.nih.nci.codegen.core.BaseArtifact;
import gov.nih.nci.codegen.core.ConfigurationException;
import gov.nih.nci.codegen.core.XMLConfigurable;
import gov.nih.nci.codegen.core.filter.UML13ClassifierFilter;
import gov.nih.nci.codegen.core.filter.UML13ModelElementFilter;
import gov.nih.nci.codegen.core.util.UML13Utils;
import gov.nih.nci.codegen.core.util.XMLUtils;
import gov.nih.nci.codegen.framework.FilteringException;
import gov.nih.nci.codegen.framework.TransformationException;
import gov.nih.nci.codegen.framework.Transformer;
import gov.nih.nci.common.exception.XMLUtilityException;
import gov.nih.nci.common.util.Constant;
import gov.nih.nci.common.util.caCOREMarshaller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.jmi.reflect.RefObject;
import org.apache.log4j.Logger;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.omg.uml.foundation.core.AssociationEnd;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.ModelElement;
import org.omg.uml.foundation.core.UmlClass;
import org.omg.uml.modelmanagement.Model;
import org.omg.uml.modelmanagement.UmlPackage;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2001-2004 SAIC. Copyright 2001-2003 SAIC. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* 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 disclaimer of Article 3, below. 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.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by the SAIC and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or SAIC-Frederick.
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED 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 NATIONAL CANCER INSTITUTE,
* SAIC, OR THEIR AFFILIATES 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.
* <!-- LICENSE_TEXT_END -->
*/
/**
* Produces an XML schema for the project object model
* <p>
* <p>
* The content model for this transformer's configuration element is as follows:
* <p>
* <code>
* <pre>
*
*
*
* <!ELEMENT transformer (param, filter)>
* <!ATTLIST transformer
* name CDATA #REQUIRED
* className CDATA #FIXED gov.nih.nci.codegen.core.transformer.UML13CastorMappingTransformer>
* <!ELEMENT param EMPTY>
* <!ATTLIST param
* name CDATA #FIXED packageName
* value CDATA #REQUIRED>
* <!ELEMENT filter ... see {@link gov.nih.nci.codegen.core.filter.UML13ClassifierFilter#configure(org.w3c.dom.Element)} ...
*
*
*
* </pre>
* </code>
* <p>
* As you can see, this transformer expects a nested filter element. The reason
* is that this transformer produces a single Artifact (an XML file) from a
* collection of model elements.
* <p>
* UML13OJBRepTransformer expects to be passed an instance of
* org.omg.uml.modelmanagement.Model. It uses UML13ModelElementFilter to obtain
* all model elements in the model. Then it use UML13Classifier to obtain the
* classifiers selected by the contents of the nested filter element. Then it
* iterates through these classifiers, building the class-descriptor elements.
* <p>
* A Collection containing a single Artifact is returned by this transformer's
* execute method. The name attribute of the Artifact is set to "ojb_repository"
* and its source attribute is set to the String that represents the XML
* document.
* <p>
*
* @author caBIO Team
* @version 1.0
*/
public class UML13CastorMappingTransformer implements Transformer, XMLConfigurable {
private static Logger log = Logger.getLogger(UML13CastorMappingTransformer.class);
public static final String PROPERTIES_FILENAME = "xml.properties";
public static final String PROPERTIES_CONTEXT_KEY = "context";
public static final String PROPERTIES_CLASSIFICATION_KEY = "classification";
public static final String PROPERTIES_VERSION_KEY = "version";
public static final String PROPERTIES_NS_PREFIX_KEY = "ns_prefix";
private UML13ClassifierFilter _classifierFilt;
private String _pkgName;
private boolean _includeAssociations = false;
private boolean _includeFieldHandler = false;
private Properties _properties;
private String context;
private String classification;
private String version;
private String nsprefix;
/**
*
*/
public UML13CastorMappingTransformer() {
super();
}
private String loadProperty(String key) throws IOException{
if(_properties == null){
try {
_properties = new Properties();
_properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(this.PROPERTIES_FILENAME));
} catch (IOException e) {
throw new IOException("Error loading " + caCOREMarshaller.PROPERTIES_FILENAME + " file. Please make sure the file is in your classpath.");
}
}
return _properties.getProperty(key);
}
/**
* @see gov.nih.nci.codegen.framework.Transformer#execute(javax.jmi.reflect.RefObject,
* java.util.Collection)
*/
public Collection execute(RefObject modelElement, Collection artifacts) throws TransformationException {
if (modelElement == null) {
log.error("model element is null");
throw new TransformationException("model element is null");
}
if (!(modelElement instanceof Model)) {
log.error("model element not instance of Model");
throw new TransformationException(
"model element not instance of Model");
}
ArrayList newArtifacts = new ArrayList();
UML13ModelElementFilter meFilt = new UML13ModelElementFilter();
ArrayList umlExtentCol = new ArrayList();
umlExtentCol.add(modelElement.refOutermostPackage());
Collection classifiers = null;
try {
classifiers = _classifierFilt.execute(meFilt.execute(umlExtentCol));
} catch (FilteringException ex) {
log.error("couldn't filter model elements" + ex.getMessage());
throw new TransformationException("couldn't filter model elements",
ex);
}
Document doc = generateRepository(classifiers);
XMLOutputter p = new XMLOutputter();
p.setFormat(Format.getPrettyFormat());
newArtifacts.add(new BaseArtifact("castormapping", modelElement, p.outputString(doc)));
return newArtifacts;
}
private Document generateRepository(Collection classifiers) {
Element mappingEl = new Element("mapping");
//DocType docType = new DocType("mapping","SYSTEM","mapping.dtd");
DocType docType = new DocType("mapping","-//EXOLAB/Castor Object Mapping DTD Version 1.0//EN","http://www.castor.org/mapping.dtd");
Document doc = new Document();
doc.setDocType(docType);
Collection sortedClassifier = sortClassifiers(classifiers);
for (Iterator i = sortedClassifier.iterator(); i.hasNext();) {
UmlClass klass = (UmlClass) i.next();
try {
doMapping(klass, mappingEl);
} catch (XMLUtilityException ex) {
log.error("XMLUtilityException: ", ex);
}
}
doc.setRootElement(mappingEl);
return doc;
}
private Collection sortClassifiers(Collection classifiers)
{
// The caCOREMarsheller has problem with forward references. Sorting
// the class with the list generalizations to the top.
class caCOREComparer implements Comparator {
public int compare(Object obj1, Object obj2)
{
return determineWeight((UmlClass)obj1) - determineWeight((UmlClass)obj2);
}
private int determineWeight(UmlClass obj)
{
int count = -1;
UmlClass superClass = obj;
do
{
superClass = UML13Utils.getSuperClass(superClass);
count++;
}while (superClass!=null);
return count;
}
};
ArrayList list = new ArrayList(classifiers);
Collections.sort(list, new caCOREComparer());
return list;
}
private String getNamespaceURI(UmlClass klass) throws XMLUtilityException{
StringBuffer nsURI = new StringBuffer();
try {
context = loadProperty(this.PROPERTIES_CONTEXT_KEY);
classification = loadProperty(this.PROPERTIES_CLASSIFICATION_KEY);
version = loadProperty(this.PROPERTIES_VERSION_KEY);
nsprefix= loadProperty(this.PROPERTIES_NS_PREFIX_KEY);
} catch (IOException e) {
log.error("Error reading default xml mapping file " + e.getMessage()); //To change body of catch statement use File | Settings | File Templates.
throw new XMLUtilityException("Error reading default xml mapping file " + e.getMessage(), e);
}
String packageName = getPackage(klass);
nsURI.append(nsprefix);
nsURI.append(classification);
nsURI.append(Constant.DOT);
nsURI.append(context);
nsURI.append(Constant.FORWARD_SLASH);
nsURI.append(version);
nsURI.append(Constant.FORWARD_SLASH);
nsURI.append(packageName);
return nsURI.toString();
}
private void doMapping(UmlClass klass, Element mappingEl) throws XMLUtilityException {
String superClassName =null;
UmlClass superClass = UML13Utils.getSuperClass(klass);
if (superClass != null) {
superClassName = getPackage(superClass)+ Constant.DOT+superClass.getName();
}
String classElName = "class";
Element classEl = new Element(classElName);
mappingEl.addContent(classEl);
classEl.setAttribute("name", getPackage(klass)+Constant.DOT+klass.getName());
classEl.setAttribute("identity", "id");
if (superClassName!=null){
classEl.setAttribute("extends", superClassName);
}
Element maptoelement = new Element("map-to");
maptoelement.setAttribute("xml", klass.getName());
String nsURI = getNamespaceURI(klass);
maptoelement.setAttribute("ns-uri",nsURI);
classEl.addContent(maptoelement);
//Do properties
for (Iterator i = UML13Utils.getAttributes(klass).iterator(); i.hasNext();) {
org.omg.uml.foundation.core.Attribute att = (org.omg.uml.foundation.core.Attribute) i.next();
Element field = new Element("field");
field.setAttribute("name", att.getName());
log.debug("Field name: " + att.getName());
String qName = getQualifiedName(att.getType());
if (qName.equalsIgnoreCase("collection")) {
log.debug("Handling type 'collection' - qName: " + qName);
field.setAttribute("type", "string");
field.setAttribute("collection", qName);
Namespace namespace = Namespace.getNamespace(qName,nsURI);
Element bind = new Element("bind-xml");
bind.setAttribute("name", qName + ":" + att.getName());
bind.setAttribute("QName-prefix",qName,namespace);
bind.setAttribute("node", "attribute");
field.addContent(bind);
} else {
field.setAttribute("type", getQualifiedName(att.getType()));
Element bind = new Element("bind-xml");
bind.setAttribute("name", att.getName());
bind.setAttribute("node", "attribute");
field.addContent(bind);
}
classEl.addContent(field);
}
if (_includeAssociations) {
log.debug("*********** klass: " + klass.getName());
log.debug("*********** UML13Utils.getAssociationEnds(klass).size(): " + UML13Utils.getAssociationEnds(klass).size());
for (Iterator i = UML13Utils.getAssociationEnds(klass).iterator(); i.hasNext();) {
AssociationEnd thisEnd = (AssociationEnd) i.next();
AssociationEnd otherEnd = UML13Utils.getOtherAssociationEnd(thisEnd);
addSequenceAssociationElement(classEl, klass,thisEnd, otherEnd);
}
}
}
private void addSequenceAssociationElement(Element mappingEl, UmlClass klass, AssociationEnd thisEnd, AssociationEnd otherEnd) throws XMLUtilityException {
if (otherEnd.isNavigable()) {
/** If classes belong to the same package then do not qualify the association
*
*/
log.debug("mappingEl.getName(): " + mappingEl);
log.debug("klass.getName(): " + klass.getName());
log.debug("thisEnd.getName(): " + thisEnd.getName());
log.debug("thisEnd.getType().getName(): " + thisEnd.getType().getName());
log.debug("otherEnd.getName(): " + otherEnd.getName());
log.debug("otherEnd.getType().getName(): " + otherEnd.getType().getName());
if (UML13Utils.isMany2One(thisEnd, otherEnd)) {
log.debug("UML13Utils.isMany2One(thisEnd, otherEnd): " + true);
log.debug("lowerBound: " + UML13Utils.getLowerBound(thisEnd, otherEnd));
log.debug("upperBound: " + UML13Utils.getUpperBound(thisEnd, otherEnd));
Element field = new Element("field");
field.setAttribute("name", otherEnd.getName());
String associationPackage = getPackage(otherEnd.getType());
field.setAttribute("type", associationPackage + Constant.DOT + otherEnd.getType().getName());
if (_includeFieldHandler) {
field.setAttribute("handler", "gov.nih.nci.common.util.CastorDomainObjectFieldHandler" );
}
Element bind = new Element("bind-xml");
bind.setAttribute("name", otherEnd.getType().getName()); //otherEnd.getName()
bind.setAttribute("type", associationPackage + Constant.DOT+otherEnd.getType().getName());
bind.setAttribute("location", otherEnd.getName());
bind.setAttribute("node", "element");
field.addContent(bind);
mappingEl.addContent(field);
} else if (UML13Utils.isMany2Many(thisEnd, otherEnd) || UML13Utils.isOne2Many(thisEnd, otherEnd)){
log.debug("UML13Utils.isMany2Many(thisEnd, otherEnd): " + UML13Utils.isMany2Many(thisEnd, otherEnd));
log.debug("UML13Utils.isOne2Many(thisEnd, otherEnd): " + UML13Utils.isOne2Many(thisEnd, otherEnd));
log.debug("lowerBound: " + UML13Utils.getLowerBound(thisEnd, otherEnd));
log.debug("upperBound: " + UML13Utils.getUpperBound(thisEnd, otherEnd));
Element field = new Element("field");
field.setAttribute("name", otherEnd.getName());
String associationPackage = getPackage(otherEnd.getType());
field.setAttribute("type", associationPackage + Constant.DOT+otherEnd.getType().getName());
field.setAttribute("collection", "collection" );
if (_includeFieldHandler) {
field.setAttribute("handler", "gov.nih.nci.common.util.CastorCollectionFieldHandler" );
}
//for container = false
//field.setAttribute("container", "false" );
Element bind = new Element("bind-xml");
//bind.setAttribute("auto-naming", "deriveByClass");
// for container = false
//bind.setAttribute("name", otherEnd.getName());
// for container = true
bind.setAttribute("name", otherEnd.getType().getName());
bind.setAttribute("type", associationPackage+Constant.DOT+otherEnd.getType().getName());
bind.setAttribute("location", otherEnd.getName());
bind.setAttribute("node", "element");
field.addContent(bind);
mappingEl.addContent(field);
}
}
}
/**
* @param classifiers
* @return
*/
private Document generateConfig(Collection classifiers) {
Element configEl = new Element("DAOConfiguration");
for (Iterator i = classifiers.iterator(); i.hasNext();) {
Classifier klass = (Classifier) i.next();
UmlPackage pkg = null;
if (_pkgName != null) {
pkg = UML13Utils.getPackage(UML13Utils.getModel(klass),
_pkgName);
} else {
pkg = UML13Utils.getModel(klass);
}
}
Document doc = new Document();
doc.setRootElement(configEl);
return doc;
}
/**
* @see gov.nih.nci.codegen.core.JDOMConfigurable#configure(org.jdom.Element)
*/
public void configure(org.w3c.dom.Element config) throws ConfigurationException {
org.w3c.dom.Element filterEl = XMLUtils.getChild(config, "filter");
if (filterEl == null) {
log.error("no child filter element found");
throw new ConfigurationException("no child filter element found");
}
String className = filterEl.getAttribute("className");
if (className == null) {
log.error("no filter class name specified");
throw new ConfigurationException("no filter class name specified");
}
_pkgName = getParameter(config, "basePackage");
log.debug("basePackage: " + _pkgName);
String isIncludeAssociations = getParameter(config, "includeAssociations");
log.debug("includeAssociations: " + isIncludeAssociations);
if (isIncludeAssociations != null && isIncludeAssociations.length() > 0) {
_includeAssociations = new Boolean(isIncludeAssociations).booleanValue();
}
String isIncludeFieldHandler = getParameter(config, "includeFieldHandler");
log.debug("includeFieldHandler: " + isIncludeFieldHandler);
if (isIncludeFieldHandler != null && isIncludeFieldHandler.length() > 0) {
_includeFieldHandler = new Boolean(isIncludeFieldHandler).booleanValue();
}
try {
_classifierFilt = (UML13ClassifierFilter) Class.forName(className)
.newInstance();
} catch (Exception ex) {
log.error("Couldn't instantiate "
+ className);
throw new ConfigurationException("Couldn't instantiate "
+ className);
}
_classifierFilt.configure(filterEl);
}
private String getQualifiedName(ModelElement me) {
String qName = null;
UmlPackage pkg = null;
if (_pkgName != null) {
pkg = UML13Utils.getPackage(UML13Utils.getModel(me), _pkgName);
} else {
pkg = UML13Utils.getModel(me);
}
qName = UML13Utils.getNamespaceName(pkg, me) + Constant.DOT + me.getName();
int i = qName.lastIndexOf(Constant.DOT);
if (qName.startsWith(".") || qName.startsWith("java")) {
qName = qName.substring(i+1);
}
if ("HashSet".equalsIgnoreCase(qName)) {
return "set";
}
if ("HashMap".equalsIgnoreCase(qName)){
return "map";
}
log.debug("*** qName: " + qName);
return qName.toLowerCase();
}
/**
* @param klass
* @return
*/
/*
private String getPackage(UmlClass klass) {
UmlPackage pkg = null;
if (_pkgName != null) {
pkg = UML13Utils.getPackage(UML13Utils.getModel(klass), _pkgName);
} else {
pkg = UML13Utils.getModel(klass);
}
return UML13Utils.getNamespaceName(pkg, klass);
}
*/
private String getPackage(ModelElement klass) {
UmlPackage pkg = null;
if (_pkgName != null) {
pkg = UML13Utils.getPackage(UML13Utils.getModel(klass), _pkgName);
} else {
pkg = UML13Utils.getModel(klass);
}
return UML13Utils.getNamespaceName(pkg, klass);
}
private String getParameter(org.w3c.dom.Element config, String paramName) {
String param = null;
List params = XMLUtils.getChildren(config, "param");
for (Iterator i = params.iterator(); i.hasNext();) {
org.w3c.dom.Element paramEl = (org.w3c.dom.Element) i.next();
if (paramName.equals(paramEl.getAttribute("name"))) {
param = paramEl.getAttribute("value");
break;
}
}
return param;
}
}
| bsd-3-clause |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/maps/ImageReadable.java | 340 | package abi44_0_0.host.exp.exponent.modules.api.components.maps;
import android.graphics.Bitmap;
import com.google.android.gms.maps.model.BitmapDescriptor;
public interface ImageReadable {
public void setIconBitmap(Bitmap bitmap);
public void setIconBitmapDescriptor(BitmapDescriptor bitmapDescriptor);
public void update();
}
| bsd-3-clause |
cmu-cylab-privacylens/PrivacyLens | src/main/java/edu/cmu/ece/privacylens/consent/flow/ar/DecorateEvents.java | 5682 | /*
* COPYRIGHT_BOILERPLATE
* Copyright (c) 2016 Carnegie Mellon University
* 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 names 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.
*
* 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 SWITCH 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 edu.cmu.ece.privacylens.consent.flow.ar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import org.opensaml.profile.context.ProfileRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.core.collection.MutableAttributeMap;
import org.springframework.webflow.execution.RequestContext;
import org.springframework.webflow.execution.RequestContextHolder;
import edu.cmu.ece.privacylens.IdPHelper;
import edu.cmu.ece.privacylens.Oracle;
import edu.cmu.ece.privacylens.ar.AdminViewHelper;
import edu.cmu.ece.privacylens.ar.AttributeReleaseModule;
import edu.cmu.ece.privacylens.ar.LoginEvent;
import edu.cmu.ece.privacylens.config.General;
import net.shibboleth.idp.profile.context.ProfileInterceptorContext;
import net.shibboleth.idp.profile.interceptor.AbstractProfileInterceptorAction;
import net.shibboleth.utilities.java.support.component.ComponentInitializationException;
/**
* Attribute consent action to populate the interface with useful textual info
*
* @event {@link org.opensaml.profile.action.EventIds#PROCEED_EVENT_ID}
* @post See above.
*/
public class DecorateEvents extends AbstractProfileInterceptorAction {
/** Class logger. */
@Nonnull private final Logger log = LoggerFactory.getLogger(DecorateEvents.class);
/** {@inheritDoc} */
@Override protected void doInitialize() throws ComponentInitializationException {
super.doInitialize();
}
/** {@inheritDoc} */
@Override protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
@Nonnull final ProfileInterceptorContext interceptorContext) {
final RequestContext requestContext =
RequestContextHolder.getRequestContext();
final MutableAttributeMap<Object> flowScope =
requestContext.getFlowScope();
final String relyingPartyId =
IdPHelper.getRelyingPartyId(profileRequestContext);
flowScope.put("service",
Oracle.getInstance().getServiceName(relyingPartyId));
flowScope.put("idpOrganization", General.getInstance().getOrganizationName());
final AttributeReleaseModule attributeReleaseModule =
IdPHelper.getAttributeReleaseModule();
final String principalName =
IdPHelper.getPrincipalName(profileRequestContext);
final int limitLoginEvents = AdminViewHelper.limitLoginEvents;
final int limitRelyingPartyList = AdminViewHelper.limitRelyingPartyList;
final List<LoginEvent> lastLoginEvents =
attributeReleaseModule.listLoginEvents(principalName, "",
limitLoginEvents);
final List<Map> loginEventList =
AdminViewHelper.processLoginEvents(lastLoginEvents);
flowScope.put("lastLoginEvents", loginEventList);
if (loginEventList.size() == limitLoginEvents) {
flowScope.put("loginEventFull", true);
}
final List<String> servicesList =
attributeReleaseModule.listRelyingParties(principalName,
limitRelyingPartyList);
final Map<String, List> serviceLoginEventMap =
new HashMap<String, List>();
for (final String service : servicesList) {
final List<LoginEvent> serviceLoginEvents =
attributeReleaseModule.listLoginEvents(principalName,
service, limitLoginEvents);
final List<Map> serviceLoginEventList =
AdminViewHelper.processLoginEvents(serviceLoginEvents);
serviceLoginEventMap.put(service, serviceLoginEventList);
}
flowScope.put("relyingPartiesList", servicesList);
flowScope.put("serviceLoginEvents", serviceLoginEventMap);
if (servicesList.size() == limitRelyingPartyList) {
flowScope.put("relyingPartyListFull", true);
}
log.debug("{} Decorated login data", getLogPrefix());
}
}
| bsd-3-clause |
dudaerich/WS-TransferExample | client/src/main/java/org/apache/cxf/example/wstransferexample/client/handlers/CreateResHandler.java | 2756 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.apache.cxf.example.wstransferexample.client.handlers;
import java.util.List;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.cxf.example.wstransferexample.client.ClientResourceManager;
import org.apache.cxf.example.wstransferexample.client.Config;
import org.apache.cxf.example.wstransferexample.client.KeywordHandler;
import org.apache.cxf.example.wstransferexample.client.XMLManager;
import org.apache.cxf.example.wstransferexample.client.exception.HandlerException;
import org.apache.cxf.example.wstransferexample.client.exception.NotFoundException;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.ws.transfer.Create;
import org.apache.cxf.ws.transfer.CreateResponse;
import org.apache.cxf.ws.transfer.Representation;
import org.apache.cxf.ws.transfer.resourcefactory.ResourceFactory;
import org.w3c.dom.Document;
/**
*
* @author erich
*/
public class CreateResHandler implements KeywordHandler {
private static ResourceFactory client;
public CreateResHandler() {
if (client == null) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(ResourceFactory.class);
factory.setAddress(Config.getInstance().getServerUrl());
client = (ResourceFactory) factory.create();
}
}
public void handle(List<String> parameters) throws HandlerException {
if (parameters.size() != 1) {
throw new HandlerException("Wrong number of arguments.");
}
try {
int i = Integer.valueOf(parameters.get(0));
Document doc = XMLManager.getInstance().getDocument(i - 1).getDocument();
Representation representation = new Representation();
representation.setAny(doc.getDocumentElement());
Create createRequest = new Create();
createRequest.setRepresentation(representation);
CreateResponse createResponse = client.create(createRequest);
ClientResourceManager.getInstance().saveResource(createResponse.getResourceCreated());
} catch (NumberFormatException ex) {
throw new HandlerException("Parameter must be integer.");
} catch (NotFoundException ex) {
throw new HandlerException("XML is not found.");
} catch (SOAPFaultException ex) {
throw new HandlerException(ex.getLocalizedMessage());
}
}
public String getHelp() {
return "[numberOfXML] - Creates XMLResource and saves its reference.";
}
}
| bsd-3-clause |
atomixnmc/jmonkeyengine | jme3-vr/src/main/java/com/jme3/shadow/AbstractShadowFilterVR.java | 12166 | package com.jme3.shadow;
/*
* Copyright (c) 2009-2018 jMonkeyEngine
* 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 'jMonkeyEngine' 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.
*/
import com.jme3.asset.AssetManager;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.material.Material;
import com.jme3.material.RenderState;
import com.jme3.math.Matrix4f;
import com.jme3.math.Vector4f;
import com.jme3.post.Filter;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue;
import com.jme3.shadow.CompareMode;
import com.jme3.shadow.EdgeFilteringMode;
import com.jme3.texture.FrameBuffer;
import java.io.IOException;
/**
* Generic abstract filter that holds common implementations for the different
* shadow filters.
*
* @author Rémy Bouquet aka Nehon
* @author reden - phr00t - https://github.com/phr00t
* @author Julien Seinturier - COMEX SA - <a href="http://www.seinturier.fr">http://www.seinturier.fr</a>
* @param <T> the type of the underlying renderer (subclass of {@link AbstractShadowRendererVR}).
*/
public abstract class AbstractShadowFilterVR<T extends AbstractShadowRendererVR> extends Filter {
protected T shadowRenderer;
protected ViewPort viewPort;
/**
* Abstract class constructor
*
* @param manager the application asset manager
* @param shadowMapSize the size of the rendered shadowmaps (512,1024,2048,
* etc...)
* @param nbShadowMaps the number of shadow maps rendered (the more shadow
* maps the more quality, the less fps).
* @param shadowRenderer the shadowRenderer to use for this Filter
*/
@SuppressWarnings("all")
protected AbstractShadowFilterVR(AssetManager manager, int shadowMapSize, T shadowRenderer) {
super("Post Shadow");
material = new Material(manager, "Common/MatDefs/Shadow/PostShadowFilter.j3md");
this.shadowRenderer = shadowRenderer;
this.shadowRenderer.setPostShadowMaterial(material);
//this is legacy setting for shadows with backface shadows
this.shadowRenderer.setRenderBackFacesShadows(true);
}
@SuppressWarnings("all")
protected AbstractShadowFilterVR(AssetManager manager, int shadowMapSize, T shadowRenderer, String useMatDef) {
super("Post Shadow");
material = new Material(manager, useMatDef);
this.shadowRenderer = shadowRenderer;
this.shadowRenderer.setPostShadowMaterial(material);
}
@Override
protected Material getMaterial() {
return material;
}
@Override
protected boolean isRequiresDepthTexture() {
return true;
}
/**
* Get the {@link Material material} used by this filter.
* @return the {@link Material material} used by this filter.
*/
public Material getShadowMaterial() {
return material;
}
Vector4f tmpv = new Vector4f();
@Override
protected void preFrame(float tpf) {
shadowRenderer.preFrame(tpf);
material.setMatrix4("ViewProjectionMatrixInverse", viewPort.getCamera().getViewProjectionMatrix().invert());
Matrix4f m = viewPort.getCamera().getViewProjectionMatrix();
material.setVector4("ViewProjectionMatrixRow2", tmpv.set(m.m20, m.m21, m.m22, m.m23));
}
@Override
protected void postQueue(RenderQueue queue) {
shadowRenderer.postQueue(queue);
if(shadowRenderer.skipPostPass){
//removing the shadow map so that the post pass is skipped
material.setTexture("ShadowMap0", null);
}
}
@Override
protected void postFrame(RenderManager renderManager, ViewPort viewPort, FrameBuffer prevFilterBuffer, FrameBuffer sceneBuffer) {
if(!shadowRenderer.skipPostPass){
shadowRenderer.setPostShadowParams();
}
}
@Override
protected void initFilter(AssetManager manager, RenderManager renderManager, ViewPort vp, int w, int h) {
shadowRenderer.needsfallBackMaterial = true;
shadowRenderer.initialize(renderManager, vp);
this.viewPort = vp;
}
/**
* How far the shadows are rendered in the view
*
* @see #setShadowZExtend(float zFar)
* @return shadowZExtend
*/
public float getShadowZExtend() {
return shadowRenderer.getShadowZExtend();
}
/**
* Set the distance from the eye where the shadows will be rendered default
* value is dynamically computed to the shadow casters/receivers union bound
* zFar, capped to view frustum far value.
*
* @param zFar the zFar values that override the computed one
*/
public void setShadowZExtend(float zFar) {
shadowRenderer.setShadowZExtend(zFar);
}
/**
* Define the length over which the shadow will fade out when using a
* shadowZextend
*
* @param length the fade length in world units
*/
public void setShadowZFadeLength(float length) {
shadowRenderer.setShadowZFadeLength(length);
}
/**
* get the length over which the shadow will fade out when using a
* shadowZextend
*
* @return the fade length in world units
*/
public float getShadowZFadeLength() {
return shadowRenderer.getShadowZFadeLength();
}
/**
* returns the shadow intensity
*
* @see #setShadowIntensity(float shadowIntensity)
* @return shadowIntensity
*/
public float getShadowIntensity() {
return shadowRenderer.getShadowIntensity();
}
/**
* Set the shadowIntensity, the value should be between 0 and 1, a 0 value
* gives a bright and invisible shadow, a 1 value gives a pitch black
* shadow, default is 0.7
*
* @param shadowIntensity the darkness of the shadow
*/
final public void setShadowIntensity(float shadowIntensity) {
shadowRenderer.setShadowIntensity(shadowIntensity);
}
/**
* returns the edges thickness <br>
*
* @see #setEdgesThickness(int edgesThickness)
* @return edgesThickness
*/
public int getEdgesThickness() {
return shadowRenderer.getEdgesThickness();
}
/**
* Sets the shadow edges thickness. default is 1, setting it to lower values
* can help to reduce the jagged effect of the shadow edges
* @param edgesThickness the edge thickness.
*/
public void setEdgesThickness(int edgesThickness) {
shadowRenderer.setEdgesThickness(edgesThickness);
}
/**
* isFlushQueues does nothing and is kept only for backward compatibility.
* @return <code>false</code>
* @deprecated does nothing and is kept only for backward compatibility.
*/
@Deprecated
public boolean isFlushQueues() {
return shadowRenderer.isFlushQueues();
}
/**
* setFlushQueues does nothing now and is kept only for backward compatibility.
* @param flushQueues can be <code>true</code> or <code>false</code>.
* @deprecated does nothing now and is kept only for backward compatibility.
*/
@Deprecated
public void setFlushQueues(boolean flushQueues) {}
/**
* Sets the shadow compare mode (see {@link CompareMode} for more info).
* @param compareMode the compare mode.
*/
final public void setShadowCompareMode(CompareMode compareMode) {
shadowRenderer.setShadowCompareMode(compareMode);
}
/**
* Get the shadow compare mode.
*
* @return the shadow compare mode.
* @see CompareMode
*/
public CompareMode getShadowCompareMode() {
return shadowRenderer.getShadowCompareMode();
}
/**
* Sets the filtering mode for shadow edges see {@link EdgeFilteringMode} for more info
* @param filterMode the filtering mode for shadow edges.
*/
final public void setEdgeFilteringMode(EdgeFilteringMode filterMode) {
shadowRenderer.setEdgeFilteringMode(filterMode);
}
/**
*
* <b>WARNING</b> this parameter is defaulted to <code>true</code> for the shadow filter. Setting it to <code>true</code>, may produce edges artifacts on shadows.<br>
* <br>
* Set to <code>true</code> if you want back faces shadows on geometries.
* Note that back faces shadows will be blended over dark lighten areas and may produce overly dark lighting.<br>
*<br>
* Setting this parameter will override this parameter for <b>ALL</b> materials in the scene.
* This also will automatically adjust the face cull mode and the PolyOffset of the pre shadow pass.
* You can modify them by using {@link #getPreShadowForcedRenderState()}.<br>
* <br>
* If you want to set it differently for each material in the scene you have to use the ShadowRenderer instead
* of the shadow filter.
*
* @param renderBackFacesShadows <code>true</code> if back faces shadows on geometries have to be rendered and <code>false</code> otherwise.
*/
public void setRenderBackFacesShadows(Boolean renderBackFacesShadows) {
shadowRenderer.setRenderBackFacesShadows(renderBackFacesShadows);
}
/**
* Is this filter renders back faces shadows.
* @return <code>true</code> if this filter renders back faces shadows and <code>false</code> otherwise.
*/
public boolean isRenderBackFacesShadows() {
return shadowRenderer.isRenderBackFacesShadows();
}
/**
* Get the pre-shadows pass render state.
* use it to adjust the RenderState parameters of the pre shadow pass.
* Note that this will be overridden if the preShadow technique in the material has a ForcedRenderState
* @return the pre shadow render state.
*/
public RenderState getPreShadowForcedRenderState() {
return shadowRenderer.getPreShadowForcedRenderState();
}
/**
* Get the edge filtering mode.
* @return the edge filtering mode.
*/
public EdgeFilteringMode getEdgeFilteringMode() {
return shadowRenderer.getEdgeFilteringMode();
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
//OutputCapsule oc = ex.getCapsule(this);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
//InputCapsule ic = im.getCapsule(this);
}
}
| bsd-3-clause |
credentials/credentials_api | src/main/java/org/irmacard/credentials/Attributes.java | 14002 | /*
* Copyright (c) 2015, the IRMA Team
* 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 IRMA 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.irmacard.credentials;
import org.irmacard.credentials.info.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
* A generic container class for attributes. Indexes attributes (in the form
* of byte arrays) by name, and provides getters and setters for all metadata
* fields.
*/
@SuppressWarnings("unused")
public class Attributes implements Serializable {
private static final long serialVersionUID = 1L;
private Map<String, byte[]> attributes;
/**
* Precision factor for the expiry attribute, 1 means millisecond precision.
* Set to one week.
*/
public final static long EXPIRY_FACTOR = 1000 * 60 * 60 * 24 * 7;
public final static String META_DATA_FIELD = "metadata";
public final static int META_DATA_LENGTH; // Computed below
public final static byte CURRENT_VERSION = (byte) 0x02;
public final static int FIELD_COUNT = Field.values().length;
/** The metadata fields. The order in which they appear here defines the order in which
* they are stored in the metadata attribute. */
private enum Field {
VERSION(1),
SIGNING_DATE(3),
EXPIRY(2),
KEY_COUNTER(2),
CREDENTIAL_ID(16);
private int length;
private int offset;
Field(int length) {
this.length = length;
}
}
static {
Field[] fields = Field.values();
int offset = 0;
fields[0].offset = 0;
for (int i = 1; i < FIELD_COUNT; ++i) {
offset += fields[i-1].length;
fields[i].offset = offset;
}
Field lastField = fields[FIELD_COUNT-1];
META_DATA_LENGTH = lastField.offset + lastField.length;
}
/**
* Create a new instance with all metadata fields set to their default values.
*/
public Attributes() {
attributes = new HashMap<>();
// Create meta-data field
byte[] metadata = new byte[META_DATA_LENGTH];
add(META_DATA_FIELD, metadata);
// Set metadata fields to their default values
setMetadataField(new byte[]{CURRENT_VERSION}, Field.VERSION);
setSigningDate(null);
setValidityDuration((short)(52 / 2));
setKeyCounter(0);
}
/**
* Create a new instance with the specified attributes. The credential type is extracted from the
* metadata attribute (no. 1), which must be present. The corresponding attribute names are fetched
* from the {@link DescriptionStore}. If an attribute is not present in the hash map, its value
* becomes 0.
* @param values The attribute values
* @throws IllegalArgumentException If the metadata attribute was absent, i.e., values.get(1) == null,
* or if the credential type is unknown (i.e. not present in the
* DescriptionStore)
*/
public Attributes(HashMap<Integer, BigInteger> values) throws IllegalArgumentException {
if (values.get(1) == null)
throw new IllegalArgumentException("Metadata attribute was absent but is compulsory");
attributes = new HashMap<>();
attributes.put(META_DATA_FIELD, values.get(1).toByteArray());
CredentialDescription cd = getCredentialDescription();
if (cd == null)
throw new IllegalArgumentException("Credential type not found in store");
List<String> attributeNames = cd.getAttributeNames();
for (int i = 0; i < attributeNames.size(); ++i) {
BigInteger attribute = values.get(i+2);
if (attribute != null)
attributes.put(attributeNames.get(i), attribute.toByteArray());
}
}
/**
* Create a new instance with the specified attributes. The credential type is extracted from the
* metadata attribute (no. 1). The corresponding attribute names are fetched from the
* {@link DescriptionStore}.
* @param values The attribute values, with the metadata attribute at position 1 and the rest of
* the attributes at position 2 and on.
* @throws IllegalArgumentException If the metadata attribute was absent, i.e., values.get(1) == null,
* or if the credential type is unknown (i.e. not present in the
* DescriptionStore)
*/
public Attributes(List<BigInteger> values) {
if (values.get(1) == null)
throw new IllegalArgumentException("Metadata attribute was absent but is compulsory");
attributes = new HashMap<>();
attributes.put(META_DATA_FIELD, values.get(1).toByteArray());
CredentialDescription cd = getCredentialDescription();
if (cd == null)
throw new IllegalArgumentException("Credential type not found in store");
List<String> attributeNames = cd.getAttributeNames();
for (int i = 0; i < attributeNames.size(); ++i)
attributes.put(attributeNames.get(i), values.get(i+2).toByteArray());
}
/**
* Create a new instance containing the specified BigInteger as metadat attribute.
*/
public Attributes(BigInteger metadata) {
attributes = new HashMap<>();
attributes.put(META_DATA_FIELD, metadata.toByteArray());
}
public byte[] getMetadataField(Field field) {
return Arrays.copyOfRange(attributes.get(META_DATA_FIELD), field.offset, field.offset + field.length);
}
public void setMetadataField(byte[] value, Field field) {
byte[] metadata = attributes.get(META_DATA_FIELD);
if (value.length > field.length)
throw new RuntimeException("Metadata field value for " + field
+ " too long: was " + value.length + ", maximum is " + field.length);
// Populate the bytes, pushing them as far right as possible within the space allotted to this field
int emptySpace = field.length - value.length;
ByteBuffer buffer = ByteBuffer.wrap(metadata);
buffer.position(field.offset);
if (emptySpace > 0)
buffer.put(new byte[emptySpace]);
buffer.put(value);
add(META_DATA_FIELD, buffer.array());
}
public void add(String id, byte[] value) {
attributes.put(id, value);
}
public byte[] get(String id) {
return attributes.get(id);
}
public Set<String> getIdentifiers() {
return attributes.keySet();
}
public void print() {
for(String k : attributes.keySet() ) {
System.out.println(toString());
}
}
public String toString() {
String res = "[";
for(String k : attributes.keySet() ) {
res += k + ": " + new String(get(k)) + ", ";
}
res += "]";
return res;
}
/**
* Get the validity duration in weeks for this credential.
*/
public short getValidityDuration() {
return ByteBuffer.wrap(getMetadataField(Field.EXPIRY)).getShort();
}
/**
* Set the validity duration in weeks for this credential.
*/
public void setValidityDuration(short numberOfWeeks) {
setMetadataField(ByteBuffer.allocate(2).putShort(numberOfWeeks).array(), Field.EXPIRY);
}
/**
* Get the expiry date for this credential.
*/
public Date getExpiryDate() {
Date signing = getSigningDate();
long duration = getValidityDuration() * EXPIRY_FACTOR;
return new Date(signing.getTime() + duration);
}
/**
* Set the expiry date for this credential.
* @param expiry The desired expiry date
* @throws IllegalArgumentException if the specified date does not fall on an epoch boundary
*/
public void setExpiryDate(Date expiry) throws IllegalArgumentException {
long expiryLong = expiry.getTime();
if (expiryLong % EXPIRY_FACTOR != 0)
throw new IllegalArgumentException("Expiry date does not match an epoch boundary");
long signingLong = getSigningDate().getTime();
short difference = (short)((expiryLong - signingLong) / EXPIRY_FACTOR);
setMetadataField(ByteBuffer.allocate(2).putShort(difference).array(), Field.EXPIRY);
}
/**
* Get the date on which this credential was signed.
*/
public Date getSigningDate() {
byte[] signingDateBytes = getMetadataField(Field.SIGNING_DATE);
long signingDateLong = new BigInteger(signingDateBytes).longValue();
Calendar signingDate = Calendar.getInstance();
signingDate.setTimeInMillis(signingDateLong * EXPIRY_FACTOR);
return signingDate.getTime();
}
/**
* Set the date on which this credential was signed.
*/
public void setSigningDate(Date date) {
long value;
if (date != null)
value = date.getTime() / EXPIRY_FACTOR;
else
value = Calendar.getInstance().getTimeInMillis() / EXPIRY_FACTOR;
setMetadataField(BigInteger.valueOf(value).toByteArray(), Field.SIGNING_DATE);
}
/**
* Get the counter of the public key with which this credential was signed.
*/
public short getKeyCounter() {
return ByteBuffer.wrap(getMetadataField(Field.KEY_COUNTER)).getShort();
}
/**
* Set the counter of the public key with which this credential was signed.
*/
public void setKeyCounter(int value) {
setMetadataField(ByteBuffer.allocate(2).putShort((short)value).array(), Field.KEY_COUNTER);
}
/**
* Get the {@link CredentialIdentifier} from the metadata attribute of this instance.
* @return Either the identifier, or null if the {@link DescriptionStore} does not contain it.
* @throws StoreException if the {@link DescriptionStore} is not initialized
*/
public CredentialIdentifier getCredentialIdentifier() throws StoreException {
return DescriptionStore.getInstance().hashToCredentialIdentifier(getMetadataField(Field.CREDENTIAL_ID));
}
/**
* Set the {@link CredentialIdentifier} of this credential.
*/
public void setCredentialIdentifier(CredentialIdentifier value) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(value.toString().getBytes());
byte[] truncatedHash = Arrays.copyOfRange(md.digest(), 0, 16);
setMetadataField(truncatedHash, Field.CREDENTIAL_ID);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 hash algorithm absent");
}
}
/**
* Get the {@link CredentialDescription} of this credential, using {@link #getCredentialIdentifier()}
* and the {@link DescriptionStore}.
* @throws StoreException if the {@link DescriptionStore} is not initialized
*/
public CredentialDescription getCredentialDescription() {
return DescriptionStore.getInstance().getCredentialDescription(getCredentialIdentifier());
}
/**
* Test whether the the credential containing these attributes is still valid on the given date.
* @return True if the specified date is before the expiry dates of both the credential and the
* corresponding public key; false otherwise.
* @throws InfoException when the {@link CredentialIdentifier} could not be determined using the metadata attribute;
* when the {@link KeyStore} has not been initialized; or when it does not contain the
* required public key.
* @throws KeyException when the corresponding public key could not be found.
*/
public boolean isValidOn(Date date) throws InfoException, KeyException {
try {
IssuerIdentifier issuer = getCredentialIdentifier().getIssuerIdentifier();
PublicKey key = KeyStore.getInstance().getPublicKey(issuer, getKeyCounter());
return key.isValidOn(getSigningDate()) && !isExpiredOn(date);
} catch (NullPointerException|StoreException e) {
throw new InfoException(e);
}
}
/**
* @return {@link #isValidOn(Date)} the current time.
*/
public boolean isValid() throws InfoException, KeyException {
return isValidOn(Calendar.getInstance().getTime());
}
/** Returns true iff the credential is expired on the given date. */
public boolean isExpiredOn(Date date) {
return date.after(getExpiryDate());
}
/** Returns true iff the credential is expired at the current time. */
public boolean isExpired() {
return isExpiredOn(Calendar.getInstance().getTime());
}
/**
* Convert this instance to a list of BigIntegers, suitable for passing to the Idemix API.
* The secret key is not included so the first element is the metadata attribute.
* @throws InfoException if there is a mismatch between the attribute names according to this
* instance and the {@link DescriptionStore}
*/
public ArrayList<BigInteger> toBigIntegers() throws InfoException {
List<String> names = getCredentialDescription().getAttributeNames();
ArrayList<BigInteger> bigints = new ArrayList<>(names.size() + 2);
// Add metadata field manually as it is not included in .getAttributeNames()
bigints.add(new BigInteger(get(META_DATA_FIELD)));
// Add the other attributes
for (String name : names) {
byte[] value = get(name);
if (value == null)
throw new InfoException("Attribute " + name + " missing");
bigints.add(new BigInteger(value));
}
return bigints;
}
}
| bsd-3-clause |
bmjares/self_service | app/controllers/account/Reset.java | 6552 | package controllers.account;
import models.Token;
import models.User;
import models.utils.AppException;
import models.utils.Mail;
import org.apache.commons.mail.EmailException;
import play.Logger;
import play.data.Form;
import play.data.validation.Constraints;
import play.i18n.Messages;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.account.reset.ask;
import views.html.account.reset.reset;
import views.html.account.reset.runAsk;
import java.net.MalformedURLException;
/**
* Token password :
* - ask for an email address.
* - send a link pointing them to a reset page.
* - show the reset page and set them reset it.
* <p/>
* <p/>
* User: yesnault
* Date: 20/01/12
*/
public class Reset extends Controller {
public static class AskForm {
@Constraints.Required
public String email;
}
public static class ResetForm {
@Constraints.Required
public String inputPassword;
}
/**
* Display the reset password form.
*
* @return reset password form
*/
public static Result ask() {
Form<AskForm> askForm = form(AskForm.class);
return ok(ask.render(askForm));
}
/**
* Run ask password.
*
* @return reset password form if error, runAsk render otherwise
*/
public static Result runAsk() {
Form<AskForm> askForm = form(AskForm.class).bindFromRequest();
if (askForm.hasErrors()) {
flash("error", Messages.get("signup.valid.email"));
return badRequest(ask.render(askForm));
}
final String email = askForm.get().email;
Logger.debug("runAsk: email = " + email);
User user = User.findByEmail(email);
Logger.debug("runAsk: user = " + user);
// If we do not have this email address in the list, we should not expose this to the user.
// This exposes that the user has an account, allowing a user enumeration attack.
// See http://www.troyhunt.com/2012/05/everything-you-ever-wanted-to-know.html for details.
// Instead, email the person saying that the reset failed.
if (user == null) {
Logger.debug("No user found with email " + email);
sendFailedPasswordResetAttempt(email);
return ok(runAsk.render());
}
Logger.debug("Sending password reset link to user " + user);
try {
Token.sendMailResetPassword(user);
return ok(runAsk.render());
} catch (MalformedURLException e) {
Logger.error("Cannot validate URL", e);
flash("error", Messages.get("error.technical"));
}
return badRequest(ask.render(askForm));
}
/**
* Sends an email to say that the password reset was to an invalid email.
*
* @param email the email address to send to.
*/
private static void sendFailedPasswordResetAttempt(String email) {
String subject = Messages.get("mail.reset.fail.subject");
String message = Messages.get("mail.reset.fail.message", email);
Mail.Envelop envelop = new Mail.Envelop(subject, message, email);
Mail.sendMail(envelop);
}
public static Result reset(String token) {
if (token == null) {
flash("error", Messages.get("error.technical"));
Form<AskForm> askForm = form(AskForm.class);
return badRequest(ask.render(askForm));
}
Token resetToken = Token.findByTokenAndType(token, Token.TypeToken.password);
if (resetToken == null) {
flash("error", Messages.get("error.technical"));
Form<AskForm> askForm = form(AskForm.class);
return badRequest(ask.render(askForm));
}
if (resetToken.isExpired()) {
resetToken.delete();
flash("error", Messages.get("error.expiredresetlink"));
Form<AskForm> askForm = form(AskForm.class);
return badRequest(ask.render(askForm));
}
Form<ResetForm> resetForm = form(ResetForm.class);
return ok(reset.render(resetForm, token));
}
/**
* @return reset password form
*/
public static Result runReset(String token) {
Form<ResetForm> resetForm = form(ResetForm.class).bindFromRequest();
if (resetForm.hasErrors()) {
flash("error", Messages.get("signup.valid.password"));
return badRequest(reset.render(resetForm, token));
}
try {
Token resetToken = Token.findByTokenAndType(token, Token.TypeToken.password);
if (resetToken == null) {
flash("error", Messages.get("error.technical"));
return badRequest(reset.render(resetForm, token));
}
if (resetToken.isExpired()) {
resetToken.delete();
flash("error", Messages.get("error.expiredresetlink"));
return badRequest(reset.render(resetForm, token));
}
// check email
User user = User.find.byId(resetToken.userId);
if (user == null) {
// display no detail (email unknown for example) to
// avoir check email by foreigner
flash("error", Messages.get("error.technical"));
return badRequest(reset.render(resetForm, token));
}
String password = resetForm.get().inputPassword;
user.changePassword(password);
// Send email saying that the password has just been changed.
sendPasswordChanged(user);
flash("success", Messages.get("resetpassword.success"));
return ok(reset.render(resetForm, token));
} catch (AppException e) {
flash("error", Messages.get("error.technical"));
return badRequest(reset.render(resetForm, token));
} catch (EmailException e) {
flash("error", Messages.get("error.technical"));
return badRequest(reset.render(resetForm, token));
}
}
/**
* Send mail with the new password.
*
* @param user user created
* @throws EmailException Exception when sending mail
*/
private static void sendPasswordChanged(User user) throws EmailException {
String subject = Messages.get("mail.reset.confirm.subject");
String message = Messages.get("mail.reset.confirm.message");
Mail.Envelop envelop = new Mail.Envelop(subject, message, user.email);
Mail.sendMail(envelop);
}
}
| bsd-3-clause |
NCIP/cacore-sdk | sdk-toolkit/software/modules/security-client/src/gov/nih/nci/system/security/acegi/providers/UsernameAuthenticationToken.java | 1453 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC, SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk/LICENSE.txt for details.
*/
package gov.nih.nci.system.security.acegi.providers;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.providers.AbstractAuthenticationToken;
public class UsernameAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = 1L;
private Object principal;
public UsernameAuthenticationToken(Object principal) {
super(null);
this.principal = principal;
setAuthenticated(false);
}
public UsernameAuthenticationToken(Object principal, GrantedAuthority[] authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
public Object getPrincipal() {
return this.principal;
}
public Object getCredentials() {
return "dummy";
}
public void setAuthenticated(boolean isAuthenticated)
throws IllegalArgumentException {
if (isAuthenticated) {
throw new IllegalArgumentException(
"Cannot set this token to trusted - use constructor containing GrantedAuthority[]s instead");
}
super.setAuthenticated(false);
}
}
| bsd-3-clause |
sebastiencaille/sky-lib | skylib-java/lib-gui-java8/src/main/java/ch/scaille/gui/mvc/Logging.java | 230 | package ch.scaille.gui.mvc;
import java.util.logging.Logger;
import ch.scaille.util.helpers.Logs;
public class Logging {
public static final Logger MVC_EVENTS_DEBUGGER = Logs.of("MvcEventsDebug");
private Logging() {
}
}
| bsd-3-clause |
tzima/Bytelang | Bytelang/src/bytelang/parser/syntactical/Utils.java | 1125 | package bytelang.parser.syntactical;
import java.util.LinkedList;
import bytelang.CompilationErrorException;
import bytelang.parser.lexical.states.LexicalState;
import bytelang.parser.lexical.states.LexicalStateType;
public abstract class Utils {
public static LexicalState next(LinkedList<LexicalState> tokens, LexicalStateType type, String message) {
if (tokens.size() > 0) {
LexicalState lexicalState = tokens.removeFirst();
if (lexicalState.getType() == type) {
return lexicalState;
}
}
throw new CompilationErrorException(message);
}
public static LexicalState next(LinkedList<LexicalState> tokens, String message) {
if (tokens.size() > 0) {
return tokens.getFirst();
}
throw new CompilationErrorException(message);
}
public static LexicalState next(LinkedList<LexicalState> tokens, LexicalStateType[] types, String message) {
if (tokens.size() > 0) {
LexicalState first = tokens.removeFirst();
for (LexicalStateType type : types) {
if (first.getType() == type) {
return first;
}
}
}
throw new CompilationErrorException(message);
}
}
| bsd-3-clause |
Digot/GoMint | gomint-api/src/main/java/io/gomint/plugin/Startup.java | 541 | /*
* Copyright (c) 2015, GoMint, BlackyPaw and geNAZt
*
* This code is licensed under the BSD license found in the
* LICENSE file in the root directory of this source tree.
*/
package io.gomint.plugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author BlackyPaw
* @version 1.0
*/
@Target( ElementType.TYPE )
@Retention( RetentionPolicy.RUNTIME )
public @interface Startup {
StartupPriority value();
}
| bsd-3-clause |
FuriKuri/aspgen | aspgen-generator/src/test/java/de/hbrs/aspgen/generator/builder/JavaClassExtenderForMethodsInClassTest.java | 8592 | package de.hbrs.aspgen.generator.builder;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
import de.hbrs.aspgen.api.ast.JavaClass;
import de.hbrs.aspgen.api.generator.AdviceForMethod;
import de.hbrs.aspgen.api.generator.AdviceForMethodGenerator;
import de.hbrs.aspgen.api.generator.ExtendMethodWithAdvices;
import de.hbrs.aspgen.api.generator.ExtendMethodWithFields;
import de.hbrs.aspgen.api.generator.FieldForMethod;
import de.hbrs.aspgen.api.generator.FieldForMethodGenerator;
import de.hbrs.aspgen.jparser.type.Java6Annotation;
import de.hbrs.aspgen.jparser.type.Java6Class;
import de.hbrs.aspgen.jparser.type.Java6Method;
import de.hbrs.aspgen.jparser.type.Java6Parameter;
public class JavaClassExtenderForMethodsInClassTest {
@Test
public void createAspectOnlyForMethod() {
final JavaClassExtender extender = new JavaClassExtender(createClass("de.hbrs.Print"), new MethodGen());
final String result = extender.createAspectJFileContent();
final String expectedResult = "import de.hbrs.aspgen.annotation.Generated;\n\npublic privileged aspect Person_Print perthis(this(Person)) {\n"
+ " @Generated(id = {newid1}, name = \"Dummy\", data = \"private:void:print;;\")\n before() : execution(private void Person.print()) {\n"
+ " System.out.println();\n"
+ " }\n\n"
+ " @Generated(id = {newid2}, name = \"Dummy\", data = \"public:String:do2;;\")\n before() : execution(public String Person.do2()) {\n"
+ " System.out.println();\n"
+ " }\n"
+ "}";
assertEquals(expectedResult, result);
}
private JavaClass createClass(final String anno) {
final Java6Annotation annotation = new Java6Annotation();
annotation.setName(anno);
final Java6Class java6Class = new Java6Class();
java6Class.setClassName("Person");
final Java6Method java6Method = new Java6Method();
java6Method.setAccessType("private");
java6Method.setName("print");
java6Method.setType("void");
java6Method.addAnnotation(annotation);
java6Class.addMethod(java6Method);
final Java6Method java6Method2 = new Java6Method();
java6Method2.setAccessType("public");
java6Method2.setName("do2");
java6Method2.setType("String");
java6Method2.addAnnotation(annotation);
java6Class.addMethod(java6Method2);
return java6Class;
}
@Test
public void createAspectForMethodWithAnnotationClass() {
final JavaClassExtender extender = new JavaClassExtender(createClassWithAnnoation("de.hbrs.Print"), new MethodGen());
final String result = extender.createAspectJFileContent();
final String expectedResult = "import de.hbrs.aspgen.annotation.Generated;\n\npublic privileged aspect Person_Print perthis(this(Person)) {\n"
+ " @Generated(id = {newid1}, name = \"Dummy\", data = \"private:void:print;;\")\n before() : execution(private void Person.print()) {\n"
+ " System.out.println();\n"
+ " }\n\n"
+ " @Generated(id = {newid2}, name = \"Dummy\", data = \"public:String:do2;;\")\n before() : execution(public String Person.do2()) {\n"
+ " System.out.println();\n"
+ " }\n"
+ "}";
assertEquals(expectedResult, result);
}
private JavaClass createClassWithAnnoation(final String anno) {
final Java6Annotation annotation = new Java6Annotation();
annotation.setName(anno);
final Java6Class java6Class = new Java6Class();
java6Class.setClassName("Person");
java6Class.addAnnotation(annotation);
final Java6Method java6Method = new Java6Method();
java6Method.setAccessType("private");
java6Method.setName("print");
java6Method.setType("void");
java6Class.addMethod(java6Method);
final Java6Method java6Method2 = new Java6Method();
java6Method2.setAccessType("public");
java6Method2.setName("do2");
java6Method2.setType("String");
java6Class.addMethod(java6Method2);
return java6Class;
}
private static class MethodGen implements AdviceForMethodGenerator {
@Override
public String getName() {
return "de.hbrs.Print";
}
@Override
public void extendJavaClass(final ExtendMethodWithAdvices builder,
final Map<String, String> properties) {
final AdviceForMethod adviceForMethod = builder.appendNewBeforeAdvice("Dummy");
adviceForMethod.addLine("System.out.println();");
}
}
@Test
public void createFieldForMethod() {
final JavaClassExtender extender = new JavaClassExtender(createClass("de.hbrs.Print"), new FieldGen());
final String result = extender.createAspectJFileContent();
final String expectedResult = "import de.hbrs.aspgen.annotation.Generated;\n\npublic privileged aspect Person_Print perthis(this(Person)) {\n"
+ " @Generated(id = {newid1}, name = \"Dummy\", data = \"private:void:print;;\")\n public void Person.fieldPrint;\n\n"
+ " @Generated(id = {newid2}, name = \"Dummy\", data = \"public:String:do2;;\")\n public void Person.fieldDo2;\n"
+ "}";
assertEquals(expectedResult, result);
}
private static class FieldGen implements FieldForMethodGenerator {
@Override
public String getName() {
return "de.hbrs.Print";
}
@Override
public void extendJavaClass(final ExtendMethodWithFields builder,
final Map<String, String> properties) {
final FieldForMethod fieldForMethod = builder.appendNewField("Dummy");
fieldForMethod.setContent("public void field$methodname$;");
}
}
@Test
public void createOneAdviceForNotExcludeParameters() {
final JavaClassExtender extender = new JavaClassExtender(createClassWithAnnoationAndExcludeParameter("de.hbrs.Print"), new MethodForEachParameterGen());
final String result = extender.createAspectJFileContent();
final String expectedResult = "import de.hbrs.aspgen.annotation.Generated;\n\npublic privileged aspect Person_Print perthis(this(Person)) {\n"
+ " @Generated(id = {newid1}, name = \"Dummy\", data = \"public:String:do2;String:name,int:age;\")\n"
+ " before(final String name, final int age) : execution(public String Person.do2(String, int)) && args(name, age) {\n"
+ " System.out.println(name);\n"
+ " }\n"
+ "}";
assertEquals(expectedResult, result);
}
private JavaClass createClassWithAnnoationAndExcludeParameter(final String anno) {
final Java6Annotation annotation = new Java6Annotation();
annotation.setName(anno);
final Java6Class java6Class = new Java6Class();
java6Class.setClassName("Person");
final Java6Method java6Method = new Java6Method();
java6Method.setAccessType("public");
java6Method.setName("do2");
java6Method.setType("String");
java6Method.addAnnotation(annotation);
java6Class.addMethod(java6Method);
final Java6Parameter javaParameter = new Java6Parameter();
javaParameter.setName("name");
javaParameter.setType("String");
java6Method.addParameter(javaParameter);
final Java6Parameter javaParameter2 = new Java6Parameter();
javaParameter2.setName("age");
javaParameter2.setType("int");
java6Method.addParameter(javaParameter2);
final Java6Annotation annotation2 = new Java6Annotation();
annotation2.setName(anno);
annotation2.addAttribute("exclude", "\"Dummy\"");
javaParameter2.addAnnotation(annotation2);
return java6Class;
}
private static class MethodForEachParameterGen implements AdviceForMethodGenerator {
@Override
public String getName() {
return "de.hbrs.Print";
}
@Override
public void extendJavaClass(final ExtendMethodWithAdvices builder,
final Map<String, String> properties) {
final AdviceForMethod adviceForMethod = builder.appendNewBeforeAdvice("Dummy");
adviceForMethod.addLineForeachParameter("System.out.println($parametername$);");
}
}
}
| bsd-3-clause |
Sukelluskello/VectorAttackScanner | Android/DependenciesVectorAttackScanner/src/org/antlr/runtime/ParserRuleReturnScope.java | 2666 | /*
[The "BSD license"]
Copyright (c) 2005-2009 Terence Parr
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.antlr.runtime;
/** Rules that return more than a single value must return an object
* containing all the values. Besides the properties defined in
* RuleLabelScope.predefinedRulePropertiesScope there may be user-defined
* return values. This class simply defines the minimum properties that
* are always defined and methods to access the others that might be
* available depending on output option such as template and tree.
*
* Note text is not an actual property of the return value, it is computed
* from start and stop using the input stream's toString() method. I
* could add a ctor to this so that we can pass in and store the input
* stream, but I'm not sure we want to do that. It would seem to be undefined
* to get the .text property anyway if the rule matches tokens from multiple
* input streams.
*
* I do not use getters for fields of objects that are used simply to
* group values such as this aggregate. The getters/setters are there to
* satisfy the superclass interface.
*/
public class ParserRuleReturnScope extends RuleReturnScope {
public Token start, stop;
public Object getStart() { return start; }
public Object getStop() { return stop; }
}
| bsd-3-clause |
NCIP/cab2b | software/cab2b/src/java/server/edu/wustl/cab2b/server/queryengine/querybuilders/CategoryPreprocessor.java | 26273 | /*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.wustl.cab2b.server.queryengine.querybuilders;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.cab2b.common.exception.RuntimeException;
import edu.wustl.cab2b.common.queryengine.ICab2bQuery;
import edu.wustl.cab2b.common.util.TreeNode;
import edu.wustl.cab2b.common.util.Utility;
import edu.wustl.cab2b.server.category.CategoryCache;
import edu.wustl.common.querysuite.exceptions.CyclicException;
import edu.wustl.common.querysuite.exceptions.MultipleRootsException;
import edu.wustl.common.querysuite.factory.QueryObjectFactory;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
import edu.wustl.common.querysuite.metadata.category.CategorialAttribute;
import edu.wustl.common.querysuite.metadata.category.CategorialClass;
import edu.wustl.common.querysuite.metadata.category.Category;
import edu.wustl.common.querysuite.metadata.path.IPath;
import edu.wustl.common.querysuite.queryobject.ICondition;
import edu.wustl.common.querysuite.queryobject.IConnector;
import edu.wustl.common.querysuite.queryobject.IConstraints;
import edu.wustl.common.querysuite.queryobject.IExpression;
import edu.wustl.common.querysuite.queryobject.IExpressionOperand;
import edu.wustl.common.querysuite.queryobject.IJoinGraph;
import edu.wustl.common.querysuite.queryobject.IQuery;
import edu.wustl.common.querysuite.queryobject.IQueryEntity;
import edu.wustl.common.querysuite.queryobject.IRule;
import edu.wustl.common.querysuite.queryobject.LogicalOperator;
/**
* Category Preprocessor
* @author Srinath K
*/
public class CategoryPreprocessor {
private static final Logger logger = edu.wustl.common.util.logger.Logger.getLogger(CategoryPreprocessor.class);
private IQuery query;
private CategoryPreprocessorResult categoryPreprocessorResult;
private List<IExpression> catExprs = new ArrayList<IExpression>();
/**
* The query object is modified appropriately.
* @param query
* @return Results from category preprocessor
*
*/
public CategoryPreprocessorResult processCategories(IQuery query) {
clear();
this.query = query;
this.categoryPreprocessorResult = new CategoryPreprocessorResult();
processCategories();
return this.categoryPreprocessorResult;
}
private void clear() {
this.catExprs.clear();
}
private void processCategories() {
for (IExpression expr : getConstraints()) {
if (!Utility.isCategory(expr.getQueryEntity().getDynamicExtensionsEntity())) {
logger.info("JJJ not a category"+expr.getId()+"queryentity="+expr.getQueryEntity().toString());
continue;
}
logger.info("JJJ *IS* a category id="+expr.getId());
processCategoryExpression(expr);
this.catExprs.add(expr);
}
removeCategoryExpressions();
// check there is a single root.
try {
for(IExpression exp:getConstraints().getJoinGraph().getAllRoots()){
logger.info("JJJ ROOT: id="+exp.getId()+"exp.id="+exp.getExpressionId()+"queryent="+exp.getQueryEntity());
}
getConstraints().getRootExpression();
} catch (MultipleRootsException e) {
throw new RuntimeException("Problem in code...", e);
}
}
private void removeCategoryExpressions() {
for (IExpression expression : this.catExprs) {
// by this time, none of the cat expressions should have any
// parents...
// assert getJoinGraph().getParentList(expressionId).isEmpty();
getConstraints().removeExpression(expression);
}
}
private void processCategoryExpression(IExpression expr) {
List<IExpression> parentExprs = getJoinGraph().getParentList(expr);
if (parentExprs.isEmpty()) {
// implies that this is the root expr.
// transformCategoryExpression(expr, this.masterEntryPoint);
EntityInterface catEntity = expr.getQueryEntity().getDynamicExtensionsEntity();
Category category = getCategoryFromEntity(catEntity);
transformCategoryExpression(expr, category.getRootClass().getCategorialClassEntity());
} else {
for (IExpression parentExpr : parentExprs) {
if (this.catExprs.contains(parentExpr)) {
// this parent will be removed in the future; so don't heed
// it.
continue;
}
IAssociation association = getJoinGraph().getAssociation(parentExpr, expr);
IExpression transformedExpr = transformCategoryExpression(expr, association.getTargetEntity());
int index = parentExpr.indexOfOperand(expr);
parentExpr.setOperand(index, transformedExpr);
try {
getJoinGraph().putAssociation(parentExpr, transformedExpr, association);
} catch (CyclicException e) {
// this should not occur...
throw new RuntimeException("Problem in code... might be due to invalid input.", e);
}
getJoinGraph().removeAssociation(parentExpr, expr);
}
}
}
// protected for testing
protected Category getCategoryFromEntity(EntityInterface catEntity) {
Long entityId = catEntity.getId();
return CategoryCache.getInstance().getCategoryByEntityId(entityId);
}
private Category pivot(Category category, EntityInterface requiredRoot) {
Category clonedCat = cloneCategorialClasses(category);
clonedCat.setCategoryEntity(category.getCategoryEntity());
getResult().getOriginallyRootCatClasses().add(clonedCat.getRootClass());
List<CategorialClass> catClassesPath =
findCategorialClassesPathFromRoot(clonedCat.getRootClass(), requiredRoot);
if (catClassesPath.isEmpty()) {
throw new RuntimeException("Problem in code; could not find entry point in category");
// TODO this is a hack for single outputs.... ????
// return clonedCat;
}
Collections.reverse(catClassesPath);
catClassesPath.get(0).setParent(null);
List<IPath> correctedPaths = new ArrayList<IPath>(catClassesPath.size() - 1);
for (int i = 0; i < catClassesPath.size() - 1; i++) {
CategorialClass currCatClass = catClassesPath.get(i);
CategorialClass nextCatClass = catClassesPath.get(i + 1);
IPath origPath = currCatClass.getPathFromParent();
if (!origPath.isBidirectional()) {
logger.warn("Unidirectional path found " + origPath + " in category " + category
+ ". Results could be incorrect.");
break;
}
nextCatClass.removeChildCategorialClass(currCatClass);
currCatClass.addChildCategorialClass(nextCatClass);
correctedPaths.add(origPath.reverse());
}
clonedCat.setRootClass(catClassesPath.get(0));
catClassesPath.get(0).setPathFromParent(null);
for (int i = 1; i < catClassesPath.size(); i++) {
catClassesPath.get(i).setPathFromParent(correctedPaths.get(i - 1));
}
return clonedCat;
}
/**
* Creates a new category with a deep clone of the categorial classes' tree
* (and categorial attributes). DE entities and paths are not cloned. Info
* regarding subcategories is not copied.
*
* @return the cloned category.
*/
private Category cloneCategorialClasses(Category category) {
Category clone = new Category();
CategorialClass clonedRootCatClass = cloneCategorialClass(category.getRootClass());
clone.setRootClass(clonedRootCatClass);
clonedRootCatClass.setCategory(clone);
clonedRootCatClass.setParent(null);
List<CategorialClass> currOrigCatClasses = new ArrayList<CategorialClass>();
currOrigCatClasses.add(category.getRootClass());
List<CategorialClass> currClonedCatClasses = new ArrayList<CategorialClass>();
currClonedCatClasses.add(clone.getRootClass());
while (!currOrigCatClasses.isEmpty()) {
List<CategorialClass> nextOrigCatClasses = new ArrayList<CategorialClass>();
List<CategorialClass> nextClonedCatClasses = new ArrayList<CategorialClass>();
for (int i = 0; i < currOrigCatClasses.size(); i++) {
CategorialClass currOrigCatClass = currOrigCatClasses.get(i);
CategorialClass currClonedCatClass = currClonedCatClasses.get(i);
for (CategorialClass origChildCatClass : currOrigCatClass.getChildren()) {
CategorialClass clonedChildCatClass = cloneCategorialClass(origChildCatClass);
clonedChildCatClass.setCategory(clone);
currClonedCatClass.addChildCategorialClass(clonedChildCatClass, origChildCatClass
.getPathFromParent());
nextOrigCatClasses.add(origChildCatClass);
nextClonedCatClasses.add(clonedChildCatClass);
}
}
currOrigCatClasses = nextOrigCatClasses;
currClonedCatClasses = nextClonedCatClasses;
}
return clone;
}
// does not set parentCatClass and category.
// does not set path.
private CategorialClass cloneCategorialClass(CategorialClass categorialClassToClone) {
CategorialClass clone = new CategorialClass();
clone.setDeEntityId(categorialClassToClone.getDeEntityId());
clone.setId(categorialClassToClone.getId());
// clone.setPathFromParent(categorialClassToClone.getPathFromParent());
clone.setCategorialClassEntity(categorialClassToClone.getCategorialClassEntity());
for (CategorialAttribute origAttr : categorialClassToClone.getCategorialAttributeCollection()) {
clone.addCategorialAttribute(cloneCategorialAttribute(origAttr));
}
return clone;
}
// does not set containingCatClass
private CategorialAttribute cloneCategorialAttribute(CategorialAttribute categorialAttributeToClone) {
CategorialAttribute clone = new CategorialAttribute();
clone.setDeCategoryAttributeId(categorialAttributeToClone.getDeCategoryAttributeId());
clone.setDeSourceClassAttributeId(categorialAttributeToClone.getDeSourceClassAttributeId());
clone.setCategoryAttribute(categorialAttributeToClone.getCategoryAttribute());
clone.setSourceClassAttribute(categorialAttributeToClone.getSourceClassAttribute());
clone.setId(categorialAttributeToClone.getId());
return clone;
}
protected boolean areEntitiesEqual(EntityInterface entity1, EntityInterface entity2) {
return entity1.getId().equals(entity2.getId());
}
private List<CategorialClass> findCategorialClassesPathFromRoot(CategorialClass rootCatClass,
EntityInterface requiredRoot) {
List<CategorialClass> res = new ArrayList<CategorialClass>();
if (areEntitiesEqual(rootCatClass.getCategorialClassEntity(), requiredRoot)) {
res.add(rootCatClass);
return res;
}
for (CategorialClass childCatClass : rootCatClass.getChildren()) {
List<CategorialClass> pathFromChild = findCategorialClassesPathFromRoot(childCatClass, requiredRoot);
if (!pathFromChild.isEmpty()) {
res.add(rootCatClass);
res.addAll(pathFromChild);
// TODO taking first plausible exit point as THE exit point...
// calling code should ensure (for jan release) that there is
// only one plausible exit point.
break;
}
}
return res;
}
private IExpression transformCategoryExpression(IExpression catExpr, EntityInterface entryPoint) {
EntityInterface catEntity = catExpr.getQueryEntity().getDynamicExtensionsEntity();
Category originalCategory = getCategoryFromEntity(catEntity);
getResult().getCategoryForEntity().put(catEntity, originalCategory);
Category category = pivot(originalCategory, entryPoint);
CategorialClass rootCatClass = category.getRootClass();
IExpression rootExpr = createExpression(rootCatClass.getCategorialClassEntity(), catExpr.isInView());
TreeNode<IExpression> rootExprNode = new TreeNode<IExpression>(rootExpr);
getResult().addExprSourcedFromCategory(catEntity, rootExprNode);
getResult().getCatClassForExpr().put(rootExpr, rootCatClass);
if (catExpr.numberOfOperands() == 0) {
markRedundant(rootExpr);
return rootExpr;
}
// this map contains the appropriate position, in the new expr, of the
// original connectors.
Map<Integer, Integer> followingConnIndexOrigToNew = new HashMap<Integer, Integer>();
for (int i = 0; i < catExpr.numberOfOperands(); i++) {
int initialRootExprSize = rootExpr.numberOfOperands();
IExpressionOperand operand = catExpr.getOperand(i);
if (operand instanceof IExpression) {
// find path to exit point
IExpression externalExpr = (IExpression) operand;
IAssociation exitAssociation = getJoinGraph().getAssociation(catExpr, externalExpr);
EntityInterface exitPoint = exitAssociation.getSourceEntity();
List<CategorialClass> catClassesPath = findCategorialClassesPathFromRoot(rootCatClass, exitPoint);
IExpression lastExpr = rootExpr;
TreeNode<IExpression> lastExprNode = rootExprNode;
for (int j = 1; j < catClassesPath.size(); j++) {
CategorialClass catClass = catClassesPath.get(j);
List<IAssociation> associations = catClass.getPathFromParent().getIntermediateAssociations();
TreeNode<IExpression> newExprNode =
createExpressionsForAssociations(lastExpr, associations, new HashSet<IExpression>(),
catExpr.isInView(), lastExprNode);
IExpression newExpr = newExprNode.getValue();
getResult().getCatClassForExpr().put(newExpr, catClass);
lastExpr = newExpr;
lastExprNode = newExprNode;
}
// set external expr as subexpr for last expression...
addSubExpr(lastExpr, externalExpr, exitAssociation);
} else {
// it is a rule
// traverse category tree in BFS creating IExpression's along
// the way.
IRule rule = (IRule) operand;
addRuleToExpr(rootExpr, gleanConditions(rootCatClass, rule));
Map<CategorialClass, IExpression> exprForCatClass = new HashMap<CategorialClass, IExpression>();
exprForCatClass.put(rootCatClass, rootExpr);
Map<CategorialClass, TreeNode<IExpression>> treeNodeForCatClass =
new HashMap<CategorialClass, TreeNode<IExpression>>();
treeNodeForCatClass.put(rootCatClass, rootExprNode);
Set<CategorialClass> currCatClasses = new HashSet<CategorialClass>();
currCatClasses.addAll(rootCatClass.getChildren());
Set<IExpression> possiblyRedundantExprs = new HashSet<IExpression>();
// BFS starts from one level below the root...
while (!currCatClasses.isEmpty()) {
Set<CategorialClass> nextCatClasses = new HashSet<CategorialClass>();
for (CategorialClass categorialClass : currCatClasses) {
nextCatClasses.addAll(categorialClass.getChildren());
CategorialClass parentCatClass = categorialClass.getParent();
TreeNode<IExpression> newExprNode =
createExpressionsForAssociations(exprForCatClass.get(parentCatClass),
categorialClass.getPathFromParent()
.getIntermediateAssociations(),
possiblyRedundantExprs, catExpr.isInView(),
treeNodeForCatClass.get(parentCatClass));
IExpression newExpr = newExprNode.getValue();
addRuleToExpr(newExpr, gleanConditions(categorialClass, rule));
exprForCatClass.put(categorialClass, newExpr);
treeNodeForCatClass.put(categorialClass, newExprNode);
getResult().getCatClassForExpr().put(newExpr, categorialClass);
}
currCatClasses = nextCatClasses;
}
for (IExpression possiblyRedundantExpr : possiblyRedundantExprs) {
processRedundantExprs(possiblyRedundantExpr, possiblyRedundantExprs);
}
}
if (i < catExpr.numberOfOperands() - 1) {
followingConnIndexOrigToNew.put(i, rootExpr.numberOfOperands() - 1);
}
int numOperandsAdded = rootExpr.numberOfOperands() - initialRootExprSize;
if (numOperandsAdded > 1) {
// add parantheses around the operands created. The connectors
// were created with default nesting (0). The no. of parantheses
// to be added thus equals the no. of parantheses around the
// original operand + 1.
int precedingConnNesting = catExpr.getConnector(i - 1, i).getNestingNumber();
int followingConnNesting = catExpr.getConnector(i, i + 1).getNestingNumber();
// the nesting of operand equals the nesting of the adjacent
// connector with greater nesting.
int operandNesting =
(precedingConnNesting > followingConnNesting) ? precedingConnNesting
: followingConnNesting;
// add operandNesting + 1 parantheses.
for (int j = 0; j <= operandNesting; j++) {
rootExpr.addParantheses(initialRootExprSize, initialRootExprSize + numOperandsAdded - 1);
}
}
}
// place connectors in original expression in appropriate positions in
// new expression.
for (Map.Entry<Integer, Integer> entry : followingConnIndexOrigToNew.entrySet()) {
IConnector<LogicalOperator> connector = catExpr.getConnector(entry.getKey(), entry.getKey() + 1);
rootExpr.setConnector(entry.getValue(), entry.getValue() + 1, connector);
}
return rootExpr;
}
private void processRedundantExprs(IExpression possiblyRedundantExpr, Set<IExpression> possiblyRedundantExprs) {
if (isRedundant(possiblyRedundantExpr)) {
// the expr was already found to be redundant.
return;
}
for (IExpression possiblyRedundantChildExprId : getJoinGraph().getChildrenList(possiblyRedundantExpr)) {
processRedundantExprs(possiblyRedundantChildExprId, possiblyRedundantExprs);
}
if (possiblyRedundantExprs.contains(possiblyRedundantExpr)) {
List<IExpression> childExprs = getJoinGraph().getChildrenList(possiblyRedundantExpr);
if (possiblyRedundantExpr.numberOfOperands() == childExprs.size()) {
// this means that possiblyRedundantExpr has no rules
boolean redundant = true;
for (IExpression childExpr : childExprs) {
if (!isRedundant(childExpr)) {
redundant = false;
break;
}
}
if (redundant) {
// all child exprs are redundant, so this expr is redundant.
markRedundant(possiblyRedundantExpr);
}
}
// }
}
}
private void markRedundant(IExpression expr) {
getResult().getRedundantExprs().add(expr);
}
private boolean isRedundant(IExpression expr) {
return getResult().getRedundantExprs().contains(expr);
}
/**
* Creates expressions corresponding to the associations; also sets the
* subexpressions in parentExpr.
*
* @param parentExpr the parentExpr that which is start-point for the
* expressions created.
* @param associationsToLastChild the associations that lead from
* parentExpr's entity to the entity for which the expr is to be
* created.
* @return the last expression.
*/
private TreeNode<IExpression> createExpressionsForAssociations(IExpression parentExpr,
List<IAssociation> associationsToLastChild,
Set<IExpression> expressionsAdded,
boolean inView,
TreeNode<IExpression> parentExprNode) {
IExpression lastChildExpr = parentExpr;
TreeNode<IExpression> lastChildNode = parentExprNode;
for (IAssociation association : associationsToLastChild) {
parentExpr = lastChildExpr;
parentExprNode = lastChildNode;
lastChildExpr = createExpression(association.getTargetEntity(), inView);
lastChildNode = new TreeNode<IExpression>(lastChildExpr);
expressionsAdded.add(lastChildExpr);
addSubExpr(parentExpr, lastChildExpr, association);
parentExprNode.addChild(lastChildNode);
}
return lastChildNode;
}
private IRule gleanConditions(CategorialClass categorialClass, IRule rule) {
IRule newRule = QueryObjectFactory.createRule();
for (int i = 0; i < rule.size(); i++) {
ICondition condition = rule.getCondition(i);
AttributeInterface catAttr = condition.getAttribute();
AttributeInterface srcAttr = findSourceAttribute(catAttr, categorialClass);
if (srcAttr != null) {
newRule.addCondition(cloneWithSpecifiedAttribute(condition, srcAttr));
}
}
return newRule;
}
protected AttributeInterface findSourceAttribute(AttributeInterface catAttr, CategorialClass categorialClass) {
AttributeInterface origAttr = categorialClass.findSourceAttribute(catAttr);
return origAttr;
}
private ICondition cloneWithSpecifiedAttribute(ICondition origCondition, AttributeInterface attr) {
ICondition newCondition = QueryObjectFactory.createCondition();
newCondition.setValues(origCondition.getValues());
newCondition.setRelationalOperator(origCondition.getRelationalOperator());
newCondition.setAttribute(attr);
return newCondition;
}
private void addRuleToExpr(IExpression expr, IRule rule) {
if (rule.size() != 0) {
addOperandToExpr(expr, rule);
}
}
private void addSubExpr(IExpression parentExpr, IExpression childExpr, IAssociation association) {
addOperandToExpr(parentExpr, childExpr);
try {
getJoinGraph().putAssociation(parentExpr, childExpr, association);
} catch (CyclicException e) {
// this should not occur...
throw new RuntimeException("Problem in code...", e);
}
}
private void addOperandToExpr(IExpression parentExpr, IExpressionOperand operand) {
if (parentExpr.numberOfOperands() > 0) {
LogicalOperator operator = LogicalOperator.And;
if (((ICab2bQuery) query).isKeywordSearch()) {
operator = LogicalOperator.Or;
}
IConnector<LogicalOperator> connector = QueryObjectFactory.createLogicalConnector(operator);
parentExpr.addOperand(connector, operand);
} else {
parentExpr.addOperand(operand);
}
}
private IExpression createExpression(EntityInterface entity, boolean inView) {
IQueryEntity queryEntity = QueryObjectFactory.createQueryEntity(entity);
IExpression expr = getConstraints().addExpression(queryEntity);
expr.setInView(inView);
return expr;
}
private IJoinGraph getJoinGraph() {
return getConstraints().getJoinGraph();
}
private IConstraints getConstraints() {
return query.getConstraints();
}
private CategoryPreprocessorResult getResult() {
return this.categoryPreprocessorResult;
}
} | bsd-3-clause |
luttero/Maud | src/gov/noaa/pmel/util/SoTPoint.java | 3706 | /*
* $Id: SoTPoint.java,v 1.1 2004/12/27 16:15:23 luca Exp $
*
* This software is provided by NOAA for full, free and open release. It is
* understood by the recipient/user that NOAA assumes no liability for any
* errors contained in the code. Although this software is released without
* conditions or restrictions in its use, it is expected that appropriate
* credit be given to its author and to the National Oceanic and Atmospheric
* Administration should the software be included by the recipient as an
* element in other product development.
*/
package gov.noaa.pmel.util;
import java.io.Serializable;
/**
* <code>SoTPoint</code> has two coordinates which are of
* type <code>SoTValue</code>. SoT stands for
* space or time, but being basically lazy I've abbreviated it.
*
* @author Donald Denbo
* @version $Revision: 1.1 $, $Date: 2004/12/27 16:15:23 $
* @sgt 2.0
*/
public class SoTPoint implements Serializable, Cloneable {
/** X coordinate */
private SoTValue x_;
/** Y coordinate */
private SoTValue y_;
/**
* Default constructor.
*/
public SoTPoint() {
}
/**
* Construct a <code>SoTPoint</code> from <code>SoTValue</code>s.
*
* @param x space or time coordinate
* @param y space or time coordinate
*/
public SoTPoint(SoTValue x, SoTValue y) {
x_ = x;
y_ = y;
}
/**
* Construct a <code>SoTPoint</code> from <code>double</code>s.
*/
public SoTPoint(double x, double y) {
this(new SoTValue.Double(x), new SoTValue.Double(y));
}
/**
* Construct a <code>SoTPoint</code> from a <code>double</code> and
* a <code>GeoDate</code>.
*/
public SoTPoint(double x, GeoDate y) {
this(new SoTValue.Double(x), new SoTValue.Time(y));
}
/**
* @since sgt 3.0
*/
public SoTPoint(double x, long y) {
this(new SoTValue.Double(x), new SoTValue.Time(y));
}
/**
* Construct a <code>SoTPoint</code> from a <code>GeoDate</code> and
* a <code>double</code>.
*/
public SoTPoint(GeoDate x, double y) {
this(new SoTValue.Time(x), new SoTValue.Double(y));
}
/**
* @since sgt 3.0
*/
public SoTPoint(long x, double y) {
this(new SoTValue.Time(x), new SoTValue.Double(y));
}
/**
* Construct a <code>SoTPoint</code> from a <code>SoTPoint</code>.
*/
public SoTPoint(SoTPoint pt) {
this(pt.getX(), pt.getY());
}
/**
* Get x value
*/
public SoTValue getX() {
return x_;
}
/**
* Set x value
* @since sgt 3.0
*/
public void setX(SoTValue x) {
x_ = x;
}
/**
* Get y value
*/
public SoTValue getY() {
return y_;
}
/**
* Set y value
* @since sgt 3.0
*/
public void setY(SoTValue y) {
y_ = y;
}
/**
* Test for equality. For equality both x and y values must be
* equal.
*/
public boolean equals(SoTPoint stp) {
return (x_.equals(stp.getX()) &&
y_.equals(stp.getY()));
}
/**
* Test if x value is time
*/
public boolean isXTime() {
return x_.isTime();
}
/**
* Test if y value is time
*/
public boolean isYTime() {
return y_.isTime();
}
/**
* Add to point.
*
* @since sgt 3.0
*/
public void add(SoTPoint point) {
x_.add(point.getX());
y_.add(point.getY());
}
/**
* Make a copy of the <code>SoTRange</code>.
* @since sgt 3.0
*/
public SoTPoint copy() {
try {
return (SoTPoint)clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Convert <code>SoTPoint</code> to a default string
*
* @return string representation of the SoTPoint.
*/
public String toString() {
return new String("(" + x_ + ", " + y_ + ")");
}
}
| bsd-3-clause |
GameRevision/GWLP-R | database/src/main/java/gwlpr/database/jpa/LevelJpaController.java | 8001 | /**
* For copyright information see the LICENSE document.
*/
package gwlpr.database.jpa;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import gwlpr.database.entities.Character;
import gwlpr.database.entities.Level;
import gwlpr.database.jpa.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
/**
*
* @author _rusty
*/
public class LevelJpaController implements Serializable
{
public LevelJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Level level) {
if (level.getCharacterCollection() == null) {
level.setCharacterCollection(new ArrayList<Character>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Collection<Character> attachedCharacterCollection = new ArrayList<Character>();
for (Character characterCollectionCharacterToAttach : level.getCharacterCollection()) {
characterCollectionCharacterToAttach = em.getReference(characterCollectionCharacterToAttach.getClass(), characterCollectionCharacterToAttach.getId());
attachedCharacterCollection.add(characterCollectionCharacterToAttach);
}
level.setCharacterCollection(attachedCharacterCollection);
em.persist(level);
for (Character characterCollectionCharacter : level.getCharacterCollection()) {
Level oldLevelOfCharacterCollectionCharacter = characterCollectionCharacter.getLevel();
characterCollectionCharacter.setLevel(level);
characterCollectionCharacter = em.merge(characterCollectionCharacter);
if (oldLevelOfCharacterCollectionCharacter != null) {
oldLevelOfCharacterCollectionCharacter.getCharacterCollection().remove(characterCollectionCharacter);
oldLevelOfCharacterCollectionCharacter = em.merge(oldLevelOfCharacterCollectionCharacter);
}
}
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Level level) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Level persistentLevel = em.find(Level.class, level.getLevel());
Collection<Character> characterCollectionOld = persistentLevel.getCharacterCollection();
Collection<Character> characterCollectionNew = level.getCharacterCollection();
Collection<Character> attachedCharacterCollectionNew = new ArrayList<Character>();
for (Character characterCollectionNewCharacterToAttach : characterCollectionNew) {
characterCollectionNewCharacterToAttach = em.getReference(characterCollectionNewCharacterToAttach.getClass(), characterCollectionNewCharacterToAttach.getId());
attachedCharacterCollectionNew.add(characterCollectionNewCharacterToAttach);
}
characterCollectionNew = attachedCharacterCollectionNew;
level.setCharacterCollection(characterCollectionNew);
level = em.merge(level);
for (Character characterCollectionOldCharacter : characterCollectionOld) {
if (!characterCollectionNew.contains(characterCollectionOldCharacter)) {
characterCollectionOldCharacter.setLevel(null);
characterCollectionOldCharacter = em.merge(characterCollectionOldCharacter);
}
}
for (Character characterCollectionNewCharacter : characterCollectionNew) {
if (!characterCollectionOld.contains(characterCollectionNewCharacter)) {
Level oldLevelOfCharacterCollectionNewCharacter = characterCollectionNewCharacter.getLevel();
characterCollectionNewCharacter.setLevel(level);
characterCollectionNewCharacter = em.merge(characterCollectionNewCharacter);
if (oldLevelOfCharacterCollectionNewCharacter != null && !oldLevelOfCharacterCollectionNewCharacter.equals(level)) {
oldLevelOfCharacterCollectionNewCharacter.getCharacterCollection().remove(characterCollectionNewCharacter);
oldLevelOfCharacterCollectionNewCharacter = em.merge(oldLevelOfCharacterCollectionNewCharacter);
}
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = level.getLevel();
if (findLevel(id) == null) {
throw new NonexistentEntityException("The level with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(Integer id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Level level;
try {
level = em.getReference(Level.class, id);
level.getLevel();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The level with id " + id + " no longer exists.", enfe);
}
Collection<Character> characterCollection = level.getCharacterCollection();
for (Character characterCollectionCharacter : characterCollection) {
characterCollectionCharacter.setLevel(null);
characterCollectionCharacter = em.merge(characterCollectionCharacter);
}
em.remove(level);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Level> findLevelEntities() {
return findLevelEntities(true, -1, -1);
}
public List<Level> findLevelEntities(int maxResults, int firstResult) {
return findLevelEntities(false, maxResults, firstResult);
}
private List<Level> findLevelEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Level.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Level findLevel(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Level.class, id);
} finally {
em.close();
}
}
public int getLevelCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Level> rt = cq.from(Level.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| bsd-3-clause |
rnathanday/dryad-repo | dspace/modules/payment-system/payment-api/src/main/java/org/dspace/paymentsystem/PaymentSystemService.java | 3748 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.paymentsystem;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.core.Context;
import org.dspace.workflow.WorkflowItem;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
/**
* PaymentService provides an interface for the DSpace application to
* interact with the Payment Service implementation.
*
* @author Mark Diggory, mdiggory at atmire.com
* @author Fabio Bolognesi, fabio at atmire.com
* @author Lantian Gai, lantian at atmire.com
*/
public interface PaymentSystemService
{
public ShoppingCart createNewShoppingCart(Context context, Integer itemId, Integer epersonId, String country, String currency, String status) throws SQLException, PaymentSystemException;
public void modifyShoppingCart(Context context, ShoppingCart transaction, DSpaceObject dso) throws AuthorizeException, SQLException, PaymentSystemException;
public void deleteShoppingCart(Context context, Integer transactionId) throws AuthorizeException, SQLException, PaymentSystemException;
public ShoppingCart getShoppingCart(Context context, Integer transactionId) throws SQLException;
public ShoppingCart[] findAllShoppingCart(Context context, Integer itemId) throws SQLException,PaymentSystemException;
public ShoppingCart getShoppingCartByItemId(Context context, Integer itemId) throws SQLException,PaymentSystemException;
public Double calculateShoppingCartTotal(Context context, ShoppingCart transaction, String journal) throws SQLException;
public double getSurchargeLargeFileFee(Context context, ShoppingCart transaction) throws SQLException;
public boolean getJournalSubscription(Context context, ShoppingCart transaction, String journal) throws SQLException;
public boolean hasDiscount(Context context, ShoppingCart transaction, String journal) throws SQLException;
public void updateTotal(Context context, ShoppingCart transaction, String journal) throws SQLException;
public void setCurrency(ShoppingCart shoppingCart,String currency)throws SQLException;
public int getWaiver(Context context,ShoppingCart shoppingcart,String journal)throws SQLException;
public boolean getCountryWaiver(Context context, ShoppingCart transaction) throws SQLException;
public String getPayer(Context context,ShoppingCart shoppingcart,String journal)throws SQLException;
public String printShoppingCart(Context c, ShoppingCart shoppingCart);
public void generateShoppingCart(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart transaction,PaymentSystemConfigurationManager manager,String baseUrl,Map<String,String> messages) throws WingException,SQLException;
public void generateNoEditableShoppingCart(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart transaction,PaymentSystemConfigurationManager manager,String baseUrl,Map<String,String> messages) throws WingException,SQLException;
public void sendPaymentApprovedEmail(Context c, WorkflowItem wfi, ShoppingCart shoppingCart);
public void sendPaymentErrorEmail(Context c, WorkflowItem wfi, ShoppingCart shoppingCart, String error);
public void sendPaymentWaivedEmail(Context c, WorkflowItem wfi, ShoppingCart shoppingCart);
public void sendPaymentRejectedEmail(Context c, WorkflowItem wfi, ShoppingCart shoppingCart);
}
| bsd-3-clause |
SnakeDoc/GuestVM | guestvm~guestvm/com.oracle.max.ve.nfsserver/src/org/acplt/oncrpc/XdrChar.java | 3460 | /*
* $Header: /cvsroot/remotetea/remotetea/src/org/acplt/oncrpc/XdrChar.java,v
* 1.1.1.1 2003/08/13 12:03:44 haraldalbrecht Exp $
*
* Copyright (c) 1999, 2000 Lehrstuhl fuer Prozessleittechnik (PLT), RWTH Aachen
* D-52064 Aachen, Germany. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Library General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more
* details.
*
* You should have received a copy of the GNU Library General Public License
* along with this program (see the file COPYING.LIB for more details); if not,
* write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
* 02139, USA.
*/
package org.acplt.oncrpc;
import java.io.IOException;
/**
* Instances of the class <code>XdrChar</code> represent (de-)serializeable
* chars, which are especially useful in cases where a result with only a single
* char is expected from a remote function call or only a single char parameter
* needs to be supplied.
*
* <p>
* Please note that this class is somewhat modelled after Java's primitive data
* type wrappers. As for these classes, the XDR data type wrapper classes follow
* the concept of values with no identity, so you are not allowed to change the
* value after you've created a value object.
*
* @version $Revision: 1.1.1.1 $ $Date: 2003/08/13 12:03:44 $ $State: Exp $
* $Locker: $
* @author Harald Albrecht
*/
public class XdrChar implements XdrAble {
/**
* The encapsulated char value itself.
*/
private char value;
/**
* Constructs and initializes a new <code>XdrChar</code> object.
*/
public XdrChar() {
this.value = 0;
}
/**
* Constructs and initializes a new <code>XdrChar</code> object.
*
* @param value
* Char value.
*/
public XdrChar(char value) {
this.value = value;
}
/**
* Returns the value of this <code>XdrChar</code> object as a char
* primitive.
*
* @return The primitive <code>char</code> value of this object.
*/
public char charValue() {
return this.value;
}
/**
* Decodes -- that is: deserializes -- a XDR char from a XDR stream in
* compliance to RFC 1832.
*
* @throws OncRpcException
* if an ONC/RPC error occurs.
* @throws IOException
* if an I/O error occurs.
*/
public void xdrDecode(XdrDecodingStream xdr) throws OncRpcException,
IOException {
value = (char) xdr.xdrDecodeByte();
}
/**
* Encodes -- that is: serializes -- a XDR char into a XDR stream in
* compliance to RFC 1832.
*
* @throws OncRpcException
* if an ONC/RPC error occurs.
* @throws IOException
* if an I/O error occurs.
*/
public void xdrEncode(XdrEncodingStream xdr) throws OncRpcException,
IOException {
xdr.xdrEncodeByte((byte) value);
}
}
// End of XdrChar.java
| bsd-3-clause |
e-mission/cordova-jwt-auth | src/android/JWTAuthPlugin.java | 4609 | package edu.berkeley.eecs.emission.cordova.jwtauth;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import android.widget.Toast;
import com.google.android.gms.common.api.ResultCallback;
import edu.berkeley.eecs.emission.cordova.unifiedlogger.Log;
public class JWTAuthPlugin extends CordovaPlugin {
private static String TAG = "JWTAuthPlugin";
private AuthTokenCreator tokenCreator;
private static final int RESOLVE_ERROR_CODE = 2000;
@Override
public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException {
tokenCreator = AuthTokenCreationFactory.getInstance(cordova.getActivity());
if (action.equals("getUserEmail")) {
Activity ctxt = cordova.getActivity();
AuthPendingResult result = tokenCreator.getUserEmail();
result.setResultCallback(new ResultCallback<AuthResult>() {
@Override
public void onResult(@NonNull AuthResult authResult) {
if (authResult.getStatus().isSuccess()) {
callbackContext.success(authResult.getEmail());
} else {
callbackContext.error(authResult.getStatus().getStatusCode() + " : "+
authResult.getStatus().getStatusMessage());
}
}
});
return true;
} else if (action.equals("signIn")) {
AuthPendingResult result = tokenCreator.uiSignIn(this);
result.setResultCallback(new ResultCallback<AuthResult>() {
@Override
public void onResult(@NonNull AuthResult authResult) {
if (authResult.getStatus().isSuccess()) {
Toast.makeText(cordova.getActivity(), authResult.getEmail(),
Toast.LENGTH_SHORT).show();
callbackContext.success(authResult.getEmail());
} else {
callbackContext.error(authResult.getStatus().getStatusCode() + " : "+
authResult.getStatus().getStatusMessage());
}
}
});
return true;
} else if (action.equals("getJWT")) {
AuthPendingResult result = tokenCreator.getServerToken();
result.setResultCallback(new ResultCallback<AuthResult>() {
@Override
public void onResult(@NonNull AuthResult authResult) {
if (authResult.getStatus().isSuccess()) {
callbackContext.success(authResult.getToken());
} else {
callbackContext.error(authResult.getStatus().getStatusCode() + " : "+
authResult.getStatus().getStatusMessage());
}
// TODO: Figure out how to handle pending status codes here
// Would be helpful if I could actually generate some to test :)
}
});
return true;
} else if (action.equals("setPromptedAuthToken")) {
if (tokenCreator.getClass() != PromptedAuth.class) {
callbackContext.error("Attempting to set programmatic token conflicts"
+ "with configured auth method");
}
String email = data.getString(0);
Log.d(cordova.getActivity(),TAG,
"Force setting the prompted auth token = "+email);
((PromptedAuth)tokenCreator).writeStoredUserAuthEntry(cordova.getActivity(), email);
callbackContext.success(email);
return true;
} else {
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(cordova.getActivity(), TAG, "requestCode = " + requestCode + " resultCode = " + resultCode);
tokenCreator.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onNewIntent(Intent intent) {
Log.d(cordova.getActivity(), TAG, "onNewIntent(" + intent.getDataString() + ")");
if (tokenCreator != null) {
tokenCreator.onNewIntent(intent);
} else {
Log.i(cordova.getActivity(), TAG, "tokenCreator = null, ignoring intent"+intent.getDataString());
}
}
}
| bsd-3-clause |
lutece-platform/lutece-core | src/java/fr/paris/lutece/portal/service/dashboard/admin/AdminDashboardComponent.java | 1896 | /*
* Copyright (c) 2002-2022, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' 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 HOLDERS 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.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.dashboard.admin;
import fr.paris.lutece.portal.service.dashboard.DashboardComponent;
/**
*
* Abstract implementation of {@link IAdminDashboardComponent}
*
*/
public abstract class AdminDashboardComponent extends DashboardComponent implements IAdminDashboardComponent
{
}
| bsd-3-clause |
Pluto-tv/chromium-crosswalk | android_webview/java/src/org/chromium/android_webview/AwWebViewLifecycleObserver.java | 2205 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import android.content.Context;
import org.chromium.base.ThreadUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.net.NetworkChangeNotifier;
/**
* This class is intended to observe the lifetime of webviews. It receives
* a callback when the first webview instance (native aw_content) is created
* and when the last webview instance is destroyed.
*/
@JNINamespace("android_webview")
public class AwWebViewLifecycleObserver {
private static final String TAG = "AwWebViewLifecycle";
// Assume there is ACCESS_NETWORK_STATE permission unless told otherwise.
private static boolean sHasNetworkStatePermission = true;
// Called on UI thread.
@CalledByNative
private static void onFirstWebViewCreated(Context appContext) {
ThreadUtils.assertOnUiThread();
if (sHasNetworkStatePermission) {
try {
if (!NetworkChangeNotifier.isInitialized()) {
NetworkChangeNotifier.init(appContext);
}
NetworkChangeNotifier.registerToReceiveNotificationsAlways();
} catch (SecurityException e) {
// Cannot enable network information api. The application does not have the
// ACCESS_NETWORK_STATE permission.
sHasNetworkStatePermission = false;
}
}
}
// Called on UI thread.
@CalledByNative
private static void onLastWebViewDestroyed(Context appContext) {
ThreadUtils.assertOnUiThread();
if (sHasNetworkStatePermission && NetworkChangeNotifier.isInitialized()) {
// Force unregister for network change broadcasts.
NetworkChangeNotifier.setAutoDetectConnectivityState(false);
}
}
@VisibleForTesting
public static void setHasNetworkStatePermission(boolean allow) {
sHasNetworkStatePermission = allow;
}
}
| bsd-3-clause |
AlexRNL/SubtitleCorrector | src/test/java/com/alexrnl/subtitlecorrector/common/TranslationKeysTest.java | 5259 | package com.alexrnl.subtitlecorrector.common;
import static com.alexrnl.subtitlecorrector.common.TranslationKeys.KEYS;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/**
* Test suite for the {@link TranslationKeys} class.
* @author Alex
*/
public class TranslationKeysTest {
/**
* Test that the return values of the method is correct.
*/
@Test
public void testTranslations () {
assertEquals("subtitlecorrector.strategy", KEYS.strategy().toString());
assertEquals("subtitlecorrector.strategy.letterreplacement", KEYS.strategy().letterReplacement().toString());
assertEquals("subtitlecorrector.strategy.letterreplacement.description", KEYS.strategy().letterReplacement().description());
assertEquals("subtitlecorrector.strategy.letterreplacement.originalletter", KEYS.strategy().letterReplacement().originalLetter());
assertEquals("subtitlecorrector.strategy.letterreplacement.newletter", KEYS.strategy().letterReplacement().newLetter());
assertEquals("subtitlecorrector.strategy.letterreplacement.onlymissingfromdictionary", KEYS.strategy().letterReplacement().onlyMissingFromDictionary());
assertEquals("subtitlecorrector.strategy.letterreplacement.promptbeforecorrecting", KEYS.strategy().letterReplacement().promptBeforeCorrecting());
assertEquals("subtitlecorrector.strategy.fixpunctuation", KEYS.strategy().fixPunctuation().toString());
assertEquals("subtitlecorrector.strategy.fixpunctuation.description", KEYS.strategy().fixPunctuation().description());
assertEquals("subtitlecorrector.strategy.fixpunctuation.locale", KEYS.strategy().fixPunctuation().locale());
assertEquals("subtitlecorrector.strategy.checkspelling", KEYS.strategy().checkSpelling().toString());
assertEquals("subtitlecorrector.strategy.checkspelling.description", KEYS.strategy().checkSpelling().description());
assertEquals("subtitlecorrector.subtitleprovider.noaccess", KEYS.subtitleProvider().noAccess());
assertEquals("subtitlecorrector.subtitleprovider.foldervisiterror", KEYS.subtitleProvider().folderVisitError());
assertEquals("subtitlecorrector.subtitleprovider.notfilenotdirectory", KEYS.subtitleProvider().notFileNotDirectory());
assertEquals("subtitlecorrector.subtitleprovider.choosesubtitleformat", KEYS.subtitleProvider().chooseSubtitleFormat());
assertEquals("subtitlecorrector.subtitleprovider.subtitlefilereaderror", KEYS.subtitleProvider().subtitleFileReadError());
assertEquals("subtitlecorrector.subtitleprovider.nosubtitletocorrect", KEYS.subtitleProvider().noSubtitleToCorrect());
assertEquals("subtitlecorrector.gui.mainwindow.title", KEYS.gui().mainWindow().title());
assertEquals("subtitlecorrector.gui.mainwindow.subtitleLabel", KEYS.gui().mainWindow().subtitleLabel());
assertEquals("subtitlecorrector.gui.mainwindow.subtitleButton", KEYS.gui().mainWindow().subtitleButton());
assertEquals("subtitlecorrector.gui.mainwindow.strategyLabel", KEYS.gui().mainWindow().strategyLabel());
assertEquals("subtitlecorrector.gui.mainwindow.overwriteLabel", KEYS.gui().mainWindow().overwriteLabel());
assertEquals("subtitlecorrector.gui.mainwindow.strategyParameters", KEYS.gui().mainWindow().strategyParameters());
assertEquals("subtitlecorrector.gui.mainwindow.localeLabel", KEYS.gui().mainWindow().localeLabel());
assertEquals("subtitlecorrector.gui.mainwindow.startCorrectingButton", KEYS.gui().mainWindow().startCorrectingButton());
assertEquals("subtitlecorrector.gui.userprompt.replacewithcontext", KEYS.gui().userPrompt().replaceWithContext());
assertEquals("subtitlecorrector.gui.userprompt.replace", KEYS.gui().userPrompt().replace());
assertEquals("subtitlecorrector.gui.userprompt.rememberchoice", KEYS.gui().userPrompt().rememberChoice());
assertEquals("subtitlecorrector.console.yes", KEYS.console().yes());
assertEquals("subtitlecorrector.console.no", KEYS.console().no());
assertEquals("subtitlecorrector.console.promptmark", KEYS.console().promptMark());
assertEquals("subtitlecorrector.console.yesnoprompt", KEYS.console().yesNoPrompt());
assertEquals("subtitlecorrector.console.userprompt", KEYS.console().userPrompt().toString());
assertEquals("subtitlecorrector.console.userprompt.invalidchoice", KEYS.console().userPrompt().invalidChoice());
assertEquals("subtitlecorrector.console.userprompt.replace", KEYS.console().userPrompt().replace());
assertEquals("subtitlecorrector.console.userprompt.context", KEYS.console().userPrompt().context());
assertEquals("subtitlecorrector.console.userprompt.changereplacement", KEYS.console().userPrompt().changeReplacement());
assertEquals("subtitlecorrector.console.userprompt.rememberchoice", KEYS.console().userPrompt().rememberChoice());
assertEquals("subtitlecorrector.console.app", KEYS.console().app().toString());
assertEquals("subtitlecorrector.console.app.strategyparametersinput", KEYS.console().app().strategyParametersInput());
assertEquals("subtitlecorrector.console.app.strategyparametersinvalidvalue", KEYS.console().app().strategyParametersInvalidValue());
assertEquals("subtitlecorrector.console.app.subtitlewriteerror", KEYS.console().app().subtitleWriteError());
assertEquals("subtitlecorrector.misc.fileExtension", KEYS.misc().fileExtension());
}
}
| bsd-3-clause |
NCIP/xmihandler | src/gov/nih/nci/ncicb/xmiinout/domain/UMLVisibility.java | 434 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/xmihandler/LICENSE.txt for details.
*/
package gov.nih.nci.ncicb.xmiinout.domain;
/**
* Wrapper class for a UML Visibility.
*/
public interface UMLVisibility {
/**
*
* @return The visibility name, for example 'public'
*/
public String getName();
} | bsd-3-clause |
BlackyPaw/I18N | i18n-spigot/src/main/java/com/blackypaw/mc/i18n/interceptor/v1_10/InterceptorSlot.java | 4216 | /*
* Copyright (c) 2016, BlackyPaw
* All rights reserved.
*
* This code is licensed under a BSD 3-Clause license. For further license details view the LICENSE file in the root folder of this source tree.
*/
package com.blackypaw.mc.i18n.interceptor.v1_10;
import com.blackypaw.mc.i18n.I18NSpigotImpl;
import com.blackypaw.mc.i18n.InterceptorBase;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.reflect.EquivalentConverter;
import com.comphenix.protocol.wrappers.BukkitConverters;
import com.google.gson.Gson;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* @author BlackyPaw
* @version 1.0
*/
public class InterceptorSlot extends InterceptorBase {
public InterceptorSlot( Plugin plugin, Gson gson, I18NSpigotImpl i18n ) {
super( plugin, gson, i18n, ListenerPriority.LOWEST, PacketType.Play.Server.SET_SLOT, PacketType.Play.Server.WINDOW_ITEMS );
}
@Override
public void onPacketSending( PacketEvent event ) {
if ( event.getPacketType() == PacketType.Play.Server.SET_SLOT ) {
this.onSetSlot( event );
} else if ( event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS ) {
this.onWindowItems( event );
}
}
private void onSetSlot( PacketEvent event ) {
final Player player = event.getPlayer();
final PacketContainer packet = event.getPacket();
final Locale language = this.i18n.getLocale( player.getUniqueId() );
ItemStack stack = packet.getItemModifier().read( 0 );
if ( stack != null ) {
ItemMeta meta = stack.getItemMeta();
if ( meta == null ) {
return;
}
String message = meta.getDisplayName();
if ( message == null ) {
return;
}
//self.getLogger().info( "#SetSlot: Message of Item = " + message );
String translated = this.translateMessageIfAppropriate( language, message );
if ( message != translated ) {
// Only write back when really needed:
// Got to clone here as otherwise we might be modifying an instance that
// is actually also used by the inventory:
stack = stack.clone();
meta = stack.getItemMeta();
meta.setDisplayName( translated );
stack.setItemMeta( meta );
packet.getItemModifier().write( 0, stack );
}
}
}
private void onWindowItems( PacketEvent event ) {
final Player player = event.getPlayer();
final PacketContainer packet = event.getPacket();
final Locale language = this.i18n.getLocale( player.getUniqueId() );
boolean changed = false;
ItemStack[] items = packet.getItemArrayModifier().read( 0 );
if ( items != null ) {
for ( int i = 0; i < items.length; ++i ) {
ItemStack stack = items[i];
if ( stack == null ) {
continue;
}
ItemMeta meta = stack.getItemMeta();
if ( meta == null ) {
continue;
}
String message = meta.getDisplayName();
if ( message == null ) {
continue;
}
//self.getLogger().info( "#WindowItems: Message of Item = " + message );
String translated = this.translateMessageIfAppropriate( language, message );
if ( message != translated ) {
// Got to localize the item's display name:
if ( !changed ) {
// Construct a shallow clone of the array as we do NOT want
// to overwrite the original stack with the contents we modified:
items = Arrays.copyOf( items, items.length );
}
// Got to clone the item stack here in order not to modify its original
// reference as it might be in use by the actual inventory:
stack = stack.clone();
meta = stack.getItemMeta();
meta.setDisplayName( translated );
stack.setItemMeta( meta );
items[i] = stack;
changed = true;
}
}
if ( changed ) {
// Only write back when really needed:
packet.getItemArrayModifier().write( 0, items );
}
}
}
}
| bsd-3-clause |
dynaTrace/Dynatrace-IBM-MQ-Queue-Channel-Monitoring-Plugin | src/com/dynatrace/plugin/util/EnvEmulator.java | 2027 | package com.dynatrace.plugin.util;
import java.io.File;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import com.dynatrace.diagnostics.pdk.MonitorEnvironment;
import com.dynatrace.diagnostics.pdk.MonitorMeasure;
public class EnvEmulator implements MonitorEnvironment {
Map<String, Object> envInternal;
public Map<String, Object> getEnvInternal() {
return envInternal;
}
public void setEnvInternal(Map<String, Object> envInternal) {
this.envInternal = envInternal;
}
public String getConfigString(String key) {
return (String)envInternal.get(key);
}
public Boolean getConfigBoolean(String key) {
return (Boolean)envInternal.get(key);
}
public String getConfigPassword(String key) {
return (String) envInternal.get(key);
}
public com.dynatrace.diagnostics.pdk.PluginEnvironment.Host getHost() {
return (Host)envInternal.get("Host");
}
@Override
public Date getConfigDate(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Double getConfigDouble(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
@Deprecated
public File getConfigFile(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Long getConfigLong(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getConfigUrl(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isStopped() {
// TODO Auto-generated method stub
return false;
}
@Override
public MonitorMeasure createDynamicMeasure(MonitorMeasure arg0,
String arg1, String arg2) {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<MonitorMeasure> getMonitorMeasures() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<MonitorMeasure> getMonitorMeasures(String arg0,
String arg1) {
// TODO Auto-generated method stub
return null;
}
}
| bsd-3-clause |
lmoroney/k-9 | tests/src/com/fsck/k9/helper/HtmlConverterTest.java | 7280 | package com.fsck.k9.helper;
import junit.framework.TestCase;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class HtmlConverterTest extends TestCase {
// Useful if you want to write stuff to a file for debugging in a browser.
private static final boolean WRITE_TO_FILE = Boolean.parseBoolean(System.getProperty("k9.htmlConverterTest.writeToFile", "false"));
private static final String OUTPUT_FILE = "C:/temp/parse.html";
public void testTextQuoteToHtmlBlockquote() {
String message = "Panama!\n" +
"\n" +
"Bob Barker <bob@aol.com> wrote:\n" +
"> a canal\n" +
">\n" +
"> Dorothy Jo Gideon <dorothy@aol.com> espoused:\n" +
"> >A man, a plan...\n" +
"> Too easy!\n" +
"\n" +
"Nice job :)\n" +
">> Guess!";
String result = HtmlConverter.textToHtml(message);
writeToFile(result);
assertEquals("<pre class=\"k9mail\">"
+ "Panama!<br />"
+ "<br />"
+ "Bob Barker <bob@aol.com> wrote:<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #729fcf; padding-left: 1ex;\">"
+ " a canal<br />"
+ "<br />"
+ " Dorothy Jo Gideon <dorothy@aol.com> espoused:<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #ad7fa8; padding-left: 1ex;\">"
+ "A man, a plan...<br />"
+ "</blockquote>"
+ " Too easy!<br />"
+ "</blockquote>"
+ "<br />"
+ "Nice job :)<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #729fcf; padding-left: 1ex;\">"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #ad7fa8; padding-left: 1ex;\">"
+ " Guess!"
+ "</blockquote>"
+ "</blockquote>"
+ "</pre>", result);
}
public void testTextQuoteToHtmlBlockquoteIndented() {
String message = "*facepalm*\n" +
"\n" +
"Bob Barker <bob@aol.com> wrote:\n" +
"> A wise man once said...\n" +
">\n" +
"> LOL F1RST!!!!!\n" +
">\n" +
"> :)";
String result = HtmlConverter.textToHtml(message);
writeToFile(result);
assertEquals("<pre class=\"k9mail\">"
+ "*facepalm*<br />"
+ "<br />"
+ "Bob Barker <bob@aol.com> wrote:<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #729fcf; padding-left: 1ex;\">"
+ " A wise man once said...<br />"
+ "<br />"
+ " LOL F1RST!!!!!<br />"
+ "<br />"
+ " :)"
+ "</blockquote></pre>", result);
}
public void testQuoteDepthColor() {
assertEquals(HtmlConverter.getQuoteColor(1), HtmlConverter.QUOTE_COLOR_LEVEL_1);
assertEquals(HtmlConverter.getQuoteColor(2), HtmlConverter.QUOTE_COLOR_LEVEL_2);
assertEquals(HtmlConverter.getQuoteColor(3), HtmlConverter.QUOTE_COLOR_LEVEL_3);
assertEquals(HtmlConverter.getQuoteColor(4), HtmlConverter.QUOTE_COLOR_LEVEL_4);
assertEquals(HtmlConverter.getQuoteColor(5), HtmlConverter.QUOTE_COLOR_LEVEL_5);
assertEquals(HtmlConverter.getQuoteColor(-1), HtmlConverter.QUOTE_COLOR_DEFAULT);
assertEquals(HtmlConverter.getQuoteColor(0), HtmlConverter.QUOTE_COLOR_DEFAULT);
assertEquals(HtmlConverter.getQuoteColor(6), HtmlConverter.QUOTE_COLOR_DEFAULT);
String message = "zero\n" +
"> one\n" +
">> two\n" +
">>> three\n" +
">>>> four\n" +
">>>>> five\n" +
">>>>>> six";
String result = HtmlConverter.textToHtml(message);
writeToFile(result);
assertEquals("<pre class=\"k9mail\">"
+ "zero<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #729fcf; padding-left: 1ex;\">"
+ " one<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #ad7fa8; padding-left: 1ex;\">"
+ " two<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #8ae234; padding-left: 1ex;\">"
+ " three<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #fcaf3e; padding-left: 1ex;\">"
+ " four<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #e9b96e; padding-left: 1ex;\">"
+ " five<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #ccc; padding-left: 1ex;\">"
+ " six"
+ "</blockquote>"
+ "</blockquote>"
+ "</blockquote>"
+ "</blockquote>"
+ "</blockquote>"
+ "</blockquote>"
+ "</pre>", result);
}
private void writeToFile(final String content) {
if (!WRITE_TO_FILE) {
return;
}
try {
System.err.println(content);
File f = new File(OUTPUT_FILE);
f.delete();
FileWriter fstream = new FileWriter(OUTPUT_FILE);
BufferedWriter out = new BufferedWriter(fstream);
out.write(content);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void testPreserveSpacesAtFirst() {
String message = "foo\n"
+ " bar\n"
+ " baz\n";
String result = HtmlConverter.textToHtml(message);
writeToFile(result);
assertEquals("<pre class=\"k9mail\">"
+ "foo<br />"
+ " bar<br />"
+ " baz<br />"
+ "</pre>", result);
}
public void testPreserveSpacesAtFirstForSpecialCharacters() {
String message =
" \n"
+ " &\n"
+ " \r\n"
+ " <\n"
+ " > \n";
String result = HtmlConverter.textToHtml(message);
writeToFile(result);
assertEquals("<pre class=\"k9mail\">"
+ " <br />"
+ " &<br />"
+ " <br />"
+ " <<br />"
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 1ex 0.8ex; border-left: 1px solid #729fcf; padding-left: 1ex;\">"
+ " <br />"
+ "</blockquote>"
+ "</pre>", result);
}
}
| bsd-3-clause |
iig-uni-freiburg/SecSy | src/de/uni/freiburg/iig/telematik/secsy/logic/generator/properties/CaseDataContainerProperties.java | 10523 | package de.uni.freiburg.iig.telematik.secsy.logic.generator.properties;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import de.invation.code.toval.misc.ArrayUtils;
import de.invation.code.toval.misc.StringUtils;
import de.invation.code.toval.misc.valuegeneration.StochasticValueGenerator;
import de.invation.code.toval.properties.AbstractProperties;
import de.invation.code.toval.properties.PropertyException;
import de.invation.code.toval.validate.ParameterException;
import de.invation.code.toval.validate.ParameterException.ErrorCode;
import de.invation.code.toval.validate.Validate;
import de.uni.freiburg.iig.telematik.secsy.logic.generator.AttributeValueGenerator;
public class CaseDataContainerProperties extends AbstractProperties {
private final String VALUE_GENERATOR_FORMAT = CaseDataContainerProperty.VALUE_GENERATOR + "_%s";
private final String VALUE_GENERATOR_VALUE_FORMAT = "%s %s"; //attribute + type
private final String VALUE_GENERATOR_PROBABILITY_FORMAT = CaseDataContainerProperty.VALUE_GENERATOR_PROBABILITY + "_%s_%s";
private final String VALUE_GENERATOR_PROBABILITY_VALUE_FORMAT = "%s %s"; //value + probability
private final String NUMBER_OF_PROBABILITIES_FORMAT = CaseDataContainerProperty.NUMBER_OF_PROBABILITIES + "_%s";
//------- Property setting -------------------------------------------------------------
private void setProperty(CaseDataContainerProperty containerProperty, Object value){
props.setProperty(containerProperty.toString(), value.toString());
}
private String getProperty(CaseDataContainerProperty containerProperty){
return props.getProperty(containerProperty.toString());
}
//-- Container name
public void setName(String name) {
validateStringValue(name);
setProperty(CaseDataContainerProperty.CONTAINER_NAME, name);
}
public String getName() throws PropertyException {
String propertyValue = getProperty(CaseDataContainerProperty.CONTAINER_NAME);
if(propertyValue == null)
throw new PropertyException(CaseDataContainerProperty.CONTAINER_NAME, propertyValue);
return propertyValue;
}
// //-- Context name
//
// public void setContextName(String contextName) {
// Validate.notNull(contextName);
// Validate.notEmpty(contextName);
// setProperty(CaseDataContainerProperty.CONTEXT_NAME, contextName);
// }
//
// public String getContextName() throws PropertyException, ParameterException {
// String propertyValue = getProperty(CaseDataContainerProperty.CONTEXT_NAME);
// if(propertyValue == null)
// throw new PropertyException(CaseDataContainerProperty.CONTEXT_NAME, propertyValue);
//
// validateStringValue(propertyValue);
//
// return propertyValue;
// }
//-- Attribute value generator
public void setAttributeValueGenerator(AttributeValueGenerator generator) {
Validate.notNull(generator);
setDefaultValue(generator.getDefaultValue());
for(String attribute: generator.getAttributes()){
//TODO: Note, that this cast fails, if other value generators are permitted!!!
addValueGenerator(attribute, (StochasticValueGenerator<?>) generator.getValueGenerator(attribute));
}
}
public AttributeValueGenerator getAttributeValueGenerator() throws PropertyException{
AttributeValueGenerator result = new AttributeValueGenerator();
result.setDefaultValue(getDefaultValue());
for(String valueGeneratorName: getValueGeneratorNames()){
String attribute = null;
try{
attribute = valueGeneratorName.substring(CaseDataContainerProperty.VALUE_GENERATOR.toString().length()+1, valueGeneratorName.length());
} catch(Exception e) {
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR, valueGeneratorName, "Invalid property value, cannot extract attribute name.");
}
result.setValueGeneration(attribute, getValueGenerator(valueGeneratorName));
}
return result;
}
//-- Default value
private void setDefaultValue(Object defaultValue) {
if(defaultValue == null){
setProperty(CaseDataContainerProperty.DEFAULT_VALUE, "null");
setProperty(CaseDataContainerProperty.DEFAULT_VALUE_TYPE, Object.class.getName().toString());
} else {
setProperty(CaseDataContainerProperty.DEFAULT_VALUE, defaultValue.toString());
setProperty(CaseDataContainerProperty.DEFAULT_VALUE_TYPE, defaultValue.getClass().getName().toString());
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object getDefaultValue() throws PropertyException {
String propertyValue = getProperty(CaseDataContainerProperty.DEFAULT_VALUE);
String propertyValueType = getProperty(CaseDataContainerProperty.DEFAULT_VALUE_TYPE);
if(propertyValue == null)
return propertyValue;
if(propertyValueType == null)
throw new PropertyException(CaseDataContainerProperty.DEFAULT_VALUE_TYPE, propertyValue, "No type information for default value");
if(propertyValue.equals("null"))
return null;
try {
Class valueClass = Class.forName(propertyValueType);
return valueClass.getDeclaredConstructor(String.class).newInstance(propertyValue);
} catch (ClassNotFoundException e) {
throw new PropertyException(CaseDataContainerProperty.DEFAULT_VALUE_TYPE, propertyValue, "Invalid value type (cannot load class): " + propertyValueType);
} catch(Exception e){
throw new PropertyException(CaseDataContainerProperty.DEFAULT_VALUE_TYPE, propertyValue, "Cannot cast value to class " + propertyValueType);
}
}
//-- Value generator
private void addValueGenerator(String attribute, StochasticValueGenerator<?> valueGenerator) {
Validate.notNull(attribute);
Validate.notNull(valueGenerator);
if(!valueGenerator.isValid())
throw new ParameterException(ErrorCode.INCOMPATIBILITY, "Cannot add invalid value generator.");
//1. Add the generator itself
String propertyNameForNewGenerator = String.format(VALUE_GENERATOR_FORMAT, attribute);
props.setProperty(propertyNameForNewGenerator, String.format(VALUE_GENERATOR_VALUE_FORMAT, '"'+attribute+'"', valueGenerator.getValueClass().getName()));
Integer countProbabilities = 0;
for(Object element: valueGenerator.getElements()){
props.setProperty(String.format(VALUE_GENERATOR_PROBABILITY_FORMAT, attribute, ++countProbabilities),
String.format(VALUE_GENERATOR_PROBABILITY_VALUE_FORMAT, element, valueGenerator.getProbability(element).toString()));
}
props.setProperty(String.format(NUMBER_OF_PROBABILITIES_FORMAT, attribute), countProbabilities.toString());
//2. Save a link in the list of generators
Set<String> currentGenerators = getValueGeneratorNames();
currentGenerators.add(propertyNameForNewGenerator);
setProperty(CaseDataContainerProperty.VALUE_GENERATORS, ArrayUtils.toString(currentGenerators.toArray()));
}
private Set<String> getValueGeneratorNames(){
Set<String> result = new HashSet<String>();
String propertyValue = getProperty(CaseDataContainerProperty.VALUE_GENERATORS);
if(propertyValue == null)
return result;
StringTokenizer activityTokens = StringUtils.splitArrayString(propertyValue, " ");
while(activityTokens.hasMoreTokens()){
result.add(activityTokens.nextToken());
}
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private StochasticValueGenerator<?> getValueGenerator(String valueGeneratorName) throws PropertyException{
Validate.notNull(valueGeneratorName);
String propertyValue = props.getProperty(valueGeneratorName);
String attribute = null;
String className = null;
try{
attribute = propertyValue.substring(1, propertyValue.lastIndexOf(' ')-1);
className = propertyValue.substring(propertyValue.lastIndexOf(' ')+1);
} catch(Exception e) {
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR, propertyValue, "Invalid property value, cannot extract attribute and class name.");
}
Class valueClass = null;
try {
valueClass = Class.forName(className);
} catch (ClassNotFoundException e) {
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR, propertyValue, "Invalid class name value.");
}
StochasticValueGenerator valueGenerator = new StochasticValueGenerator();
String countProbabilitiesPropertyValue = props.getProperty(String.format(NUMBER_OF_PROBABILITIES_FORMAT, attribute));
if(countProbabilitiesPropertyValue == null)
throw new PropertyException(CaseDataContainerProperty.NUMBER_OF_PROBABILITIES, propertyValue, "Cannot extract number of probabilities for attribute: " + attribute);
Integer countProbabilities = null;
try{
countProbabilities = Integer.parseInt(countProbabilitiesPropertyValue);
} catch(Exception e){
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR, propertyValue, "Cannot extract number of probabilities for attribute: " + attribute);
}
for(int i=1; i<=countProbabilities; i++){
String probabilityPropertyValue = props.getProperty(String.format(VALUE_GENERATOR_PROBABILITY_FORMAT, attribute, i));
if(probabilityPropertyValue == null)
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR_PROBABILITY, propertyValue, "Cannot extract probability for attribute: " + attribute);
String keyString = null;
String probabilityString = null;
try{
keyString = probabilityPropertyValue.substring(0, probabilityPropertyValue.indexOf(' '));
probabilityString = probabilityPropertyValue.substring(probabilityPropertyValue.indexOf(' ')+1);
}catch(Exception e){
throw new PropertyException(CaseDataContainerProperty.VALUE_GENERATOR_PROBABILITY, propertyValue, "Invalid property value: Cannot extract probability and value information for attribute "+attribute);
}
Object key = null;
Double probability = null;
try{
key = valueClass.getDeclaredConstructor(String.class).newInstance(keyString);
}catch(Exception e){
throw new PropertyException(CaseDataContainerProperty.NUMBER_OF_PROBABILITIES, propertyValue, "Invalid property value for attribute "+attribute+": value \""+keyString+"\"does not seem to be of type \""+valueClass.getName()+"\"");
}
try{
probability = Double.parseDouble(probabilityString);
Validate.probability(probability);
}catch(Exception e){
throw new PropertyException(CaseDataContainerProperty.NUMBER_OF_PROBABILITIES, propertyValue, "Invalid property value for attribute "+attribute+": value \""+probabilityString+"\"does not seem to be a probability");
}
valueGenerator.addProbability(key, probability);
}
return valueGenerator;
}
}
| bsd-3-clause |
fresskarma/tinyos-1.x | tools/java/net/tinyos/surge/PacketAnalyzer/PacketAnalyzer.java | 4625 | // $Id: PacketAnalyzer.java,v 1.2 2003/10/07 21:46:05 idgay Exp $
/* tab:4
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/* Authors: Kamin Whitehouse <kamin@cs.berkeley.edu>
* History: created 7/22/2001
*/
//***********************************************************************
//***********************************************************************
//This is the parent class to all PacketAnalyzers
//***********************************************************************
//***********************************************************************
/**
* @author Kamin Whitehouse <kamin@cs.berkeley.edu>
*/
package net.tinyos.surge.PacketAnalyzer;
import net.tinyos.surge.*;
import net.tinyos.surge.event.*;
import net.tinyos.surge.util.*;
import net.tinyos.message.*;
import net.tinyos.util.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.awt.*;
import javax.swing.*;
import net.tinyos.surge.Dialog.*;
public abstract class PacketAnalyzer implements MessageListener, PacketEventListener, NodeClickedEventListener, EdgeClickedEventListener, NodeEventListener, EdgeEventListener, NodePainter, EdgePainter, ScreenPainter, NodeDialogContributor, EdgeDialogContributor
{
public PacketAnalyzer() {
MainClass.getMoteIF().registerListener(new SurgeMsg(), this);
}
// For MessageListener
public void messageReceived(int addr, Message m) {
MultihopMsg msg = new MultihopMsg(m.dataGet());
this.PacketReceived(msg);
}
public void PacketReceived(MultihopMsg msg) { }
public void NodeCreated(NodeEvent e) { }
public void NodeDeleted(NodeEvent e) { }
public void EdgeCreated(EdgeEvent e) { }
public void EdgeDeleted(EdgeEvent e) { }
public void NodeClicked(NodeClickedEvent e) { }
public void EdgeClicked(EdgeClickedEvent e) { }
public void PaintNode(Integer pNodeNumber, int x1, int y1, int x2, int y2, Graphics g) { }
public void PaintEdge(Integer pSourceNodeNumber, Integer pDestinationNodeNumber, int screenX1, int screenY1, int screenX2, int screenY2, Graphics g) { }
public void PaintScreenBefore(Graphics g) { }
public void PaintScreenAfter(Graphics g) { }
public ActivePanel GetProprietaryNodeInfoPanel(Integer nodeNumber) {
return null;
}
public ActivePanel GetProprietaryEdgeInfoPanel(Integer source, Integer destination) {
return null;
}
public void AnalyzerDisplayEnable() {
MainClass.displayManager.AddScreenPainter(this);//paint on the screen over the edges and nodes
//register myself to be able to contribute to the node/edge properties panel
MainClass.displayManager.AddNodeDialogContributor(this);
MainClass.displayManager.AddEdgeDialogContributor(this);
MainClass.displayManager.AddNodePainter(this);//paint the nodes
}
public void AnalyzerDisplayDisable() {
MainClass.displayManager.RemoveScreenPainter(this);//paint on the screen over the edges and nodes
//register myself to be able to contribute to the node/edge properties panel
MainClass.displayManager.RemoveNodeDialogContributor(this);
MainClass.displayManager.RemoveEdgeDialogContributor(this);
MainClass.displayManager.RemoveNodePainter(this);//paint the nodes
}
}
| bsd-3-clause |
Bob319/RecycleRushDev | src/org/usfirst/frc319/commands/PnuematicSystemOn.java | 1663 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc319.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc319.Robot;
/**
*
*/
public class PnuematicSystemOn extends Command {
public PnuematicSystemOn() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.pnuematicSystem);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.pnuematicSystem.compressorOn();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| bsd-3-clause |
fraunhoferfokus/govapps | concern-portlet/src/main/java/com/govapps/persistence/service/ConcernServiceWrapper.java | 3862 | package com.govapps.persistence.service;
/*
* #%L
* govapps_concern
* $Id: ConcernServiceWrapper.java 566 2014-11-13 15:22:01Z sma $
* %%
* Copyright (C) 2013 - 2014 Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT
* %%
* Copyright (c) 2,013, Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3) All advertising materials mentioning features or use of this software must
* display the following acknowledgement:
* This product includes software developed by Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT.
*
* 4) Neither the name of the organization 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 COPYRIGHT HOLDER ''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
* Fraunhofer FOKUS, Kompetenzzentrum Oeffentliche IT
* 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.
* #L%
*/
import com.liferay.portal.service.ServiceWrapper;
/**
* <p>
* This class is a wrapper for {@link ConcernService}.
* </p>
*
* @author ekl
* @see ConcernService
* @generated
*/
public class ConcernServiceWrapper implements ConcernService,
ServiceWrapper<ConcernService> {
private ConcernService _concernService;
public ConcernServiceWrapper(ConcernService concernService) {
_concernService = concernService;
}
/**
* Returns the Spring bean ID for this bean.
*
* @return the Spring bean ID for this bean
*/
public java.lang.String getBeanIdentifier() {
return _concernService.getBeanIdentifier();
}
/**
* Sets the Spring bean ID for this bean.
*
* @param beanIdentifier the Spring bean ID for this bean
*/
public void setBeanIdentifier(java.lang.String beanIdentifier) {
_concernService.setBeanIdentifier(beanIdentifier);
}
public java.lang.Object invokeMethod(java.lang.String name,
java.lang.String[] parameterTypes, java.lang.Object[] arguments)
throws java.lang.Throwable {
return _concernService.invokeMethod(name, parameterTypes, arguments);
}
/**
* @deprecated Renamed to {@link #getWrappedService}
*/
public ConcernService getWrappedConcernService() {
return _concernService;
}
/**
* @deprecated Renamed to {@link #setWrappedService}
*/
public void setWrappedConcernService(ConcernService concernService) {
_concernService = concernService;
}
public ConcernService getWrappedService() {
return _concernService;
}
public void setWrappedService(ConcernService concernService) {
_concernService = concernService;
}
}
| bsd-3-clause |
yfpeng/pengyifan-leetcode | src/test/java/com/pengyifan/leetcode/WordPatternTest.java | 530 | package com.pengyifan.leetcode;
import org.junit.Test;
import static org.junit.Assert.*;
public class WordPatternTest {
private WordPattern s = new WordPattern();
@Test
public void testWordPattern() throws Exception {
assertFalse(s.wordPattern("abba", "dog dog dog dog"));
}
@Test
public void testWordPattern2() throws Exception {
assertTrue(s.wordPattern("abba", "dog cat cat dog"));
}
@Test
public void testWordPattern3() throws Exception {
assertFalse(s.wordPattern("ab", "dog dog"));
}
} | bsd-3-clause |
MarinnaCole/LightZone | lightcrafts/src/com/lightcrafts/model/ImageEditor/SpotOperationImpl.java | 1495 | /* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.model.ImageEditor;
import com.lightcrafts.jai.utils.Transform;
import com.lightcrafts.model.*;
import com.lightcrafts.mediax.jai.*;
import com.lightcrafts.ui.editor.EditorMode;
public class SpotOperationImpl extends BlendedOperation implements SpotOperation {
public SpotOperationImpl(Rendering rendering) {
super(rendering, type);
}
@Override
public boolean neutralDefault() {
return true;
}
public void setRegionInverted(boolean inverted) {
// Inverted regions have no meaning for the Spot Tool
// super.setRegionInverted(inverted);
}
static final OperationType type = new OperationTypeImpl("Spot");
class Cloner extends BlendedTransform {
Cloner(PlanarImage source) {
super(source);
}
@Override
public PlanarImage setFront() {
if (getRegion() != null)
return CloneOperationImpl.buildCloner(getRegion(), rendering, back);
else
return back;
}
}
@Override
public EditorMode getPreferredMode() {
return EditorMode.REGION;
}
@Override
protected void updateOp(Transform op) {
op.update();
}
@Override
protected BlendedTransform createBlendedOp(PlanarImage source) {
return new Cloner(source);
}
@Override
public OperationType getType() {
return type;
}
}
| bsd-3-clause |
ClemsonRSRG/jetbrains-plugin-resolve | src/edu/clemson/resolve/jetbrains/runconfig/program/RESOLVEProgramRunConfigurationProducer.java | 2524 | package edu.clemson.resolve.jetbrains.runconfig.program;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import edu.clemson.resolve.jetbrains.psi.ResFile;
import edu.clemson.resolve.jetbrains.runconfig.RESOLVERunUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class RESOLVEProgramRunConfigurationProducer
extends
RunConfigurationProducer<RESOLVEProgramRunConfiguration> implements Cloneable {
protected RESOLVEProgramRunConfigurationProducer() {
super(RESOLVEProgramRunConfigurationType.getInstance());
}
@Override
protected boolean setupConfigurationFromContext(@NotNull RESOLVEProgramRunConfiguration configuration,
@NotNull ConfigurationContext context,
Ref<PsiElement> sourceElement) {
PsiFile file = getFileFromContext(context);
if (RESOLVERunUtil.isMainRESOLVEFile(file)) {
configuration.setName(getConfigurationName(file));
configuration.setFilePath(file.getVirtualFile().getPath());
Module module = context.getModule();
if (module != null) {
configuration.setModule(module);
}
return true;
}
return false;
}
@NotNull
protected String getConfigurationName(@NotNull PsiFile file) {
return "RESOLVE " + file.getName();
}
@Override
public boolean isConfigurationFromContext(@NotNull RESOLVEProgramRunConfiguration configuration,
ConfigurationContext context) {
ResFile file = getFileFromContext(context);
return file != null && FileUtil.pathsEqual(configuration.getFilePath(), file.getVirtualFile().getPath());
}
@Nullable
private static ResFile getFileFromContext(@Nullable ConfigurationContext context) {
PsiElement contextElement = RESOLVERunUtil.getContextElement(context);
PsiFile psiFile = contextElement != null ? contextElement.getContainingFile() : null;
return psiFile instanceof ResFile ? (ResFile)psiFile : null;
}
}
| bsd-3-clause |
loadtestgo/pizzascript | script-tester/src/main/java/com/loadtestgo/script/tester/tests/CookieTests.java | 2359 | package com.loadtestgo.script.tester.tests;
import com.loadtestgo.script.api.ErrorType;
import com.loadtestgo.script.api.TestResult;
import com.loadtestgo.script.tester.framework.JavaScriptTest;
import org.junit.Test;
public class CookieTests extends JavaScriptTest {
@Test
public void testCookiesSamePage() {
String script = String.format(
"b = pizza.open(\"%s\");\n" +
"var cookies = b.listCookies();\n" +
"assert.eq(2, cookies.length);\n" +
"b.setCookie('a', 'b');\n" +
"assert.eq('b', b.getCookie('a').value);\n" +
"assert.eq(3, b.listCookies().length);\n" +
"b.setCookie('a', 'c');\n" +
"assert.eq('c', b.getCookie('a').value);\n" +
"assert.eq(3, b.listCookies().length);\n" +
"b.clearCookies();\n" +
"assert.eq(0, b.listCookies().length);\n" +
"b.setCookie('a', 'c');\n" +
"assert.eq(1, b.listCookies().length);\n" +
"assert.eq('c', b.getCookie('a').value);\n" +
"b.removeCookie('a');\n" +
"assert.eq(0, b.listCookies().length);\n",
getTestUrl("files/cookies.html"));
TestResult result = runScript(script);
assertNoError(result);
}
@Test
public void testBadUrlSetCookie() {
String script = String.format(
"b = pizza.open(\"%s\");\n" +
"b.setCookie('a', 'b', {url:'http::'});\n",
getTestUrl("files/cookies.html"));
TestResult result = runScript(script);
assertError("Invalid url: \"http::\".", ErrorType.Script, result);
}
@Test
public void testBadUrlGetCookie() {
String script = String.format(
"b = pizza.open(\"%s\");\n" +
"b.getCookie('http::', 'a');\n",
getTestUrl("files/cookies.html"));
TestResult result = runScript(script);
assertError("Invalid url: \"http::\".", ErrorType.Script, result);
}
@Test
public void testBadUrlRemoveCookie() {
String script = String.format(
"b = pizza.open(\"%s\");\n" +
"b.removeCookie('http::', 'a');\n",
getTestUrl("files/cookies.html"));
TestResult result = runScript(script);
assertError("Invalid url: \"http::\".", ErrorType.Script, result);
}
}
| bsd-3-clause |
frc3528/testbot | src/com/teamupnext/robot/Robot.java | 3107 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package com.teamupnext.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import com.teamupnext.robot.commands.CommandBase;
import com.teamupnext.robot.commands.PrintDisabledInfo;
import com.teamupnext.robot.commands.PrintInfo;
import com.teamupnext.robot.commands.SetToDefault;
import com.teamupnext.robot.commands.StopShooter;
import com.teamupnext.robot.commands.TestAuto;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand = new TestAuto();
PrintDisabledInfo disabledInfo;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// instantiate the command used for the autonomous period
//autonomousCommand = new ExampleCommand();
// Initialize all subsystems
CommandBase.init();
disabledInfo = new PrintDisabledInfo();
}
public void autonomousInit() {
// schedule the autonomous command (example)
autonomousCommand.start();
disabledInfo.cancel();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
new PrintInfo().start();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
autonomousCommand.cancel();
new StopShooter().start();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
new PrintInfo().start();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
public void disabledInit() {
new SetToDefault().start();
}
public void testInit() {
System.out.println("test init");
}
}
| bsd-3-clause |
agmip/translator-apsim | src/main/java/org/agmip/translators/apsim/util/DateSerializer.java | 920 | package org.agmip.translators.apsim.util;
import java.io.IOException;
import java.text.ParseException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
/**
* @author Ioannis N. Athanasiadis, DUTh
* @author Dean Holzworth, CSIRO
* @since Jul 13, 2012
*/
public class DateSerializer extends JsonSerializer<String>{
@Override
public void serialize(String date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate="";
try {
formattedDate = Util.agmip.format(Util.apsim.parse(date));
} catch (ParseException e) {
throw new IOException(e);
}
gen.writeString(formattedDate);
}
}
| bsd-3-clause |
FRCTeam1073-TheForceTeam/robot17 | src/org/usfirst/frc1073/robot17/commands/AutonomousBlueGear2Fuel.java | 2648 | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc1073.robot17.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc1073.robot17.Robot;
import org.usfirst.frc1073.robot17.subsystems.*;
/**
*
*/
public class AutonomousBlueGear2Fuel extends CommandGroup {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
public AutonomousBlueGear2Fuel() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
addSequential(new AutonomousBlueGear2());
addSequential(new MoveAway());
//Drives near peg and auto-drives onto it
switch(Robot.driveMode)
{
case PID:
addSequential(new moveWithPID(22));
break;
case ROTATIONS:
addSequential(new DriveInches(11));
break;
case TIME:
addSequential(new TimedDrive(11, 0));
default:
break;
}
addSequential(new AutoTurn(.4, 100, "clockwise"));
switch(Robot.driveMode)
{
case PID:
addSequential(new moveWithPID(50));
break;
case ROTATIONS:
addSequential(new DriveInches(61));
break;
case TIME:
addSequential(new TimedDrive(61, 0));
default:
break;
}
addSequential(new AutoTurn(.3, 75, "counterclockwise"));
addSequential(new AlignAndLaunch());
//Drives near boiler and auto-drives into alignment
//addSequential(new AutoLaunch(0.5, 0.5));
}
}
| bsd-3-clause |
crosg/Albianj2 | Albianj.Test/src/main/java/Albian/Test/Services/IOrgUserService.java | 428 | package Albian.Test.Services;
import org.albianj.service.IAlbianService;
public interface IOrgUserService extends IAlbianService {
final String Name = "OrgUserService";
boolean login(String uname, String pwd);
boolean addUser(String uname, String pwd);
boolean modifyPwd(String uname, String orgPwd, String newPwd);
boolean batchAddUser();
void queryMulitUserById();
boolean tranOptUser();
}
| bsd-3-clause |
cFerg/CloudStorming | ObjectAvoidance/java/src/main/java/elite/gils/country/CC.java | 553 | package elite.gils.country;
/**
* Continent: (Name)
* Country: (Name)
*/
public enum CC {
//List of State/Province names (Use 2 Letter/Number Combination codes)
/**
* Name:
*/
AA("Example"),
/**
* Name:
*/
AB("Example"),
/**
* Name:
*/
AC("Example");
//Leave the code below alone (unless optimizing)
private final String name;
CC(String name){
this.name = name;
}
public String getName(CC state){
return state.name;
}
} | bsd-3-clause |
compgen-io/cgseq | src/java/io/compgen/cgseq/CGSUtilsException.java | 229 | package io.compgen.cgseq;
public class CGSUtilsException extends Exception {
public CGSUtilsException(String string) {
super(string);
}
/**
*
*/
private static final long serialVersionUID = -409000510259617015L;
}
| bsd-3-clause |
xe1gyq/OpenAttestation | common/crypto/src/main/java/com/intel/mtwilson/crypto/X509Util.java | 12654 | /*
* Copyright (c) 2013, Intel Corporation.
* All rights reserved.
*
* The contents of this file are released under the BSD license, you may not use this file except in compliance with the License.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.mtwilson.crypto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.security.x509.GeneralNameInterface;
/**
*
* @author jbuhacoff
*/
public class X509Util {
private static Logger log = LoggerFactory.getLogger(X509Util.class);
public static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
public static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
public static final String BEGIN_PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----";
public static final String END_PUBLIC_KEY = "-----END PUBLIC KEY-----";
public static final String BEGIN_RSA_PUBLIC_KEY = "-----BEGIN RSA PUBLIC KEY-----";
public static final String END_RSA_PUBLIC_KEY = "-----END RSA PUBLIC KEY-----";
public static final String PEM_NEWLINE = "\r\n";
/**
* See also RsaCredential in the security project.
* See also Sha256Digest in the datatypes project
* @param certificate
* @return
*/
public static byte[] sha256fingerprint(X509Certificate certificate) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest hash = MessageDigest.getInstance("SHA-256");
byte[] digest = hash.digest(certificate.getEncoded());
return digest;
}
/**
* Provided for compatibility with other systems.
* See also Sha1Digest in the datatypes project
* @param certificate
* @return
*/
public static byte[] sha1fingerprint(X509Certificate certificate) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest hash = MessageDigest.getInstance("SHA-1");
byte[] digest = hash.digest(certificate.getEncoded());
return digest;
}
/**
* Converts an X509 Certificate to PEM encoding, with lines up to 76 characters long.
* Newlines are carriage-return and line-feed.
* The end certificate tag also ends in a newline, so you can output a sequence of
* pem certificates into a file without having to insert any newlines yourself.
* @param certificate
* @return
* @throws CertificateEncodingException
*/
public static String encodePemCertificate(X509Certificate certificate) throws CertificateEncodingException {
// the function Base64.encodeBase64String does not chunk to 76 characters per line
String encoded = new String(Base64.encodeBase64(certificate.getEncoded(), true));
return BEGIN_CERTIFICATE+PEM_NEWLINE+encoded.trim()+PEM_NEWLINE+END_CERTIFICATE+PEM_NEWLINE;
}
public static String encodePemPublicKey(PublicKey publicKey) {
// the function Base64.encodeBase64String does not chunk to 76 characters per line
String encoded = new String(Base64.encodeBase64(publicKey.getEncoded(), true));
return BEGIN_PUBLIC_KEY+PEM_NEWLINE+encoded.trim()+PEM_NEWLINE+END_PUBLIC_KEY+PEM_NEWLINE;
}
/**
* This function converts a PEM-format certificate to an X509Certificate
* object.
*
* Example PEM format:
*
* -----BEGIN CERTIFICATE----- (base64 data here) -----END CERTIFICATE-----
*
* You can also pass just the base64 certificate data without the header and
* footer.
*
* @param text
* @return
* @throws CertificateException
*/
public static X509Certificate decodePemCertificate(String text) throws CertificateException {
String content = text.replace(BEGIN_CERTIFICATE, "").replace(END_CERTIFICATE, "");
byte[] der = Base64.decodeBase64(content);
return decodeDerCertificate(der);
}
public static List<X509Certificate> decodePemCertificates(String text) throws CertificateException {
String[] pems = StringUtils.splitByWholeSeparator(text, END_CERTIFICATE);
ArrayList<X509Certificate> certs = new ArrayList<X509Certificate>(pems.length);
for(String pem : pems) {
if( pem.trim().isEmpty() ) { continue; }
certs.add(decodePemCertificate(pem));
}
return certs;
}
public static PublicKey decodePemPublicKey(String text) throws CryptographyException {
String content = text;
if( text.contains(BEGIN_PUBLIC_KEY) ) {
content = text.replace(BEGIN_PUBLIC_KEY, "").replace(END_PUBLIC_KEY, "");
}
if( text.contains(BEGIN_RSA_PUBLIC_KEY) ) {
content = text.replace(BEGIN_RSA_PUBLIC_KEY, "").replace(END_RSA_PUBLIC_KEY, "");
}
byte[] der = Base64.decodeBase64(content);
return decodeDerPublicKey(der);
}
/**
* Reads a DER-encoded certificate and creates a corresponding X509Certificate
* object.
* @param certificateBytes
* @return
* @throws CertificateException
*/
public static X509Certificate decodeDerCertificate(byte[] certificateBytes) throws CertificateException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));
return cert;
}
/**
* For completeness. The X509Certificate.getEncoded() method returns the DER
* encoding of the certificate.
* @param certificate
* @return
* @throws CertificateEncodingException
*/
public static byte[] encodeDerCertificate(X509Certificate certificate) throws CertificateEncodingException {
return certificate.getEncoded();
}
public static PublicKey decodeDerPublicKey(byte[] publicKeyBytes) throws CryptographyException {
try {
KeyFactory factory = KeyFactory.getInstance("RSA"); // throws NoSuchAlgorithmException
PublicKey publicKey = factory.generatePublic(new X509EncodedKeySpec(publicKeyBytes)); // throws InvalidKeySpecException
return publicKey;
}
catch(Exception e) {
throw new CryptographyException(e);
}
}
/**
* If the X509 certificate has a Subject Alternative Name which is an IP
* Address, then it will be returned as a String. If there is more than one,
* only the first is returned. If there are none, null will be
* returned.
*
* The X509Certificate method getSubjectAlternativeNames() returns a list of
* (type,value) pairs. The types are shown in this extract of the JavaDoc:
* *
GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1]
* IA5String, dNSName [2] IA5String, x400Address [3] ORAddress,
* directoryName [4] Name, ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER}
*
*
* The IP Address is type 7
*
* @param certificate
* @return
*/
public static String ipAddressAlternativeName(X509Certificate certificate) {
try {
Collection<List<?>> wtf = certificate.getSubjectAlternativeNames();
if (wtf == null) {
return null;
} // when certificate does not have the alternative names extension at all
Iterator<List<?>> it1 = wtf.iterator();
while (it1.hasNext()) {
List<?> list = it1.next();
if (list.size() == 2 && list.get(0) != null && list.get(0) instanceof Integer) {
Integer type = (Integer) list.get(0);
if (type == GeneralNameInterface.NAME_IP && list.get(1) != null && list.get(1) instanceof String) {
String ipAddress = (String) list.get(1);
return ipAddress;
}
}
}
} catch (CertificateParsingException e) {
log.error("Cannot extract Subject Alternative Name IP Address from X509 Certificate", e);
}
return null;
}
/**
* Currently only retrieves IP Address and DNS alternative names.
* @param certificate
* @return set of alternative names, or empty set if none are found
*/
public static Set<String> alternativeNames(X509Certificate certificate) {
try {
Collection<List<?>> wtf = certificate.getSubjectAlternativeNames();
if (wtf == null) { // when certificate does not have the alternative names extension at all
return Collections.EMPTY_SET;
}
HashSet<String> ipNames = new HashSet<String>();
Iterator<List<?>> it1 = wtf.iterator();
while (it1.hasNext()) {
List<?> list = it1.next();
if (list.size() == 2 && list.get(0) != null && list.get(0) instanceof Integer) {
Integer type = (Integer) list.get(0);
if (type == GeneralNameInterface.NAME_IP && list.get(1) != null && list.get(1) instanceof String) {
String ipAddress = (String) list.get(1);
ipNames.add(ipAddress);
}
if (type == GeneralNameInterface.NAME_DNS && list.get(1) != null && list.get(1) instanceof String) {
String dnsAddress = (String) list.get(1);
ipNames.add(dnsAddress);
}
}
}
return ipNames;
} catch (CertificateParsingException e) {
log.error("Cannot extract Subject Alternative Names from X509 Certificate", e);
return Collections.EMPTY_SET;
}
}
/**
* Two ways to tell if a certificate is a CA:
* 1) getBasicConstraints() > -1 means it's a CA and the value is the max certificate path length
* 2) getKeyUsage() != null && getKeyUsage()[5] == true means it has the "CA" key usage flag set
* Currently we only check the basic constraints
* @param certificate
* @return
*/
public static boolean isCA(X509Certificate certificate) {
return certificate.getBasicConstraints() > -1; // -1 indicates not a CA cert, 0 and above indicates CA cert
}
}
| bsd-3-clause |
wix/petri | wix-petri-core/src/it/java/com/wixpress/petri/LogDriver.java | 1433 | package com.wixpress.petri;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.rolling.RollingFileAppender;
import org.apache.commons.io.FileUtils;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: sagyr
* Date: 8/6/14
* Time: 2:34 PM
* To change this template use File | Settings | File Templates.
*/
public class LogDriver {
private final File logFile;
public LogDriver() {
this.logFile = new File(getLogFileFullName());
}
private String getLogFileFullName() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
RollingFileAppender appender = (RollingFileAppender) context.getLogger("experimentsLog").getAppender("EXPERIMENTS_APPENDER");
return appender.getFile();
}
public String lastLongEntry() throws IOException {
List<String> logLines = logEntries();
return logLines.get(logLines.size() - 1);
}
public List<String> logEntries() throws IOException {
return FileUtils.readLines(logFile);
}
/**
* Call this @Before each test
*/
public void cleanup() throws FileNotFoundException {
try (PrintWriter printWriter = new PrintWriter(logFile)) {
printWriter.print("");
}
}
}
| bsd-3-clause |
mikekab/RESOLVE | src/main/java/edu/clemson/cs/r2jt/rewriteprover/MainProofFitnessFunction.java | 2942 | /**
* MainProofFitnessFunction.java
* ---------------------------------
* Copyright (c) 2016
* RESOLVE Software Research Group
* School of Computing
* Clemson University
* All rights reserved.
* ---------------------------------
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package edu.clemson.cs.r2jt.rewriteprover;
import edu.clemson.cs.r2jt.rewriteprover.absyn.PExp;
import edu.clemson.cs.r2jt.rewriteprover.model.Conjunct;
import edu.clemson.cs.r2jt.rewriteprover.model.PerVCProverModel;
import edu.clemson.cs.r2jt.rewriteprover.transformations.StrengthenConsequent;
import edu.clemson.cs.r2jt.rewriteprover.transformations.SubstituteInPlaceInConsequent;
import edu.clemson.cs.r2jt.rewriteprover.transformations.Transformation;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author hamptos
*/
public class MainProofFitnessFunction
implements
FitnessFunction<Transformation> {
private Set<String> myConsequentVariableNames = new HashSet<String>();
public MainProofFitnessFunction(PerVCProverModel model) {
for (Conjunct c : model.getConsequentList()) {
myConsequentVariableNames
.addAll(c.getExpression().getSymbolNames());
}
}
@Override
public double calculateFitness(Transformation t) {
double result = 0;
if (t.couldAffectAntecedent()
|| (!(t instanceof StrengthenConsequent) && t
.introducesQuantifiedVariables())) {
result = -1;
}
else if (AutomatedProver.H_DETECT_IDENTITY_EXPANSION
&& t instanceof SubstituteInPlaceInConsequent) {
SubstituteInPlaceInConsequent tAsSIPIC =
(SubstituteInPlaceInConsequent) t;
PExp pattern = tAsSIPIC.getPattern();
PExp replacement = tAsSIPIC.getReplacement();
if (pattern.getFunctionApplications().isEmpty()
&& pattern.getQuantifiedVariables().size() == 1
&& replacement.getQuantifiedVariables().contains(
pattern.getQuantifiedVariables().iterator().next())) {
result = -1;
}
}
if (result == 0 && AutomatedProver.H_BEST_FIRST_CONSEQUENT_EXPLORATION) {
Set<String> introduced =
new HashSet<String>(t.getReplacementSymbolNames());
introduced.removeAll(myConsequentVariableNames);
double simplificationFactor =
unitAtan(t.functionApplicationCountDelta() * -1);
result =
Math.min(Math.pow(0.5, introduced.size())
* simplificationFactor, 1.0);
}
return result;
}
private double unitAtan(int i) {
return (Math.atan(i) * 2 / Math.PI + 1) / 2;
}
}
| bsd-3-clause |
TATRC/KMR2 | Services/Common/XDSCommonLib/src/main/java/gov/hhs/fha/nhinc/docmgr/NHINQueryProcessor.java | 31864 | /*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
* Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. 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 NHIN Connect 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.
*
* END OF TERMS AND CONDITIONS
*/
package gov.hhs.fha.nhinc.docmgr;
import com.thoughtworks.xstream.XStream;
import gov.hhs.fha.nhinc.account.util.PropertyAccessor;
import gov.hhs.fha.nhinc.docmgr.msgobject.NHINRetrieveMessage;
import gov.hhs.fha.nhinc.docmgr.msgobject.NHINQueryMessage;
import gov.hhs.fha.nhinc.common.docmgr.DocDownloadInfoType;
import gov.hhs.fha.nhinc.common.docmgr.DocumentInfoType;
import gov.hhs.fha.nhinc.common.docmgr.NameValuesPair;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.CeType;
import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.PersonNameType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthnStatementType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceAssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementType;
import gov.hhs.fha.nhinc.common.nhinccommon.SamlAuthzDecisionStatementEvidenceConditionsType;
import gov.hhs.fha.nhinc.common.nhinccommon.UserType;
import gov.hhs.fha.nhinc.common.nhinccommonentity.RespondingGatewayCrossGatewayQueryRequestType;
import gov.hhs.fha.nhinc.service.ServiceUtil;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.soap.MTOMFeature;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest;
import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryResponse;
import oasis.names.tc.ebxml_regrep.xsd.query._3.ResponseOptionType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.AdhocQueryType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ClassificationType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ExtrinsicObjectType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.IdentifiableType;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.SlotType1;
import oasis.names.tc.ebxml_regrep.xsd.rim._3.ValueListType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Handles the initial NHIN Query. Steps:
* <ol>
* <li>Perform the gateway query
* <li>Checks response for documents that haven't already been downloaded
* <li>Starts the download process of new documents
* <li>Informs requestor that query is done.
* </ol>
* @author cmatser
*/
public class NHINQueryProcessor {
/** Assertion values (where to set?). */
public static final String SIGNATURE_DATE = "01/01/2009 01:22:30";
public static final String EXPIRATION_DATE = "01/01/2014 01:22:30";
public static final String ROLE_NAME = "Physician";
public static final String ROLE_CODE = "5555555";
public static final String ROLE_CODE_SYSTEM = "2.16.840.1.113883.6.96";
public static final String ROLE_CODE_SYSTEM_NAME = "SNOMED_CT";
public static final String ROLE_CODE_SYSTEM_VERSION = "1.0";
public static final String USER_DOD_EXTENSION = "*DoD";
public static final String DOD_ROLE_NAME = "P";
public static final String DOD_ROLE_CODE = "P";
public static final String DOD_ROLE_CODE_SYSTEM = "30";
public static final String DOD_ROLE_CODE_SYSTEM_NAME = "nameType";
public static final String DOD_ROLE_CODE_SYSTEM_VERSION = "1.0";
public static final String PURPOSE_OF_USE_ROLE_NAME = "TREATMENT";
public static final String PURPOSE_OF_USE_ROLE_CODE = "TREATMENT";
public static final String PURPOSE_OF_USE_ROLE_CODE_SYSTEM = "2.16.840.1.113883.3.18.71.1";
public static final String PURPOSE_OF_USE_ROLE_CODE_SYSTEM_NAME = "nhin-purpose";
public static final String PURPOSE_OF_USE_ROLE_CODE_SYSTEM_VERSION = "1.0";
public static final String CLAIM_FORM_REF = "DoD-Ref-Claim";
public static final String CLAIM_FORM_STRING = "blahblah";
/** Date precision. */
public static final int XDS_DATE_QUERY_FROM_PRECISION = 8;
public static final int XDS_DATE_QUERY_TO_PRECISION = 14;
public static final int ASSERTION_DOB_PRECISION = 12;
/** XDS spec does not use timezone (but CONNECT does) */
public static final String XDS_DATE_FORMAT_FULL = "yyyyMMddHHmmssZ";
/** Search criteria. */
public static final int NUMBER_OF_YEARS = 5;
/** Data Source name. */
public static final String DATA_SOURCE = "NHIN Documents";
/** Item names for name value pairs. */
public static final String ITEM_DOCUMENT_NAME = "Name";
public static final String ITEM_MIME_TYPE = "MIME Type";
public static final String ITEM_DOCUMENT_SIZE = "Size";
public static final String ITEM_INSTITUTION = "Author Institution";
public static final String ITEM_CREATION_TIME = "Creation Time";
public static final String ITEM_LANGUAGE_CODE = "Language Code";
public static final String ITEM_SERVICE_START = "Service Start Time";
public static final String ITEM_SERVICE_STOP = "Service Stop Time";
public static final String ITEM_PATIENT_ADDRESS = "Patient Address";
public static final String ITEM_PATIENT_GENDER = "Patient Gender";
public static final String ITEM_PATIENT_DOB = "Patient DOB";
public static final String ITEM_REPOSITORY_ID = "Repository ID";
public static final String ITEM_DOCUMENT_UNIQUE_ID = "Document Unique ID";
public static final String ITEM_HOME_COMMUNITY_ID = "Home Community ID";
/** XDS ids */
public static final String XDS_FINDDOC_QUERY = "urn:uuid:14d4debf-8f97-4251-9a74-a90016b0af0d";
public static final String XDS_GETDOC_QUERY = "urn:uuid:5c4f972b-d56b-40ac-a5fc-c8ca9b40b9d4";
public static final String XDS_QUERY_PATIENT_ID = "$XDSDocumentEntryPatientId";
public static final String XDS_QUERY_ENTRY_STATUS = "$XDSDocumentEntryStatus";
public static final String XDS_QUERY_APPROVED_STATUS = "('urn:oasis:names:tc:ebxml-regrep:StatusType:Approved')";
public static final String XDS_QUERY_DOCUMENT_ID = "$XDSDocumentEntryUniqueId";
public static final String XDS_RETURN_TYPE = "LeafClass";
public static final String XDS_CUSTOM_METADATA_PREFIX = "urn:";
public static final String XDS_CREATION_TIME = "creationTime";
public static final String XDS_SERVICE_START = "serviceStartTime";
public static final String XDS_SERVICE_STOP = "serviceStopTime";
public static final String XDS_LANGUAGE_CODE = "languageCode";
public static final String XDS_PATIENT_INFO = "sourcePatientInfo";
public static final String XDS_DOC_SIZE = "size";
public static final String XDS_REPOSITORY_ID = "repositoryUniqueId";
public static final String XDS_PATIENT_NAME = "PID-5|";
public static final String XDS_PATIENT_GENDER = "PID-8|";
public static final String XDS_PATIENT_DOB = "PID-7|";
public static final String XDS_PATIENT_ADDRESS = "PID-11|";
public static final String XDS_DOC_ID = "XDSDocumentEntry.uniqueId";
public static final String XDS_CLASS_AUTHOR = "urn:uuid:93606bcf-9494-43ec-9b4e-a7748d1a838d";
public static final String XDS_SLOT_AUTHOR = "authorPerson";
public static final String XDS_SLOT_INSTITUTION = "authorInstitution";
/** Logging. */
private static Log log = LogFactory.getLog(NHINQueryProcessor.class);
public NHINQueryProcessor() { }
public void handleQueryMessage(String ticket, NHINQueryMessage msg) {
try { // Call Web Service Operation
List<WebServiceFeature> wsfeatures = new ArrayList<WebServiceFeature>();
wsfeatures.add(new MTOMFeature(0));
WebServiceFeature[] wsfeaturearray = wsfeatures.toArray(new WebServiceFeature[0]);
javax.xml.ws.Service myService = new ServiceUtil().createService(
"EntityDocQuery.wsdl",
"urn:gov:hhs:fha:nhinc:entitydocquery",
"EntityDocQuery");
gov.hhs.fha.nhinc.entitydocquery.EntityDocQueryPortType port = myService.getPort(
new javax.xml.namespace.QName("urn:gov:hhs:fha:nhinc:entitydocquery", "EntityDocQueryPortSoap"),
gov.hhs.fha.nhinc.entitydocquery.EntityDocQueryPortType.class);
((javax.xml.ws.BindingProvider)port).getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
PropertyAccessor.getProperty(
DocumentManagerImpl.REPOSITORY_PROPERTY_FILE,
DocumentManagerImpl.NHINDOCQUERY_ENDPOINT_PROP));
RespondingGatewayCrossGatewayQueryRequestType gatewayQueryRequest = new RespondingGatewayCrossGatewayQueryRequestType();
AdhocQueryRequest adhocQueryRequest = createQuery(msg);
AssertionType assertion = createAssertion(msg);
gatewayQueryRequest.setAdhocQueryRequest(adhocQueryRequest);
gatewayQueryRequest.setAssertion(assertion);
AdhocQueryResponse result = port.respondingGatewayCrossGatewayQuery(gatewayQueryRequest);
//Compare gateway results with local repository
List<NewDocInfo> newDocs = findNewDocuments(result, adhocQueryRequest);
//Start async retrieve of new documents
for (NewDocInfo newDoc : newDocs) {
startRetrieve(newDoc, assertion,
msg.getPatientUnitNumber(),
msg.getHomeCommunityId(),
PropertyAccessor.getProperty(
DocumentManagerImpl.REPOSITORY_PROPERTY_FILE,
DocumentManagerImpl.INBOUND_DOCUMENT_REPOSITORY_ID_PROP),
new DocumentManagerImpl().generateUniqueId(null).getUniqueId(),
msg.getCallbackURL());
}
//Notify caller of status
doCallback(true, "Success", ticket, msg.getCallbackURL(), newDocs);
} catch (Exception e) {
//Handle custom exceptions here
log.error("Error handling NHIN query message.", e);
//Notify caller of status
doCallback(false, e.getMessage(), ticket, msg.getCallbackURL(), new LinkedList<NewDocInfo>());
}
}
/**
* Compare the results from the gateway query to determine which documents
* are not in the local store.
*
* @param gatewayResult
* @param adhocQueryRequest
* @return
*/
private List<NewDocInfo> findNewDocuments(
AdhocQueryResponse gatewayResult,
AdhocQueryRequest adhocQueryRequest) {
List<NewDocInfo> newDocs = new LinkedList<NewDocInfo>();
//if no gateway documents, return
if (gatewayResult.getRegistryObjectList() == null) {
log.debug ("NHIN Query done, no objects returned.");
return newDocs;
}
AdhocQueryResponse localResult = getCurrentDocuments(adhocQueryRequest);
//Loop through gateway results and check if they are there locally
List<JAXBElement<? extends IdentifiableType>> gatewayObjects = gatewayResult.getRegistryObjectList().getIdentifiable();
for (JAXBElement<? extends IdentifiableType> gatewayObj : gatewayObjects) {
IdentifiableType gatewayDoc = gatewayObj.getValue();
String homeId = "";
String reposId = "";
String docId = "";
String origHomeId = null;
String origReposId = null;
String origDocId = null;
boolean found = false;
if (gatewayDoc instanceof ExtrinsicObjectType) {
ExtrinsicObjectType extrinsic = (ExtrinsicObjectType) gatewayDoc;
homeId = extrinsic.getHome();
for (SlotType1 returnSlot : extrinsic.getSlot()) {
if ("repositoryUniqueId".equals(returnSlot.getName())) {
reposId = returnSlot.getValueList().getValue().get(0);
}
}
for (ExternalIdentifierType returnId : extrinsic.getExternalIdentifier()) {
if ("XDSDocumentEntry.uniqueId".equals(returnId.getName().getLocalizedString().get(0).getValue())) {
docId = returnId.getValue();
}
}
} //if extract gateway values
//Loop through current results and check if the gateway doc already exists
List<JAXBElement<? extends IdentifiableType>> localObjects = localResult.getRegistryObjectList().getIdentifiable();
for (JAXBElement<? extends IdentifiableType> localObj: localObjects) {
IdentifiableType localDoc = localObj.getValue();
if (localDoc instanceof ExtrinsicObjectType) {
ExtrinsicObjectType extrinsic = (ExtrinsicObjectType) localDoc;
for (SlotType1 returnSlot : extrinsic.getSlot()) {
if ("urn:gov:hhs:fha:nhinc:xds:OrigHomeCommunityId".equals(returnSlot.getName())) {
origHomeId = returnSlot.getValueList().getValue().get(0);
}
if ("urn:gov:hhs:fha:nhinc:xds:OrigRepositoryUniqueId".equals(returnSlot.getName())) {
origReposId = returnSlot.getValueList().getValue().get(0);
}
if ("urn:gov:hhs:fha:nhinc:xds:OrigDocumentUniqueId".equals(returnSlot.getName())) {
origDocId = returnSlot.getValueList().getValue().get(0);
}
} //for slot loop
} //if extract local values
//Check if gateway document matches local document
if (homeId.equals(origHomeId)
&& reposId.equals(origReposId)
&& docId.equals(origDocId)) {
found = true;
log.debug("NHIN query returned existing document: " + docId
+ ", in repository: " + reposId);
break;
}
} //for loop through local results
//If the document doesn't exist locally, save the info
if (!found) {
NewDocInfo newDoc = new NewDocInfo();
newDoc.doc = new DocDownloadInfoType();
newDoc.doc.setDocInfo(parseMetadata((ExtrinsicObjectType) gatewayDoc));
newDoc.extrinsic = (ExtrinsicObjectType) gatewayDoc;
newDocs.add(newDoc);
}
} //for loop through gateway results
return newDocs;
}
/**
* Find the existing documents in the local store.
*
* @param query
*/
private AdhocQueryResponse getCurrentDocuments(AdhocQueryRequest query) {
return new DocumentManagerImpl().documentManagerQueryForDocument(query);
}
/**
* Kickoff the async retrieval of new document.
*
* @param newDoc
*/
private void startRetrieve(
NewDocInfo newDoc,
AssertionType assertion,
String localPatientId,
String localHomeCommunityId,
String localRepositoryId,
String localDocumentUniqueId,
String callbackURL) {
//Create message
NHINRetrieveMessage nhinMessage = new NHINRetrieveMessage();
nhinMessage.setCallbackURL(callbackURL);
//Serialize un-serializable objects to xml
XStream xstream = new XStream();
xstream.alias("DocumentInfoType", DocumentInfoType.class);
xstream.alias("ExtrinsicObjectType", ExtrinsicObjectType.class);
xstream.alias("AssertionType", AssertionType.class);
nhinMessage.setDocumentInfoXML(xstream.toXML(newDoc.doc.getDocInfo()));
nhinMessage.setExtrinsicXML(xstream.toXML(newDoc.extrinsic));
nhinMessage.setAssertionXML(xstream.toXML(assertion));
//Set remote values
nhinMessage.setRemoteDocumentUniqueId(newDoc.doc.getDocInfo().getItemId());
for (NameValuesPair pair : newDoc.doc.getDocInfo().getItemValues()) {
if (ITEM_HOME_COMMUNITY_ID.equals(pair.getName())) {
nhinMessage.setRemoteHomeCommunityId(pair.getValues().get(0));
}
if (ITEM_REPOSITORY_ID.equals(pair.getName())) {
nhinMessage.setRemoteRepositoryId(pair.getValues().get(0));
}
}
//Set local values
nhinMessage.setLocalHomeCommunityId(localHomeCommunityId);
nhinMessage.setLocalRepositoryId(localRepositoryId);
nhinMessage.setLocalDocumentUniqueId(localDocumentUniqueId);
nhinMessage.setLocalPatientId(localPatientId);
//Start in background
String[] startResult = DocumentManagerImpl.startBackgroundJob(nhinMessage);
//Set response info
newDoc.doc.setTicket(startResult[0]);
}
/**
* Notify requestor of the completion of the gateway query.
*
* @param success
* @param detail
* @param ticket
* @param requester
* @param newDocs
*/
private void doCallback(boolean success, String detail, String ticket, String requester, List<NewDocInfo> newDocs) {
try { // Call Web Service Operation
gov.hhs.fha.nhinc.docmgrrequester.DocMgrRequester service = new gov.hhs.fha.nhinc.docmgrrequester.DocMgrRequester();
gov.hhs.fha.nhinc.docmgrrequester.DocMgrRequesterPortType port = service.getDocMgrRequesterPortSoap11();
((javax.xml.ws.BindingProvider) port).getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
requester);
//Initialize WS operation arguments here
gov.hhs.fha.nhinc.common.docmgr.QueryDoneRequestType queryDoneRequest = new gov.hhs.fha.nhinc.common.docmgr.QueryDoneRequestType();
queryDoneRequest.setTicket(ticket);
queryDoneRequest.setSuccess(success);
queryDoneRequest.setDetail(detail);
for (NewDocInfo newDoc : newDocs) {
queryDoneRequest.getNewDocs().add(newDoc.doc);
}
//Process result here
gov.hhs.fha.nhinc.common.docmgr.QueryDoneResponseType result = port.queryDone(queryDoneRequest);
} catch (Exception e) {
//Handle custom exceptions here
log.error("Error notifying requestor ticket complete: " + ticket, e);
}
}
/**
* Create the nhin query for inbound repository based on the passed parameters and some fixed values.
*
* @param msg
* @return
*/
private AdhocQueryRequest createQuery(NHINQueryMessage msg) {
AdhocQueryRequest retVal = new AdhocQueryRequest();
retVal.setFederated(false);
retVal.setStartIndex(BigInteger.valueOf(0));
retVal.setMaxResults(BigInteger.valueOf(-1));
ResponseOptionType resp = new ResponseOptionType();
resp.setReturnComposedObjects(true);
resp.setReturnType("LeafClass");
retVal.setResponseOption(resp);
AdhocQueryType queryType = new AdhocQueryType();
queryType.setId("urn:uuid:14d4debf-8f97-4251-9a74-a90016b0af0d");
String inboundRepos = "";
try {
inboundRepos = PropertyAccessor.getProperty(
DocumentManagerImpl.REPOSITORY_PROPERTY_FILE,
DocumentManagerImpl.INBOUND_DOCUMENT_REPOSITORY_ID_PROP);
}
catch (Exception e) {
//ignore
}
addSlot(queryType, "$XDSRepositoryUniqueId",
new String[] { inboundRepos } );
addSlot(queryType, "$XDSDocumentEntryPatientId",
new String[] { msg.getPatientUnitNumber() + "^^^&" + msg.getHomeCommunityId() + "&ISO" } );
addSlot(queryType, "$XDSDocumentEntryStatus",
new String[] { "('urn:oasis:names:tc:ebxml-regrep:StatusType:Approved')" });
//Set Creation From Date
Calendar cal = new GregorianCalendar();
cal.add(Calendar.YEAR, -NUMBER_OF_YEARS);
addSlot(queryType, "$XDSDocumentEntryCreationTimeFrom",
new String[] { formatXDSDate(cal.getTime(), XDS_DATE_QUERY_FROM_PRECISION) });
// Omit Creation To Date for most current
//addSlot(queryType, "$XDSDocumentEntryCreationTimeTo",
// new String[] { XDSDateQueryToFormat.format(new Date()) });
retVal.setAdhocQuery(queryType);
return retVal;
}
/**
* Create gateway assertion object based on the passed parameters and some fixed values.
*
* @param msg
* @return
*/
private AssertionType createAssertion(NHINQueryMessage msg) {
AssertionType assertion = new AssertionType();
assertion.setDateOfBirth(formatXDSDate(msg.getPatientDOB(), ASSERTION_DOB_PRECISION));
//SAMLAuthStatementType is new for CONNECT v3.1
SamlAuthnStatementType samlAuthnStatement = new SamlAuthnStatementType();
SamlAuthzDecisionStatementType samlAuthzDecisionStatement = new SamlAuthzDecisionStatementType();
SamlAuthzDecisionStatementEvidenceType samlAuthzDecisionStatementEvidence = new SamlAuthzDecisionStatementEvidenceType();
SamlAuthzDecisionStatementEvidenceAssertionType samlAuthzDecisionStatementAssertion = new SamlAuthzDecisionStatementEvidenceAssertionType();
SamlAuthzDecisionStatementEvidenceConditionsType samlAuthzDecisionStatementEvidenceConditions = new SamlAuthzDecisionStatementEvidenceConditionsType();
samlAuthzDecisionStatementEvidenceConditions.setNotOnOrAfter(EXPIRATION_DATE);
samlAuthzDecisionStatementEvidenceConditions.setNotBefore(SIGNATURE_DATE);
samlAuthzDecisionStatementAssertion.setConditions(samlAuthzDecisionStatementEvidenceConditions);
samlAuthzDecisionStatementAssertion.setAccessConsentPolicy(CLAIM_FORM_REF);
samlAuthzDecisionStatementEvidence.setAssertion(samlAuthzDecisionStatementAssertion);
samlAuthzDecisionStatement.setEvidence(samlAuthzDecisionStatementEvidence);
assertion.setSamlAuthzDecisionStatement(samlAuthzDecisionStatement);
assertion.setSamlAuthnStatement(samlAuthnStatement);
PersonNameType pName = new PersonNameType();
pName.setFamilyName(msg.getPatientLastName());
pName.setGivenName(msg.getPatientFirstName());
pName.setSecondNameOrInitials(msg.getPatientMiddleName());
assertion.setPersonName(pName);
HomeCommunityType hc = new HomeCommunityType();
hc.setDescription(msg.getHomeCommunityDesc());
hc.setHomeCommunityId(msg.getHomeCommunityId());
hc.setName(msg.getHomeCommunityName());
UserType muser = new UserType();
CeType roleType = new CeType();
roleType.setCode(ROLE_CODE);
roleType.setCodeSystem(ROLE_CODE_SYSTEM);
roleType.setCodeSystemName(ROLE_CODE_SYSTEM_NAME);
roleType.setCodeSystemVersion(ROLE_CODE_SYSTEM_VERSION);
roleType.setDisplayName(ROLE_NAME);
roleType.setOriginalText(ROLE_NAME);
muser.setOrg(hc);
muser.setRoleCoded(roleType);
//VA DoD Requirement
String uPlusDoD = msg.getUsername() + USER_DOD_EXTENSION;
muser.setUserName(uPlusDoD);
PersonNameType uName = new PersonNameType();
CeType nType = new CeType();
nType.setCode(DOD_ROLE_CODE);
nType.setCodeSystem(DOD_ROLE_CODE_SYSTEM);
nType.setCodeSystemName(DOD_ROLE_CODE_SYSTEM_NAME);
nType.setCodeSystemVersion(DOD_ROLE_CODE_SYSTEM_VERSION);
nType.setDisplayName(DOD_ROLE_NAME);
nType.setOriginalText(DOD_ROLE_NAME);
uName.setNameType(nType);
uName.setFamilyName(msg.getProviderLastName());
uName.setGivenName(msg.getProviderFirstName());
uName.setSecondNameOrInitials(msg.getProviderMiddleName());
muser.setPersonName(uName);
assertion.setUserInfo(muser);
assertion.setHomeCommunity(hc);
CeType pouType = new CeType();
pouType.setCode(PURPOSE_OF_USE_ROLE_CODE);
pouType.setCodeSystem(PURPOSE_OF_USE_ROLE_CODE_SYSTEM);
pouType.setCodeSystemName(PURPOSE_OF_USE_ROLE_CODE_SYSTEM_NAME);
pouType.setCodeSystemVersion(PURPOSE_OF_USE_ROLE_CODE_SYSTEM_VERSION);
pouType.setDisplayName(PURPOSE_OF_USE_ROLE_NAME);
pouType.setOriginalText(PURPOSE_OF_USE_ROLE_NAME);
assertion.setPurposeOfDisclosureCoded(pouType);
return assertion;
}
/**
* Add slot to query object.
*
* @param registry - submission object
* @param name - slot name
* @param values - slot values
*/
private static void addSlot(AdhocQueryType query,
String name, String [] values) {
SlotType1 slot = new SlotType1();
slot.setName(name);
ValueListType valList = new ValueListType();
for (String value : values) {
valList.getValue().add(value);
}
slot.setValueList(valList);
query.getSlot().add(slot);
}
/**
* Parse metadata query result for summary return.
*
* @param result summary info
* @return
*/
private DocumentInfoType parseMetadata(ExtrinsicObjectType docMeta) {
GregorianCalendar cal = new GregorianCalendar();
//Poplulate summary data object
DocumentInfoType summaryData = new DocumentInfoType();
summaryData.setDataSource(DATA_SOURCE);
summaryData.setDescription(docMeta.getDescription().getLocalizedString().get(0).getValue());
addNameValue(summaryData.getItemValues(), ITEM_DOCUMENT_NAME, docMeta.getName().getLocalizedString().get(0).getValue());
addNameValue(summaryData.getItemValues(), ITEM_MIME_TYPE, docMeta.getMimeType());
addNameValue(summaryData.getItemValues(), ITEM_HOME_COMMUNITY_ID, docMeta.getHome());
for (SlotType1 metaSlot : docMeta.getSlot()) {
if (XDS_CREATION_TIME.equals(metaSlot.getName())) {
try {
cal.setTime(parseXDSDate(metaSlot.getValueList().getValue().get(0)));
summaryData.setDateCreated(
DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
}
catch (Exception pe) {
String msg = "Error parsing: " + XDS_CREATION_TIME;
log.error(msg, pe);
}
}
if (XDS_PATIENT_INFO.equals(metaSlot.getName())) {
//Find patient name
for (String ptVal : metaSlot.getValueList().getValue()) {
//Patient name is PID-5
if (ptVal.startsWith(XDS_PATIENT_NAME)) {
summaryData.setPatient(ptVal.substring(XDS_PATIENT_NAME.length()));
}
}
}
if (XDS_DOC_SIZE.equals(metaSlot.getName())) {
addNameValue(summaryData.getItemValues(), ITEM_DOCUMENT_SIZE, metaSlot.getValueList().getValue().get(0));
}
if (XDS_REPOSITORY_ID.equals(metaSlot.getName())) {
addNameValue(summaryData.getItemValues(), ITEM_REPOSITORY_ID, metaSlot.getValueList().getValue().get(0));
}
} //end for meta slots
for (ExternalIdentifierType identifier : docMeta.getExternalIdentifier()) {
if (XDS_DOC_ID.equals(identifier.getName().getLocalizedString().get(0).getValue())) {
summaryData.setItemId(identifier.getValue());
}
}
for (ClassificationType classification : docMeta.getClassification()) {
if (XDS_CLASS_AUTHOR.equals(classification.getClassificationScheme())) {
for (SlotType1 authorSlot : classification.getSlot()) {
if (XDS_SLOT_AUTHOR.equals(authorSlot.getName())) {
summaryData.setAuthor(authorSlot.getValueList().getValue().get(0));
}
}
for (SlotType1 authorSlot : classification.getSlot()) {
if (XDS_SLOT_INSTITUTION.equals(authorSlot.getName())) {
addNameValue(summaryData.getItemValues(), ITEM_INSTITUTION, authorSlot.getValueList().getValue().get(0));
}
}
}
}
return summaryData;
}
/**
* Add name/value pair to response.
*
* @param pairList
* @param name
* @param value
*/
private void addNameValue(List<NameValuesPair> pairList, String name, String value) {
NameValuesPair nameVal = new NameValuesPair();
nameVal.setName(name);
nameVal.getValues().add(value);
pairList.add(nameVal);
return;
}
/**
* Parses XDS date using scaling precision (as according to XDS Spec).
*
* @param dateStr
* @return
* @throws java.text.ParseException
*/
private Date parseXDSDate(String dateStr)
throws ParseException {
DateFormat xdFormat;
if (dateStr.length() >= XDS_DATE_FORMAT_FULL.length()) {
xdFormat = new SimpleDateFormat(XDS_DATE_FORMAT_FULL);
}
else {
xdFormat = new SimpleDateFormat(XDS_DATE_FORMAT_FULL.substring(0, dateStr.length()));
}
return xdFormat.parse(dateStr);
}
/**
* Format XDS date using scaling precision (as according to XDS Spec).
*
* @param date
* @param precision
* @return
*/
private String formatXDSDate(Date date, int precision) {
DateFormat xdsFormat = new SimpleDateFormat(XDS_DATE_FORMAT_FULL.substring(0, precision));
return xdsFormat.format(date);
}
/**
* Temporary object used for passing data in this class.
*/
class NewDocInfo {
DocDownloadInfoType doc;
ExtrinsicObjectType extrinsic;
}
}
| bsd-3-clause |
Fivium/DMDA | src/main/java/uk/co/fivium/dmda/emailmessages/InvalidRecipientException.java | 103 | package uk.co.fivium.dmda.emailmessages;
public class InvalidRecipientException
extends Exception {
}
| bsd-3-clause |
detruby/WkwFrcRobot2013 | src/us/oh/k12/wkw/robot/command/CameraFindTargetCmd.java | 1006 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2012 Worthington Kilbourne Robot Club. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package us.oh.k12.wkw.robot.command;
/**
* Find the target from the camera.
*/
public class CameraFindTargetCmd extends CommandWithTimeout {
public CameraFindTargetCmd() {
this(10.0);
}
public CameraFindTargetCmd(final double pTimeout) {
super("CameraFindTargetCmd", pTimeout);
// this.requires(this.getCameraSystem());
}
protected void execute() {
try {
this.debug("execute()", "Called.");
// this.getCameraSystem().findTarget();
} catch (Exception anEx) {
this.error("execute()", anEx);
}
}
protected boolean isFinished() {
return true;
}
}
| bsd-3-clause |
davidi2/mopar | src/net/scapeemulator/game/model/player/Item.java | 1490 | package net.scapeemulator.game.model.player;
import net.scapeemulator.cache.def.ItemDefinition;
import net.scapeemulator.game.model.definition.ItemDefinitions;
public final class Item {
private final int id, amount;
public Item(int id) {
this(id, 1);
}
public Item(int id, int amount) {
if (amount < 0)
throw new IllegalArgumentException();
this.id = id;
this.amount = amount;
}
public Item add(Item item) {
if(item.getId() != id) {
throw new IllegalStateException();
}
int newAmount = item.getAmount() + amount;
return new Item(id, newAmount);
}
public int getId() {
return id;
}
public int getAmount() {
return amount;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + amount;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Item other = (Item) obj;
if (amount != other.amount)
return false;
if (id != other.id)
return false;
return true;
}
@Override
public String toString() {
return Item.class.getSimpleName() + " [id=" + id + ", amount=" + amount + "]";
}
public ItemDefinition getDefinition() {
return ItemDefinitions.forId(id);
}
public EquipmentDefinition getEquipmentDefinition() {
return EquipmentDefinition.forId(id);
}
}
| isc |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/MarketOperations/impl/SecurityConstraintsClearingImpl.java | 7231 | /**
*/
package gluemodel.CIM.IEC61970.Informative.MarketOperations.impl;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.SecurityConstraintsClearing;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Security Constraints Clearing</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link gluemodel.CIM.IEC61970.Informative.MarketOperations.impl.SecurityConstraintsClearingImpl#getMwLimit <em>Mw Limit</em>}</li>
* <li>{@link gluemodel.CIM.IEC61970.Informative.MarketOperations.impl.SecurityConstraintsClearingImpl#getMwFlow <em>Mw Flow</em>}</li>
* <li>{@link gluemodel.CIM.IEC61970.Informative.MarketOperations.impl.SecurityConstraintsClearingImpl#getShadowPrice <em>Shadow Price</em>}</li>
* </ul>
*
* @generated
*/
public class SecurityConstraintsClearingImpl extends MarketFactorsImpl implements SecurityConstraintsClearing {
/**
* The default value of the '{@link #getMwLimit() <em>Mw Limit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMwLimit()
* @generated
* @ordered
*/
protected static final float MW_LIMIT_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getMwLimit() <em>Mw Limit</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMwLimit()
* @generated
* @ordered
*/
protected float mwLimit = MW_LIMIT_EDEFAULT;
/**
* The default value of the '{@link #getMwFlow() <em>Mw Flow</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMwFlow()
* @generated
* @ordered
*/
protected static final float MW_FLOW_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getMwFlow() <em>Mw Flow</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMwFlow()
* @generated
* @ordered
*/
protected float mwFlow = MW_FLOW_EDEFAULT;
/**
* The default value of the '{@link #getShadowPrice() <em>Shadow Price</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShadowPrice()
* @generated
* @ordered
*/
protected static final float SHADOW_PRICE_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getShadowPrice() <em>Shadow Price</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShadowPrice()
* @generated
* @ordered
*/
protected float shadowPrice = SHADOW_PRICE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected SecurityConstraintsClearingImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MarketOperationsPackage.Literals.SECURITY_CONSTRAINTS_CLEARING;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getMwLimit() {
return mwLimit;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMwLimit(float newMwLimit) {
float oldMwLimit = mwLimit;
mwLimit = newMwLimit;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_LIMIT, oldMwLimit, mwLimit));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getMwFlow() {
return mwFlow;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMwFlow(float newMwFlow) {
float oldMwFlow = mwFlow;
mwFlow = newMwFlow;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_FLOW, oldMwFlow, mwFlow));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getShadowPrice() {
return shadowPrice;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShadowPrice(float newShadowPrice) {
float oldShadowPrice = shadowPrice;
shadowPrice = newShadowPrice;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__SHADOW_PRICE, oldShadowPrice, shadowPrice));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_LIMIT:
return getMwLimit();
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_FLOW:
return getMwFlow();
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__SHADOW_PRICE:
return getShadowPrice();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_LIMIT:
setMwLimit((Float)newValue);
return;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_FLOW:
setMwFlow((Float)newValue);
return;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__SHADOW_PRICE:
setShadowPrice((Float)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_LIMIT:
setMwLimit(MW_LIMIT_EDEFAULT);
return;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_FLOW:
setMwFlow(MW_FLOW_EDEFAULT);
return;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__SHADOW_PRICE:
setShadowPrice(SHADOW_PRICE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_LIMIT:
return mwLimit != MW_LIMIT_EDEFAULT;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__MW_FLOW:
return mwFlow != MW_FLOW_EDEFAULT;
case MarketOperationsPackage.SECURITY_CONSTRAINTS_CLEARING__SHADOW_PRICE:
return shadowPrice != SHADOW_PRICE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (mwLimit: ");
result.append(mwLimit);
result.append(", mwFlow: ");
result.append(mwFlow);
result.append(", shadowPrice: ");
result.append(shadowPrice);
result.append(')');
return result.toString();
}
} //SecurityConstraintsClearingImpl
| mit |
Mozu/Mozu.Integrations.Quickbooks | src/main/java/com/mozu/qbintegration/model/qbmodel/allgen/SpecialItemAddRqType.java | 3982 | //
// 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.07 at 08:01:35 PM IST
//
package com.mozu.qbintegration.model.qbmodel.allgen;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SpecialItemAddRqType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SpecialItemAddRqType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}SpecialItemAdd"/>
* <element name="IncludeRetElement" maxOccurs="unbounded" minOccurs="0">
* <simpleType>
* <restriction base="{}STRTYPE">
* <maxLength value="50"/>
* </restriction>
* </simpleType>
* </element>
* </sequence>
* <attribute name="requestID" type="{}STRTYPE" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SpecialItemAddRqType", propOrder = {
"specialItemAdd",
"includeRetElement"
})
public class SpecialItemAddRqType {
@XmlElement(name = "SpecialItemAdd", required = true)
protected SpecialItemAdd specialItemAdd;
@XmlElement(name = "IncludeRetElement")
protected List<String> includeRetElement;
@XmlAttribute(name = "requestID")
protected String requestID;
/**
* Gets the value of the specialItemAdd property.
*
* @return
* possible object is
* {@link SpecialItemAdd }
*
*/
public SpecialItemAdd getSpecialItemAdd() {
return specialItemAdd;
}
/**
* Sets the value of the specialItemAdd property.
*
* @param value
* allowed object is
* {@link SpecialItemAdd }
*
*/
public void setSpecialItemAdd(SpecialItemAdd value) {
this.specialItemAdd = value;
}
/**
* Gets the value of the includeRetElement property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the includeRetElement property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getIncludeRetElement().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getIncludeRetElement() {
if (includeRetElement == null) {
includeRetElement = new ArrayList<String>();
}
return this.includeRetElement;
}
/**
* Gets the value of the requestID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRequestID() {
return requestID;
}
/**
* Sets the value of the requestID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRequestID(String value) {
this.requestID = value;
}
}
| mit |
bagage/bootstraped-multi-test-results-report | junit-reporting-handlebars/src/test/java/com/github/bogdanlivadariu/reporting/junit/builder/AllJunitReportsTest.java | 1793 | package com.github.bogdanlivadariu.reporting.junit.builder;
import static org.junit.Assert.assertEquals;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.junit.Before;
import org.junit.Test;
public class AllJunitReportsTest {
private List<String> xmlReports;
private String reportPath = this.getClass().getClassLoader().getResource("valid-report-1.xml").getPath();
private JUnitReportBuilder builder;
private AllJUnitReports reports;
@Before
public void setUp() throws FileNotFoundException, JAXBException {
xmlReports = new ArrayList<>();
xmlReports.add(reportPath);
builder = new JUnitReportBuilder(xmlReports, "out");
reports = new AllJUnitReports("title", builder.getProcessedTestSuites());
}
@Test
public void restSuitesSizeTest() throws FileNotFoundException, JAXBException {
assertEquals("reports count is not right",
reports.getAllTestSuites().size(), 1);
assertEquals(reports.getSuitesCount(), 1);
assertEquals(reports.getTotalErrors(), 0);
}
@Test
public void pageTitleTest() {
assertEquals(reports.getPageTitle(), "title");
}
@Test
public void totalErrorsTest() {
assertEquals(reports.getSuitesCount(), 1);
}
@Test
public void totalFailuresTest() {
assertEquals(reports.getTotalFailures(), 7);
}
@Test
public void totalSkippedTest() {
assertEquals(reports.getTotalSkipped(), 0);
}
@Test
public void totalTestsTest() {
assertEquals(reports.getTotalTests(), 13);
}
@Test
public void totalTimeTest() {
assertEquals(reports.getTotalTime(), "0.813");
}
}
| mit |
xiangyong/ameba | src/main/java/ameba/filter/ResponseLoggingFilter.java | 823 | package ameba.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Priority;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.WriterInterceptor;
/**
* @author icode
*/
@Singleton
@Priority(Integer.MAX_VALUE)
public class ResponseLoggingFilter extends BaseLoggingFilter implements ContainerResponseFilter, WriterInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ResponseLoggingFilter.class);
public ResponseLoggingFilter(Logger logger, boolean printEntity) {
super(logger, printEntity);
}
public ResponseLoggingFilter(Logger logger, int maxEntitySize) {
super(logger, maxEntitySize);
}
public ResponseLoggingFilter() {
this(logger, true);
}
}
| mit |
Bachelorpraktikum/DBVisualization | src/main/java/com/github/bachelorpraktikum/visualisierbar/view/MainController.java | 28798 | package com.github.bachelorpraktikum.visualisierbar.view;
import com.github.bachelorpraktikum.visualisierbar.CompositeObservableList;
import com.github.bachelorpraktikum.visualisierbar.FXCollectors;
import com.github.bachelorpraktikum.visualisierbar.Visualisierbar;
import com.github.bachelorpraktikum.visualisierbar.config.ConfigFile;
import com.github.bachelorpraktikum.visualisierbar.config.ConfigKey;
import com.github.bachelorpraktikum.visualisierbar.datasource.DataSource;
import com.github.bachelorpraktikum.visualisierbar.datasource.RestSource;
import com.github.bachelorpraktikum.visualisierbar.model.Context;
import com.github.bachelorpraktikum.visualisierbar.model.Element;
import com.github.bachelorpraktikum.visualisierbar.model.Event;
import com.github.bachelorpraktikum.visualisierbar.model.GraphObject;
import com.github.bachelorpraktikum.visualisierbar.model.Messages;
import com.github.bachelorpraktikum.visualisierbar.model.Shapeable;
import com.github.bachelorpraktikum.visualisierbar.model.train.Train;
import com.github.bachelorpraktikum.visualisierbar.view.detail.DetailsBase;
import com.github.bachelorpraktikum.visualisierbar.view.detail.DetailsController;
import com.github.bachelorpraktikum.visualisierbar.view.graph.Graph;
import com.github.bachelorpraktikum.visualisierbar.view.graph.GraphShape;
import com.github.bachelorpraktikum.visualisierbar.view.graph.adapter.ProportionalCoordinatesAdapter;
import com.github.bachelorpraktikum.visualisierbar.view.graph.adapter.SimpleCoordinatesAdapter;
import com.github.bachelorpraktikum.visualisierbar.view.legend.LegendListViewCell;
import com.github.bachelorpraktikum.visualisierbar.view.sourcechooser.SourceController;
import com.github.bachelorpraktikum.visualisierbar.view.train.TrainView;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.binding.Binding;
import javafx.beans.binding.Bindings;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableIntegerValue;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Bounds;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBase;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Shape;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;
import javafx.util.StringConverter;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class MainController {
@FXML
private AnchorPane detail;
@FXML
private ToggleButton eventTraversal;
@FXML
private ListView<GraphObject> elementList;
@FXML
private CheckBox elementFilter;
@FXML
private CheckBox trainFilter;
@FXML
private TextField filterText;
@FXML
private ToggleButton proportionalToggle;
@FXML
private ListView<Shapeable<?>> legend;
@FXML
private ToggleButton legendButton;
@FXML
private TextField velocityText;
@FXML
private ToggleButton playToggle;
@FXML
private Button closeButton;
@FXML
private BorderPane rootPane;
@FXML
private DetailsController detailBoxController;
@FXML
private Pane leftPane;
@FXML
private ToggleButton logToggle;
@FXML
private ListView<Event> logList;
@FXML
private Button resetButton;
@FXML
private Button resetViewButton;
@FXML
private Button infoButton;
@FXML
private TextField timeText;
@FXML
private Button continueSimulation;
@FXML
private Label modelTime;
@FXML
private HBox rightSpacer;
@FXML
private Pane centerPane;
@FXML
private Pane graphPane;
@Nullable
private Graph graph;
private Map<Train, TrainView> trains;
@Nullable
private Highlightable lastHighlighted = null;
private Stage stage;
private static final double SCALE_DELTA = 1.1;
private double mousePressedX = -1;
private double mousePressedY = -1;
private boolean autoChange = false;
private Pattern timePattern;
private IntegerProperty simulationTime;
/**
* Is updated when simulationTime changes, but AFTER the model state has been updated
*/
private ObservableIntegerValue postSimulationTime;
private IntegerProperty velocity;
private Animation simulation;
private Timeline eventTraversalTimeline;
@FXML
private void initialize() {
timePattern = Pattern.compile("(\\d+)(m?s?|h)?$");
trains = new WeakHashMap<>();
HBox.setHgrow(rightSpacer, Priority.ALWAYS);
// START OF TIME RELATED INIT
simulationTime = new SimpleIntegerProperty();
IntegerProperty postSimulationTime = new SimpleIntegerProperty();
this.postSimulationTime = postSimulationTime;
simulationTime.addListener((observable, oldValue, newValue) -> {
DataSourceHolder.getInstance().ifPresent(dataSource -> {
Context context = dataSource.getContext();
int oldInt = oldValue.intValue();
int newInt = newValue.intValue();
timeText.setText(String.format("%dms", newInt));
Element.in(context).setTime(newInt);
if (newInt > oldInt) {
boolean messages = Messages.in(context).fireEventsBetween(
node -> getGraph().getNodes().get(node).getShape(),
oldInt,
newInt
);
if (messages) {
playToggle.setSelected(false);
}
}
});
postSimulationTime.setValue(newValue);
});
timeText.setOnAction(event -> {
String text = timeText.getText();
Matcher timeMatch = timePattern.matcher(text);
int newTime = 0;
if (timeMatch.find()) {
try {
newTime = getMsFromString(text);
} catch (NumberFormatException e) {
timeText.setText(simulationTime.get() + "ms");
return;
}
}
simulationTime.set(newTime);
selectClosestLogEntry(newTime);
});
timeText.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
timeText.setText(simulationTime.get() + "ms");
}
});
this.simulation = new Timeline(new KeyFrame(Duration.millis(50), event -> {
int time = (int) (simulationTime.get() + (velocity.get() * 0.05));
simulationTime.set(time);
selectClosestLogEntry(time);
}));
simulation.setCycleCount(Animation.INDEFINITE);
eventTraversalTimeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
Event nextEvent = selectNextEvent(getCurrentTime());
simulationTime.set(nextEvent.getTime());
}));
eventTraversal.selectedProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
eventTraversalTimeline.play();
} else {
eventTraversalTimeline.stop();
}
timeText.setDisable(newValue);
playToggle.setDisable(newValue);
});
eventTraversalTimeline.setCycleCount(Timeline.INDEFINITE);
// END OF TIME RELATED INIT
fireOnEnterPress(closeButton);
fireOnEnterPress(logToggle);
closeButton.setOnAction(event -> showSourceChooser());
resetButton.setOnAction(event -> {
simulationTime.set(Context.INIT_STATE_TIME);
selectClosestLogEntry(Context.INIT_STATE_TIME);
});
infoButton.setOnAction(event -> showLicenceInfo());
resetViewButton.setOnAction(event -> resetGraphView());
proportionalToggle.setOnAction(ActionEvent -> switchGraph());
legendButton.selectedProperty().addListener((observable, oldValue, newValue) -> {
legend.setVisible(newValue);
if (newValue) {
legend.toFront();
} else {
legend.toBack();
}
});
detailBoxController.setOnClose(event -> hideDetailView());
// Hide logList by default
rootPane.setLeft(null);
logToggle.selectedProperty().addListener((observable, oldValue, newValue) ->
rootPane.setLeft(newValue ? leftPane : null)
);
initializeElementList();
initializeLogList();
initializeCenterPane();
velocity = new SimpleIntegerProperty(1000);
velocityText.textProperty().addListener((observable, oldValue, newValue) -> {
try {
int newVelocity = Integer.parseUnsignedInt(newValue);
velocity.set(newVelocity);
} catch (NumberFormatException e) {
velocityText.setText(oldValue);
}
});
playToggle.selectedProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
simulation.playFromStart();
} else {
simulation.stop();
}
timeText.setDisable(newValue);
eventTraversal.setDisable(newValue);
});
DataSourceHolder.getInstance().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
boolean isRest = newValue instanceof RestSource;
continueSimulation.setVisible(isRest);
modelTime.setVisible(isRest);
}
});
continueSimulation.setOnAction(event -> {
RestSource source = (RestSource) DataSourceHolder.getInstance().get();
continueSimulation.setDisable(true);
source.continueSimulation();
String text = ResourceBundle.getBundle("bundles.localization")
.getString("model_time");
modelTime.setText(String.format(text, source.getTime()));
continueSimulation.setDisable(false);
});
}
private void initializeCenterPane() {
ChangeListener<Number> boundsListener = (observable, oldValue, newValue) -> {
if (DataSourceHolder.getInstance().isPresent()) {
fitGraphToCenter(getGraph());
}
};
graphPane.heightProperty().addListener(boundsListener);
graphPane.widthProperty().addListener(boundsListener);
graphPane.setOnScroll(event -> {
if (graph != null) {
Group group = graph.getGroup();
Bounds bounds = group.localToScene(group.getBoundsInLocal());
double oldScale = group.getScaleX();
double scaleFactor =
oldScale * ((event.getDeltaY() > 0) ? SCALE_DELTA : 1 / SCALE_DELTA);
double translateX =
event.getScreenX() - (bounds.getWidth() / 2 + bounds.getMinX());
double translateY =
event.getScreenY() - (bounds.getHeight() / 2 + bounds.getMinY());
double factor = (scaleFactor / oldScale) - 1;
group.setScaleX(scaleFactor);
group.setScaleY(scaleFactor);
group.setTranslateX(group.getTranslateX() - factor * translateX);
group.setTranslateY(group.getTranslateY() - factor * translateY);
}
});
graphPane.setOnMouseReleased(event -> {
mousePressedX = -1;
mousePressedY = -1;
});
graphPane.setOnMouseDragged(event -> {
if (!event.isPrimaryButtonDown()) {
return;
}
if (mousePressedX == -1 && mousePressedY == -1) {
mousePressedX = event.getX();
mousePressedY = event.getY();
}
double xOffset = (event.getX() - mousePressedX);
double yOffset = (event.getY() - mousePressedY);
graphPane.setTranslateX(graphPane.getTranslateX() + xOffset);
graphPane.setTranslateY(graphPane.getTranslateY() + yOffset);
event.consume();
});
MenuItem exportItem = new MenuItem("Export");
exportItem.setOnAction(event -> exportGraph());
ContextMenuUtil.attach(centerPane, Collections.singletonList(exportItem));
}
private void initializeLogList() {
StringConverter<Event> stringConverter = new StringConverter<Event>() {
@Override
public String toString(Event event) {
return event.getDescription();
}
@Override
public Event fromString(String string) {
return null;
}
};
Callback<ListView<Event>, ListCell<Event>> textFactory = TextFieldListCell
.forListView(stringConverter);
AtomicReference<Binding<Paint>> paintBinding = new AtomicReference<>();
Callback<ListView<Event>, ListCell<Event>> listCellFactory = cell -> {
ListCell<Event> result = textFactory.call(cell);
Paint defaultTextFill = result.getTextFill();
result.itemProperty().addListener(((observable, oldValue, newValue) -> {
if (newValue != null) {
Binding<Paint> warningBinding = Bindings.createObjectBinding(
() -> newValue.getWarnings().isEmpty() ?
defaultTextFill : Color.rgb(255, 0, 0),
newValue.getWarnings()
);
paintBinding.set(warningBinding);
result.textFillProperty().bind(warningBinding);
}
}));
TooltipUtil.install(result, () -> {
StringBuilder sb = new StringBuilder();
if (result.getItem() != null) {
sb.append(result.getItem().getDescription());
for (String warning : result.getItem().getWarnings()) {
sb.append(System.lineSeparator()).append("[WARN]: ").append(warning);
}
}
return sb.toString();
});
return result;
};
logList.setCellFactory(listCellFactory);
logList.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> {
if (!autoChange) {
simulationTime.set(newValue.getTime());
}
Context context = DataSourceHolder.getInstance().getContext();
Element.in(context).setTime(newValue.getTime());
}
);
}
private void initializeElementList() {
StringConverter<GraphObject> stringConverter = new StringConverter<GraphObject>() {
@Override
public String toString(GraphObject object) {
return object.getName();
}
@Override
public GraphObject fromString(String string) {
return null;
}
};
Callback<ListView<GraphObject>, ListCell<GraphObject>> textFactory = TextFieldListCell
.forListView(stringConverter);
Callback<ListView<GraphObject>, ListCell<GraphObject>> elementListCellFactory =
(listView) -> {
ListCell<GraphObject> cell = textFactory.call(listView);
TooltipUtil.install(cell, () -> {
if (cell.getItem() != null) {
return cell.getItem().getName();
} else {
return "";
}
});
return cell;
};
elementList.setCellFactory(elementListCellFactory);
elementList.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if (lastHighlighted != null) {
lastHighlighted.highlightedProperty().set(false);
}
if (newValue == null) {
return;
}
if (newValue instanceof Element) {
Element elemnt = (Element) newValue;
lastHighlighted = getGraph().getElements().get(elemnt);
} else {
Train train = (Train) newValue;
lastHighlighted = trains.get(train);
}
lastHighlighted.highlightedProperty().set(true);
setDetail(DetailsBase.create(newValue, postSimulationTime, centerPane));
});
}
private int getLastEventIndex(int time) {
int last = 0;
List<Event> items = logList.getItems();
for (int index = 0; index < items.size(); index++) {
Event item = items.get(index);
if (item.getTime() > time) {
return last;
}
last = index;
}
// Return last
return last;
}
private Event selectNextEvent(int time) {
int index = getLastEventIndex(time) + 1;
if (index >= logList.getItems().size()) {
index--;
}
Event event = logList.getItems().get(index);
selectEvent(event);
return event;
}
private Event selectClosestLogEntry(int time) {
Event event = logList.getItems().get(getLastEventIndex(time));
selectEvent(event);
return event;
}
private void selectEvent(Event event) {
autoChange = true;
logList.getSelectionModel().select(event);
logList.scrollTo(event);
autoChange = false;
}
private int getMsFromString(String timeString) {
int ms = -1;
Matcher timeMatch = timePattern.matcher(timeString);
String type = "ms";
int time = ms;
if (timeMatch.find()) {
String typeMatch = timeMatch.group(2);
if (typeMatch != null) {
type = typeMatch;
}
time = Integer.valueOf(timeMatch.group(1));
}
switch (type) {
case "s":
ms = time * 1000;
break;
case "m":
ms = time * 1000 * 60;
break;
case "h":
ms = time * 1000 * 60 * 60;
break;
default:
ms = time;
}
return ms;
}
private void showDetailView() {
detail.toFront();
legend.toBack();
elementList.toBack();
}
private void hideDetailView() {
detail.toBack();
elementList.toFront();
elementList.getSelectionModel().clearSelection();
}
/**
* Adds an EventHandler to the button which fires the button on pressing enter.
*
* @param button Button to add eventHandler to
*/
private void fireOnEnterPress(ButtonBase button) {
button.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
if (event.getCode() == KeyCode.ENTER) {
button.fire();
}
});
}
public void setStage(@Nonnull Stage stage) {
this.stage = stage;
stage.setScene(new Scene(rootPane));
stage.centerOnScreen();
stage.setMaximized(false);
stage.setMaximized(true);
}
private void showLegend() {
Context context = DataSourceHolder.getInstance().getContext();
ObservableList<Shapeable<?>> items = Stream.concat(
Train.in(context).getAll().stream(),
Element.in(context).getAll().stream()
.map(Element::getType)
.distinct()
).collect(FXCollectors.toObservableList());
legend.setItems(items);
legend.setCellFactory(studentListView -> new LegendListViewCell());
}
private int getCurrentTime() {
return simulationTime.get();
}
private void showElements() {
Context context = DataSourceHolder.getInstance().getContext();
FilteredList<Train> trains = FXCollections.observableList(
new ArrayList<>(Train.in(context).getAll())
).filtered(null);
ObservableValue<Predicate<Train>> trainBinding = Bindings.createObjectBinding(
() -> s -> trainFilter.isSelected(),
trainFilter.selectedProperty()
);
context.addObject(trainBinding);
trains.predicateProperty().bind(trainBinding);
FilteredList<Element> elements = FXCollections.observableList(
new ArrayList<>(Element.in(context).getAll())
).filtered(null);
ObservableValue<Predicate<Element>> elementBinding = Bindings.createObjectBinding(
() -> s -> elementFilter.isSelected(),
elementFilter.selectedProperty());
context.addObject(elementBinding);
elements.predicateProperty().bind(elementBinding);
ObservableList<GraphObject> items = new CompositeObservableList<>(trains, elements);
FilteredList<GraphObject> textFilteredItems = items.filtered(null);
ObservableValue<Predicate<GraphObject>> textFilterBinding = Bindings
.createObjectBinding(() -> {
String text = filterText.getText().trim().toLowerCase();
return s -> s.getName().toLowerCase().contains(text);
}, filterText.textProperty());
context.addObject(textFilterBinding);
textFilteredItems.predicateProperty().bind(textFilterBinding);
elementList.setItems(textFilteredItems);
}
public void setDataSource(@Nonnull DataSource source) {
DataSourceHolder.getInstance().set(source);
Context context = source.getContext();
logList.setItems(context.getObservableEvents().sorted());
fitGraphToCenter(getGraph());
simulationTime.set(Context.INIT_STATE_TIME);
showElements();
}
/**
* Gets the current graph shape.<br>
* If no graph shape exists, this method creates one and returns it.
*
* @return the graph shape
* @throws IllegalStateException if there is no context
*/
@Nonnull
private Graph getGraph() {
if (graph == null) {
Context context = DataSourceHolder.getInstance().getContext();
if (proportionalToggle.isSelected()) {
graph = new Graph(context, new ProportionalCoordinatesAdapter(context));
} else {
graph = new Graph(context, new SimpleCoordinatesAdapter());
}
graphPane.getChildren().add(graph.getGroup());
showLegend();
for (Map.Entry<Element, GraphShape<Element>> entry : graph.getElements().entrySet()) {
Element element = entry.getKey();
Shape elementShape = entry.getValue().getShape(element);
Binding<Boolean> binding = Bindings.createBooleanBinding(() ->
element.getType().isVisible(elementShape.getBoundsInParent()),
element.getType().visibleStateProperty()
);
context.addObject(binding);
entry.getValue().getShape(element).visibleProperty().bind(binding);
elementShape.setOnMouseClicked(event -> {
elementList.getSelectionModel().select(element);
});
}
for (Train train : Train.in(context).getAll()) {
TrainView trainView = new TrainView(train, graph);
trainView.timeProperty().bind(simulationTime);
trains.put(train, trainView);
trainView.setOnMouseClicked(e -> elementList.getSelectionModel().select(train));
}
}
return graph;
}
private void setDetail(DetailsBase<? extends GraphObject<?>> detail) {
showDetailView();
detailBoxController.setDetail(detail);
}
private void fitGraphToCenter(Graph graph) {
Bounds graphBounds = graph.getGroup().getBoundsInParent();
double widthFactor = (graphPane.getWidth()) / graphBounds.getWidth();
double heightFactor = (graphPane.getHeight()) / graphBounds.getHeight();
double scaleFactor = Math.min(widthFactor, heightFactor);
if (!Double.isFinite(scaleFactor)) {
scaleFactor = 1;
}
if (scaleFactor <= 0) {
scaleFactor = 1;
}
graph.scale(scaleFactor);
moveGraphToCenter(graph);
}
private void moveGraphToCenter(Graph graph) {
Bounds graphBounds = graph.getGroup().getBoundsInParent();
double finalX = (graphPane.getWidth() - graphBounds.getWidth()) / 2;
double xTranslate = finalX - graphBounds.getMinX();
double finalY = (graphPane.getHeight() - graphBounds.getHeight()) / 2;
double yTranslate = finalY - graphBounds.getMinY();
graph.move(xTranslate, yTranslate);
}
private void showSourceChooser() {
cleanUp();
FXMLLoader loader = new FXMLLoader(getClass().getResource(
"sourcechooser/SourceChooser.fxml"));
loader.setResources(ResourceBundle.getBundle("bundles.localization"));
try {
loader.load();
} catch (IOException e) {
// This should never happen, because the location is set (see load function)
return;
}
SourceController controller = loader.getController();
controller.setStage(stage);
}
private void resetGraphView() {
fitGraphToCenter(getGraph());
graphPane.setTranslateX(0);
graphPane.setTranslateY(0);
}
private void cleanUp() {
stage.setMaximized(false);
if (graph != null) {
simulation.stop();
graphPane.getChildren().clear();
graph = null;
}
DataSourceHolder.getInstance().set(null);
}
private void switchGraph() {
GraphObject selected = elementList.getSelectionModel().getSelectedItem();
graphPane.getChildren().clear();
graph = null;
fitGraphToCenter(getGraph());
if (selected != null) {
// reselect element
elementList.getSelectionModel().select(null);
elementList.getSelectionModel().select(selected);
}
}
private void showLicenceInfo() {
Visualisierbar.showLicenceInfo();
}
private void exportGraph() {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("gnuplot (*.dat)", "*.dat"),
new FileChooser.ExtensionFilter("PNG Image (*.png)", "*.png"),
new FileChooser.ExtensionFilter("JPEG Image (*.jpg)", "*.jpg")
);
String initDirString = ConfigFile.getInstance().getProperty(
ConfigKey.initialLogFileDirectory.getKey(),
System.getProperty("user.home")
);
File initDir = new File(initDirString);
fileChooser.setInitialDirectory(initDir);
fileChooser.setInitialFileName("Graph");
File file = fileChooser.showSaveDialog(rootPane.getScene().getWindow());
if (file != null) {
Exporter.exportGraph(this.getGraph(), file);
}
}
}
| mit |
ecgreb/robolectric | src/main/java/org/robolectric/shadows/ShadowLocalBroadcastManager.java | 860 | package org.robolectric.shadows;
import android.content.Context;
import android.support.v4.content.LocalBroadcastManager;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import static org.robolectric.Robolectric.shadowOf;
@Implements(value = LocalBroadcastManager.class, callThroughByDefault = true)
public class ShadowLocalBroadcastManager {
@Implementation
public static LocalBroadcastManager getInstance(final Context context) {
return shadowOf(context).getShadowApplication().getSingleton(LocalBroadcastManager.class, new Provider<LocalBroadcastManager>() {
@Override
public LocalBroadcastManager get() {
return Robolectric.newInstance(LocalBroadcastManager.class, new Class[] {Context.class}, new Object[] {context});
}
});
}
}
| mit |
metamx/d8a-conjure | src/main/java/io/d8a/conjure/Conjurer.java | 12481 | package io.d8a.conjure;
import com.google.common.base.Preconditions;
import org.apache.commons.cli.*;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class Conjurer implements Runnable {
private static final Random RAND = new Random();
private final static long waitTime = 15L;
private final static TimeUnit unit = TimeUnit.SECONDS;
private final Clock clock;
private final long stopTime;
private final Printer printer;
private final int linesPerSec;
private final long maxLines;
private String filePath;
private long count = 0;
private ConjureTemplate template;
private boolean customSchema = false;
private final Thread thread = new Thread(this);
public Conjurer(long stopTime, Printer printer, int linesPerSec, String filePath) {
this(-1, stopTime, printer, linesPerSec, Long.MAX_VALUE, filePath);
}
public Conjurer(long startTime, long stopTime, Printer printer, int linesPerSec, String filePath) {
this(startTime, stopTime, printer, linesPerSec, Long.MAX_VALUE, filePath);
}
public Conjurer(long startTime, long stopTime, Printer printer, int linesPerSec, long maxLines, String filePath) {
this.stopTime = stopTime;
this.printer = printer;
this.linesPerSec = linesPerSec;
this.maxLines = maxLines;
this.filePath = filePath;
if(startTime < 0){ //-1 means generate data moving forward.
clock = Clock.SYSTEM_CLOCK;
}else{
clock = new SimulatedClock(startTime);
}
ConjureTemplateParser parser = new ConjureTemplateParser(clock);
try {
if(FilenameUtils.getExtension(filePath).equals("json")){
this.customSchema = true;
this.template = parser.jsonParse(filePath);
} else {
this.template = parser.parse(new FileInputStream(filePath));
}
}catch (IOException e) {
throw new IllegalArgumentException("Could not create ConjureTemplate from " + filePath, e);
}
}
public static Builder getBuilder() {
return new Builder();
}
public static void main(String[] args) throws IOException, ParseException {
Options options = new Options();
options.addOption("zk", true, "Zookeeper connection string for kafka");
options.addOption("topic", true, "Kafka topic to send data to");
options.addOption("template", true, "Path to the Conjure Template file that describes the data to generate");
options.addOption("rate", true, "Lines per second");
options.addOption("cap", true, "Total lines to generate");
options.addOption("out", true, "Where to write the generated samples. [file|console|kafka|none]");
options.addOption("file", true, "Filename to write generated samples to.");
options.addOption(
"startTime",
true,
"For historical data generation. What epoch time to start generating data from."
);
options.addOption("stopTime", true, "For historical data generation. What epoch time to stop generating data.");
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
String filePath = null;
String[] appArgs = cmd.getArgs();
if(appArgs != null && appArgs.length > 0){
filePath = appArgs[0];
}else{
filePath = cmd.getOptionValue("template");
}
if(filePath == null){
throw new IllegalArgumentException("Must specify a template that describes the data to be generated.");
}
long stopTime = Long.MAX_VALUE;
if(cmd.hasOption("stopTime")){
stopTime = new Long(cmd.getOptionValue("stopTime"));
}
long startTime = -1;
if(cmd.hasOption("startTime")){
startTime = new Long(cmd.getOptionValue("startTime"));
if(stopTime == Long.MAX_VALUE){
stopTime = System.currentTimeMillis();
}
}
Printer printer = consolePrinter();
if(cmd.hasOption("out")){
Set<String> outs = new HashSet<String>(Arrays.asList(cmd.getOptionValue("out").split(",")));
List<Printer> printers = new ArrayList<Printer>();
for(String out : outs) {
printers.add(createPrinter(out, cmd));
}
if(printers.size() == 1){
printer = printers.get(0);
}else{
printer = new MultiPrinter(printers.toArray(new Printer[printers.size()]));
}
}
int linesPerSec = 10;
if(cmd.hasOption("rate")){
linesPerSec = new Integer(cmd.getOptionValue("rate"));
}
long numLines = Long.MAX_VALUE;
if(cmd.hasOption("cap")){
numLines = new Long(cmd.getOptionValue("cap"));
}
long start = System.currentTimeMillis();
Conjurer conjurer = new Conjurer(startTime, stopTime, printer, linesPerSec, numLines, filePath);
conjurer.exhaust();
long duration = System.currentTimeMillis() - start;
System.err
.println("Conjurer finished. Took " + duration + "ms to conjure up " + conjurer.getCount() + " samples.");
}
private static Printer createPrinter(String type, CommandLine cmd) {
if("kafka".equals(type)){
if(cmd.hasOption("zk") && cmd.hasOption("topic")){
return kafkaPrinter(cmd.getOptionValue("zk"), cmd.getOptionValue("topic"));
}
throw new IllegalArgumentException(
"Must specify zookeeper connection string ('zk') and kafka topic ('topic') to write to kafka."
);
}else if("file".equals(type)){
if(cmd.hasOption("file")){
try {
return filePrinter(cmd.getOptionValue("file"));
}catch(FileNotFoundException e) {
throw new IllegalArgumentException("Could not create file printer.", e);
}
}
throw new IllegalArgumentException("Must specify file path to write to a file.");
}else if("console".equals(type)){
return consolePrinter();
}else if("none".equals(type)){
return nonePrinter();
}
throw new IllegalArgumentException("Printer type '" + type + "' not supported.");
}
private static Printer filePrinter(String fileName) throws FileNotFoundException {
return new FilePrinter(new File(fileName));
}
public void exhaust() {
start();
try {
thread.join();
}catch(InterruptedException e) {
thread.interrupt();
}
}
public void start() {
thread.setDaemon(true);
thread.start();
}
public void stop() {
thread.interrupt();
}
public void run() {
System.err.println("Conjuring data to " + printer + " at a rate of " + linesPerSec + " lines per second.");
double linesPerMs = (double) linesPerSec / 1000;
long start = clock.currentTimeMillis();
long lastReport = start;
long bytesWritten = 0L;
String lastLinePrinted = "";
Iterator<String> linesIterator = null;
for(int i=0; i<maxLines && clock.currentTimeMillis() <stopTime; i++) {
throttle(start, i, linesPerMs);
if(Thread.currentThread().isInterrupted()){
return;
}
Object event;
if(customSchema){
event = template.conjureMapData();
}else{
if(linesIterator == null || !linesIterator.hasNext()){
linesIterator = conjureNextBatch();
}
event = linesIterator.next();
}
printer.print(event);
++count;
if(System.currentTimeMillis() - lastReport > 5000){
report(start, count, lastLinePrinted, bytesWritten);
lastReport = System.currentTimeMillis();
}
}
report(start, count, lastLinePrinted, bytesWritten);
}
private Iterator<String> conjureNextBatch() {
String lineVal = template.conjure();
String[] conjureList = lineVal.split("\n");
return Arrays.asList(conjureList).iterator();
}
public static Printer nonePrinter() {
return new Printer<String>() {
@Override
public void print(String message) {
}
public String toString() {
return "Blackhole";
}
};
}
private void report(long start, long linesPrinted) {
long now = clock.currentTimeMillis();
long duration = now - start;
long ratePerSec = (long) (1000 * ((double) linesPrinted) / duration);
System.err.println("generated "+linesPrinted+ " lines in "+duration+"ms (using the "+clock+"), "+ratePerSec+"/s.");
}
private void report(long start, long linesPrinted, String lastLinePrinted, long bytesPrinted) {
long now = clock.currentTimeMillis();
long duration = now - start;
long ratePerSec = (long) (1000 * ((double) linesPrinted) / duration);
long bytesPerSec = (long) (1000 * ((double) bytesPrinted) / duration);
long bytesPerMin = (long) (60000 * ((double) bytesPrinted) / duration);
System.err.println("generated "+linesPrinted+ " lines in "+duration+"ms (using the "+clock+"), "+ratePerSec+"/s.");
System.err.println("bytes/sec: " + bytesPerSec + ", bytes/min: " + bytesPerMin);
System.err.println("Last: " + lastLinePrinted);
}
private void throttle(long start, long lineNumber, double linesPerMs) {
while(checkThrottle(start, lineNumber, linesPerMs)) {
clock.sleep(1);
}
}
private boolean checkThrottle(long start, long lineNumber, double linesPerMSec) {
long elapsedMs = clock.currentTimeMillis() - start;
long expectedLines = (long) (elapsedMs * linesPerMSec);
if(lineNumber < expectedLines){
return false;
}
return true;
}
public static Printer kafkaPrinter(String zkString, String topic) {
return new KafkaPrinter(zkString, topic);
}
public static Printer queuePrinter(BlockingQueue queue) {
return new QueuePrinter(queue, waitTime, unit);
}
public static Printer<String> consolePrinter() {
return new ConsolePrinter();
}
public long getCount() {
return count;
}
public static class Builder {
private long startTime = -1;
private long stopTime = Long.MAX_VALUE;
private Printer printer = Conjurer.nonePrinter();
private int linesPerSec = 10;
private long maxLines = Long.MAX_VALUE;
private String filePath = null;
private boolean customSchema = false;
public Builder withStartTime(Long startTime) {
if(startTime != null){
this.startTime = startTime;
}
return this;
}
public Builder withPrinter(Printer printer) {
this.printer = printer;
return this;
}
public Builder withStopTime(Long stopTime) {
if(stopTime != null){
this.stopTime = stopTime;
}
return this;
}
public Builder withLinesPerSec(Integer linesPerSec) {
if(linesPerSec != null){
this.linesPerSec = linesPerSec;
}
return this;
}
public Builder withMaxLines(Long maxLines) {
if(maxLines != null){
this.maxLines = maxLines;
}
return this;
}
public Builder withFilePath(String filePath) {
this.filePath = filePath;
return this;
}
public Conjurer build() {
Preconditions.checkArgument(filePath != null, "Must specify filepath");
return new Conjurer(startTime, stopTime, printer, linesPerSec, maxLines, filePath);
}
}
} | mit |
loremipsumdolor/CastFast | src/com/amazonaws/services/s3/AmazonS3Encryption.java | 781 | /*
* Copyright 2013-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.s3;
/**
* A marker interface used to check if an instance of S3 client is
* an S3 encryption client.
*/
public interface AmazonS3Encryption extends AmazonS3 {
}
| mit |
mestihudson/ruby-runtime-plugin | src/main/java/jenkins/ruby/DoDynamic.java | 474 | package jenkins.ruby;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
/**
* This interface is meant to be included by JRuby proxies so that they
* can respond directly to stapler requests.
*
* If I understand correctly, stapler will see if the <code>doDynamic</code>
* method exists and if so, dispatch it via that method.
*/
public interface DoDynamic {
void doDynamic(StaplerRequest request, StaplerResponse response);
}
| mit |
selvasingh/azure-sdk-for-java | sdk/sql/mgmt-v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/DatabaseVulnerabilityAssessmentRuleBaseline.java | 4770 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.sql.v2017_03_01_preview;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.sql.v2017_03_01_preview.implementation.DatabaseVulnerabilityAssessmentRuleBaselineInner;
import com.microsoft.azure.arm.model.Indexable;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.sql.v2017_03_01_preview.implementation.SqlManager;
import java.util.List;
/**
* Type representing DatabaseVulnerabilityAssessmentRuleBaseline.
*/
public interface DatabaseVulnerabilityAssessmentRuleBaseline extends HasInner<DatabaseVulnerabilityAssessmentRuleBaselineInner>, Indexable, Refreshable<DatabaseVulnerabilityAssessmentRuleBaseline>, Updatable<DatabaseVulnerabilityAssessmentRuleBaseline.Update>, HasManager<SqlManager> {
/**
* @return the baselineResults value.
*/
List<DatabaseVulnerabilityAssessmentRuleBaselineItem> baselineResults();
/**
* @return the id value.
*/
String id();
/**
* @return the name value.
*/
String name();
/**
* @return the type value.
*/
String type();
/**
* The entirety of the DatabaseVulnerabilityAssessmentRuleBaseline definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithRule, DefinitionStages.WithBaselineResults, DefinitionStages.WithCreate {
}
/**
* Grouping of DatabaseVulnerabilityAssessmentRuleBaseline definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a DatabaseVulnerabilityAssessmentRuleBaseline definition.
*/
interface Blank extends WithRule {
}
/**
* The stage of the databasevulnerabilityassessmentrulebaseline definition allowing to specify Rule.
*/
interface WithRule {
/**
* Specifies resourceGroupName, serverName, databaseName, ruleId.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal
* @param serverName The name of the server
* @param databaseName The name of the database for which the vulnerability assessment rule baseline is defined
* @param ruleId The vulnerability assessment rule ID
* @return the next definition stage
*/
WithBaselineResults withExistingRule(String resourceGroupName, String serverName, String databaseName, String ruleId);
}
/**
* The stage of the databasevulnerabilityassessmentrulebaseline definition allowing to specify BaselineResults.
*/
interface WithBaselineResults {
/**
* Specifies baselineResults.
* @param baselineResults The rule baseline result
* @return the next definition stage
*/
WithCreate withBaselineResults(List<DatabaseVulnerabilityAssessmentRuleBaselineItem> baselineResults);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<DatabaseVulnerabilityAssessmentRuleBaseline> {
}
}
/**
* The template for a DatabaseVulnerabilityAssessmentRuleBaseline update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<DatabaseVulnerabilityAssessmentRuleBaseline>, UpdateStages.WithBaselineResults {
}
/**
* Grouping of DatabaseVulnerabilityAssessmentRuleBaseline update stages.
*/
interface UpdateStages {
/**
* The stage of the databasevulnerabilityassessmentrulebaseline update allowing to specify BaselineResults.
*/
interface WithBaselineResults {
/**
* Specifies baselineResults.
* @param baselineResults The rule baseline result
* @return the next update stage
*/
Update withBaselineResults(List<DatabaseVulnerabilityAssessmentRuleBaselineItem> baselineResults);
}
}
}
| mit |
AgriCraft/AgriCraft | src/main/java/com/infinityraider/agricraft/network/MessageIrrigationNeighbourUpdate.java | 1409 | package com.infinityraider.agricraft.network;
import com.infinityraider.agricraft.AgriCraft;
import com.infinityraider.agricraft.content.irrigation.TileEntityIrrigationComponent;
import com.infinityraider.infinitylib.network.MessageBase;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkEvent;
public class MessageIrrigationNeighbourUpdate extends MessageBase {
private BlockPos pos;
private Direction dir;
public MessageIrrigationNeighbourUpdate() {
super();
}
public MessageIrrigationNeighbourUpdate(BlockPos pos, Direction dir) {
this();
this.pos = pos;
this.dir = dir;
}
@Override
public NetworkDirection getMessageDirection() {
return NetworkDirection.PLAY_TO_CLIENT;
}
@Override
protected void processMessage(NetworkEvent.Context ctx) {
World world = AgriCraft.instance.getClientWorld();
if(world != null && this.pos != null && this.dir != null) {
TileEntity tile = world.getTileEntity(this.pos);
if(tile instanceof TileEntityIrrigationComponent) {
((TileEntityIrrigationComponent) tile).onNeighbourUpdate(this.dir);
}
}
}
}
| mit |
dave-miles/ghprb-plugin | src/main/java/org/jenkinsci/plugins/ghprb/GhprbBuilds.java | 8248 | package org.jenkinsci.plugins.ghprb;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.TaskListener;
import hudson.model.queue.QueueTaskFuture;
import hudson.plugins.git.util.BuildData;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.ghprb.extensions.GhprbCommentAppender;
import org.jenkinsci.plugins.ghprb.extensions.GhprbCommitStatus;
import org.jenkinsci.plugins.ghprb.extensions.GhprbCommitStatusException;
import org.jenkinsci.plugins.ghprb.extensions.GhprbExtension;
import org.kohsuke.github.GHCommitState;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHUser;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author janinko
*/
public class GhprbBuilds {
private static final Logger logger = Logger.getLogger(GhprbBuilds.class.getName());
private final GhprbTrigger trigger;
private final GhprbRepository repo;
public GhprbBuilds(GhprbTrigger trigger, GhprbRepository repo) {
this.trigger = trigger;
this.repo = repo;
}
public void build(GhprbPullRequest pr, GHUser triggerSender, String commentBody) {
GhprbCause cause = new GhprbCause(pr.getHead(), pr.getId(), pr.isMergeable(), pr.getTarget(), pr.getSource(), pr.getAuthorEmail(), pr.getTitle(), pr.getUrl(), triggerSender, commentBody,
pr.getCommitAuthor(), pr.getPullRequestAuthor());
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) {
if (ext instanceof GhprbCommitStatus) {
try {
((GhprbCommitStatus) ext).onBuildTriggered(trigger, pr, repo.getGitHubRepo());
} catch (GhprbCommitStatusException e) {
repo.commentOnFailure(null, null, e);
}
}
}
QueueTaskFuture<?> build = trigger.startJob(cause, repo);
if (build == null) {
logger.log(Level.SEVERE, "Job did not start");
}
}
public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) {
PrintStream logger = listener.getLogger();
GhprbCause c = Ghprb.getCause(build);
if (c == null) {
return;
}
GhprbTrigger trigger = Ghprb.extractTrigger(build);
ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(build.getProject().getFullName());
GHPullRequest pr = pulls.get(c.getPullID()).getPullRequest();
try {
int counter = 0;
// If the PR is being resolved by GitHub then getMergeable will return null
Boolean isMergeable = pr.getMergeable();
Boolean isMerged = pr.isMerged();
// Not sure if isMerged can return null, but adding if just in case
if (isMerged == null) {
isMerged = false;
}
while (isMergeable == null && !isMerged && counter++ < 60) {
Thread.sleep(1000);
isMergeable = pr.getMergeable();
isMerged = pr.isMerged();
if (isMerged == null) {
isMerged = false;
}
}
if (isMerged) {
logger.println("PR has already been merged, builds using the merged sha1 will fail!!!");
} else if (isMergeable == null) {
logger.println("PR merge status couldn't be retrieved, maybe GitHub hasn't settled yet");
} else if (isMergeable != c.isMerged()) {
logger.println("!!! PR mergeability status has changed !!! ");
if (isMergeable) {
logger.println("PR now has NO merge conflicts");
} else if (!isMergeable) {
logger.println("PR now has merge conflicts!");
}
}
} catch (Exception e) {
logger.print("Unable to query GitHub for status of PullRequest");
e.printStackTrace(logger);
}
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) {
if (ext instanceof GhprbCommitStatus) {
try {
((GhprbCommitStatus) ext).onBuildStart(build, listener, repo.getGitHubRepo());
} catch (GhprbCommitStatusException e) {
repo.commentOnFailure(build, listener, e);
}
}
}
try {
String template = trigger.getBuildDescTemplate();
if (StringUtils.isEmpty(template)) {
template = "<a title=\"$title\" href=\"$url\">PR #$pullId</a>: $abbrTitle";
}
Map<String, String> vars = getVariables(c);
template = Util.replaceMacro(template, vars);
template = Ghprb.replaceMacros(build, listener, template);
build.setDescription(template);
} catch (IOException ex) {
logger.print("Can't update build description");
ex.printStackTrace(logger);
}
}
public Map<String, String> getVariables(GhprbCause c) {
Map<String, String> vars = new HashMap<String, String>();
vars.put("title", c.getTitle());
vars.put("url", c.getUrl().toString());
vars.put("pullId", Integer.toString(c.getPullID()));
vars.put("abbrTitle", c.getAbbreviatedTitle());
return vars;
}
public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) {
GhprbCause c = Ghprb.getCause(build);
if (c == null) {
return;
}
// remove the BuildData action that we may have added earlier to avoid
// having two of them, and because the one we added isn't correct
// @see GhprbTrigger
BuildData fakeOne = null;
for (BuildData data : build.getActions(BuildData.class)) {
if (data.getLastBuiltRevision() != null && !data.getLastBuiltRevision().getSha1String().equals(c.getCommit())) {
fakeOne = data;
break;
}
}
if (fakeOne != null) {
build.getActions().remove(fakeOne);
}
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) {
if (ext instanceof GhprbCommitStatus) {
try {
((GhprbCommitStatus) ext).onBuildComplete(build, listener, repo.getGitHubRepo());
} catch (GhprbCommitStatusException e) {
repo.commentOnFailure(build, listener, e);
}
}
}
GHCommitState state;
state = Ghprb.getState(build);
commentOnBuildResult(build, listener, state, c);
// close failed pull request automatically
if (state == GHCommitState.FAILURE && trigger.isAutoCloseFailedPullRequests()) {
closeFailedRequest(listener, c);
}
}
private void closeFailedRequest(TaskListener listener, GhprbCause c) {
try {
GHPullRequest pr = repo.getPullRequest(c.getPullID());
if (pr.getState().equals(GHIssueState.OPEN)) {
repo.closePullRequest(c.getPullID());
}
} catch (IOException ex) {
listener.getLogger().println("Can't close pull request");
ex.printStackTrace(listener.getLogger());
}
}
private void commentOnBuildResult(AbstractBuild<?, ?> build, TaskListener listener, GHCommitState state, GhprbCause c) {
StringBuilder msg = new StringBuilder();
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommentAppender.class)) {
if (ext instanceof GhprbCommentAppender) {
msg.append(((GhprbCommentAppender) ext).postBuildComment(build, listener));
}
}
if (msg.length() > 0) {
listener.getLogger().println(msg);
repo.addComment(c.getPullID(), msg.toString(), build, listener);
}
}
}
| mit |
halex2005/diadocsdk-java | src/main/java/Diadoc/Api/Proto/Documents/UniversalTransferDocument/UniversalTransferDocumentProtos.java | 299246 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Documents/UniversalTransferDocument.proto
package Diadoc.Api.Proto.Documents.UniversalTransferDocument;
public final class UniversalTransferDocumentProtos {
private UniversalTransferDocumentProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
/**
* Protobuf enum {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus}
*/
public enum UniversalTransferDocumentStatus
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <code>UnknownDocumentStatus = 0;</code>
*
* <pre>
* This type will be reported to legacy client when it receives unknown status from server
* </pre>
*/
UnknownDocumentStatus(0, 0),
/**
* <code>OutboundWaitingForSenderSignature = 1;</code>
*/
OutboundWaitingForSenderSignature(1, 1),
/**
* <code>OutboundWaitingForInvoiceReceiptAndRecipientSignature = 2;</code>
*/
OutboundWaitingForInvoiceReceiptAndRecipientSignature(2, 2),
/**
* <code>OutboundWaitingForInvoiceReceipt = 3;</code>
*/
OutboundWaitingForInvoiceReceipt(3, 3),
/**
* <code>OutboundWaitingForRecipientSignature = 4;</code>
*/
OutboundWaitingForRecipientSignature(4, 4),
/**
* <code>OutboundWithRecipientSignature = 5;</code>
*/
OutboundWithRecipientSignature(5, 5),
/**
* <code>OutboundRecipientSignatureRequestRejected = 6;</code>
*/
OutboundRecipientSignatureRequestRejected(6, 6),
/**
* <code>OutboundInvalidSenderSignature = 7;</code>
*/
OutboundInvalidSenderSignature(7, 7),
/**
* <code>OutboundNotFinished = 8;</code>
*/
OutboundNotFinished(8, 8),
/**
* <code>OutboundFinished = 9;</code>
*/
OutboundFinished(9, 9),
/**
* <code>InboundWaitingForRecipientSignature = 16;</code>
*/
InboundWaitingForRecipientSignature(10, 16),
/**
* <code>InboundWithRecipientSignature = 17;</code>
*/
InboundWithRecipientSignature(11, 17),
/**
* <code>InboundRecipientSignatureRequestRejected = 18;</code>
*/
InboundRecipientSignatureRequestRejected(12, 18),
/**
* <code>InboundInvalidRecipientSignature = 19;</code>
*/
InboundInvalidRecipientSignature(13, 19),
/**
* <code>InboundNotFinished = 20;</code>
*/
InboundNotFinished(14, 20),
/**
* <code>InboundFinished = 21;</code>
*/
InboundFinished(15, 21),
;
/**
* <code>UnknownDocumentStatus = 0;</code>
*
* <pre>
* This type will be reported to legacy client when it receives unknown status from server
* </pre>
*/
public static final int UnknownDocumentStatus_VALUE = 0;
/**
* <code>OutboundWaitingForSenderSignature = 1;</code>
*/
public static final int OutboundWaitingForSenderSignature_VALUE = 1;
/**
* <code>OutboundWaitingForInvoiceReceiptAndRecipientSignature = 2;</code>
*/
public static final int OutboundWaitingForInvoiceReceiptAndRecipientSignature_VALUE = 2;
/**
* <code>OutboundWaitingForInvoiceReceipt = 3;</code>
*/
public static final int OutboundWaitingForInvoiceReceipt_VALUE = 3;
/**
* <code>OutboundWaitingForRecipientSignature = 4;</code>
*/
public static final int OutboundWaitingForRecipientSignature_VALUE = 4;
/**
* <code>OutboundWithRecipientSignature = 5;</code>
*/
public static final int OutboundWithRecipientSignature_VALUE = 5;
/**
* <code>OutboundRecipientSignatureRequestRejected = 6;</code>
*/
public static final int OutboundRecipientSignatureRequestRejected_VALUE = 6;
/**
* <code>OutboundInvalidSenderSignature = 7;</code>
*/
public static final int OutboundInvalidSenderSignature_VALUE = 7;
/**
* <code>OutboundNotFinished = 8;</code>
*/
public static final int OutboundNotFinished_VALUE = 8;
/**
* <code>OutboundFinished = 9;</code>
*/
public static final int OutboundFinished_VALUE = 9;
/**
* <code>InboundWaitingForRecipientSignature = 16;</code>
*/
public static final int InboundWaitingForRecipientSignature_VALUE = 16;
/**
* <code>InboundWithRecipientSignature = 17;</code>
*/
public static final int InboundWithRecipientSignature_VALUE = 17;
/**
* <code>InboundRecipientSignatureRequestRejected = 18;</code>
*/
public static final int InboundRecipientSignatureRequestRejected_VALUE = 18;
/**
* <code>InboundInvalidRecipientSignature = 19;</code>
*/
public static final int InboundInvalidRecipientSignature_VALUE = 19;
/**
* <code>InboundNotFinished = 20;</code>
*/
public static final int InboundNotFinished_VALUE = 20;
/**
* <code>InboundFinished = 21;</code>
*/
public static final int InboundFinished_VALUE = 21;
public final int getNumber() { return value; }
public static UniversalTransferDocumentStatus valueOf(int value) {
switch (value) {
case 0: return UnknownDocumentStatus;
case 1: return OutboundWaitingForSenderSignature;
case 2: return OutboundWaitingForInvoiceReceiptAndRecipientSignature;
case 3: return OutboundWaitingForInvoiceReceipt;
case 4: return OutboundWaitingForRecipientSignature;
case 5: return OutboundWithRecipientSignature;
case 6: return OutboundRecipientSignatureRequestRejected;
case 7: return OutboundInvalidSenderSignature;
case 8: return OutboundNotFinished;
case 9: return OutboundFinished;
case 16: return InboundWaitingForRecipientSignature;
case 17: return InboundWithRecipientSignature;
case 18: return InboundRecipientSignatureRequestRejected;
case 19: return InboundInvalidRecipientSignature;
case 20: return InboundNotFinished;
case 21: return InboundFinished;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<UniversalTransferDocumentStatus>
internalGetValueMap() {
return internalValueMap;
}
private static com.google.protobuf.Internal.EnumLiteMap<UniversalTransferDocumentStatus>
internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<UniversalTransferDocumentStatus>() {
public UniversalTransferDocumentStatus findValueByNumber(int number) {
return UniversalTransferDocumentStatus.valueOf(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(index);
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.getDescriptor().getEnumTypes().get(0);
}
private static final UniversalTransferDocumentStatus[] VALUES = values();
public static UniversalTransferDocumentStatus valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
return VALUES[desc.getIndex()];
}
private final int index;
private final int value;
private UniversalTransferDocumentStatus(int index, int value) {
this.index = index;
this.value = value;
}
// @@protoc_insertion_point(enum_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus)
}
public interface UniversalTransferDocumentMetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
boolean hasDocumentStatus();
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
boolean hasTotal();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
java.lang.String getTotal();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
com.google.protobuf.ByteString
getTotalBytes();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
boolean hasVat();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
java.lang.String getVat();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
com.google.protobuf.ByteString
getVatBytes();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
boolean hasGrounds();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
java.lang.String getGrounds();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
com.google.protobuf.ByteString
getGroundsBytes();
/**
* <code>required string DocumentFunction = 5;</code>
*/
boolean hasDocumentFunction();
/**
* <code>required string DocumentFunction = 5;</code>
*/
java.lang.String getDocumentFunction();
/**
* <code>required string DocumentFunction = 5;</code>
*/
com.google.protobuf.ByteString
getDocumentFunctionBytes();
/**
* <code>required int32 Currency = 6;</code>
*/
boolean hasCurrency();
/**
* <code>required int32 Currency = 6;</code>
*/
int getCurrency();
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
boolean hasConfirmationDateTimeTicks();
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
long getConfirmationDateTimeTicks();
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
boolean hasInvoiceAmendmentFlags();
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
int getInvoiceAmendmentFlags();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata}
*/
public static final class UniversalTransferDocumentMetadata extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata)
UniversalTransferDocumentMetadataOrBuilder {
// Use UniversalTransferDocumentMetadata.newBuilder() to construct.
private UniversalTransferDocumentMetadata(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private UniversalTransferDocumentMetadata(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final UniversalTransferDocumentMetadata defaultInstance;
public static UniversalTransferDocumentMetadata getDefaultInstance() {
return defaultInstance;
}
public UniversalTransferDocumentMetadata getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private UniversalTransferDocumentMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.valueOf(rawValue);
if (value == null) {
unknownFields.mergeVarintField(1, rawValue);
} else {
bitField0_ |= 0x00000001;
documentStatus_ = value;
}
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
total_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
vat_ = bs;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000008;
grounds_ = bs;
break;
}
case 42: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000010;
documentFunction_ = bs;
break;
}
case 48: {
bitField0_ |= 0x00000020;
currency_ = input.readInt32();
break;
}
case 65: {
bitField0_ |= 0x00000040;
confirmationDateTimeTicks_ = input.readSFixed64();
break;
}
case 72: {
bitField0_ |= 0x00000080;
invoiceAmendmentFlags_ = input.readInt32();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.Builder.class);
}
public static com.google.protobuf.Parser<UniversalTransferDocumentMetadata> PARSER =
new com.google.protobuf.AbstractParser<UniversalTransferDocumentMetadata>() {
public UniversalTransferDocumentMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UniversalTransferDocumentMetadata(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<UniversalTransferDocumentMetadata> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int DOCUMENTSTATUS_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_;
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
public static final int TOTAL_FIELD_NUMBER = 2;
private java.lang.Object total_;
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public boolean hasTotal() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public java.lang.String getTotal() {
java.lang.Object ref = total_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
total_ = s;
}
return s;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public com.google.protobuf.ByteString
getTotalBytes() {
java.lang.Object ref = total_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
total_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VAT_FIELD_NUMBER = 3;
private java.lang.Object vat_;
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public boolean hasVat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public java.lang.String getVat() {
java.lang.Object ref = vat_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vat_ = s;
}
return s;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public com.google.protobuf.ByteString
getVatBytes() {
java.lang.Object ref = vat_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vat_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GROUNDS_FIELD_NUMBER = 4;
private java.lang.Object grounds_;
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DOCUMENTFUNCTION_FIELD_NUMBER = 5;
private java.lang.Object documentFunction_;
/**
* <code>required string DocumentFunction = 5;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CURRENCY_FIELD_NUMBER = 6;
private int currency_;
/**
* <code>required int32 Currency = 6;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>required int32 Currency = 6;</code>
*/
public int getCurrency() {
return currency_;
}
public static final int CONFIRMATIONDATETIMETICKS_FIELD_NUMBER = 8;
private long confirmationDateTimeTicks_;
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
public static final int INVOICEAMENDMENTFLAGS_FIELD_NUMBER = 9;
private int invoiceAmendmentFlags_;
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
private void initFields() {
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
total_ = "";
vat_ = "";
grounds_ = "";
documentFunction_ = "";
currency_ = 0;
confirmationDateTimeTicks_ = 0L;
invoiceAmendmentFlags_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasTotal()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasDocumentFunction()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasCurrency()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeEnum(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getTotalBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getVatBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getGroundsBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBytes(5, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeInt32(6, currency_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeSFixed64(8, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(9, invoiceAmendmentFlags_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getTotalBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getVatBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getGroundsBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(5, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(6, currency_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeSFixed64Size(8, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(9, invoiceAmendmentFlags_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata)
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.Builder.class);
}
// Construct using Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
bitField0_ = (bitField0_ & ~0x00000001);
total_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
vat_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
grounds_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
documentFunction_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
currency_ = 0;
bitField0_ = (bitField0_ & ~0x00000020);
confirmationDateTimeTicks_ = 0L;
bitField0_ = (bitField0_ & ~0x00000040);
invoiceAmendmentFlags_ = 0;
bitField0_ = (bitField0_ & ~0x00000080);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata getDefaultInstanceForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.getDefaultInstance();
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata build() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata buildPartial() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata result = new Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.documentStatus_ = documentStatus_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.total_ = total_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.vat_ = vat_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.grounds_ = grounds_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.documentFunction_ = documentFunction_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.currency_ = currency_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.confirmationDateTimeTicks_ = confirmationDateTimeTicks_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.invoiceAmendmentFlags_ = invoiceAmendmentFlags_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata) {
return mergeFrom((Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata other) {
if (other == Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata.getDefaultInstance()) return this;
if (other.hasDocumentStatus()) {
setDocumentStatus(other.getDocumentStatus());
}
if (other.hasTotal()) {
bitField0_ |= 0x00000002;
total_ = other.total_;
onChanged();
}
if (other.hasVat()) {
bitField0_ |= 0x00000004;
vat_ = other.vat_;
onChanged();
}
if (other.hasGrounds()) {
bitField0_ |= 0x00000008;
grounds_ = other.grounds_;
onChanged();
}
if (other.hasDocumentFunction()) {
bitField0_ |= 0x00000010;
documentFunction_ = other.documentFunction_;
onChanged();
}
if (other.hasCurrency()) {
setCurrency(other.getCurrency());
}
if (other.hasConfirmationDateTimeTicks()) {
setConfirmationDateTimeTicks(other.getConfirmationDateTimeTicks());
}
if (other.hasInvoiceAmendmentFlags()) {
setInvoiceAmendmentFlags(other.getInvoiceAmendmentFlags());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasTotal()) {
return false;
}
if (!hasDocumentFunction()) {
return false;
}
if (!hasCurrency()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentMetadata) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public Builder setDocumentStatus(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
documentStatus_ = value;
onChanged();
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1 [default = UnknownDocumentStatus];</code>
*/
public Builder clearDocumentStatus() {
bitField0_ = (bitField0_ & ~0x00000001);
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
onChanged();
return this;
}
private java.lang.Object total_ = "";
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public boolean hasTotal() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public java.lang.String getTotal() {
java.lang.Object ref = total_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
total_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public com.google.protobuf.ByteString
getTotalBytes() {
java.lang.Object ref = total_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
total_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder setTotal(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
total_ = value;
onChanged();
return this;
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder clearTotal() {
bitField0_ = (bitField0_ & ~0x00000002);
total_ = getDefaultInstance().getTotal();
onChanged();
return this;
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder setTotalBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
total_ = value;
onChanged();
return this;
}
private java.lang.Object vat_ = "";
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public boolean hasVat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public java.lang.String getVat() {
java.lang.Object ref = vat_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vat_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public com.google.protobuf.ByteString
getVatBytes() {
java.lang.Object ref = vat_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vat_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder setVat(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
vat_ = value;
onChanged();
return this;
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder clearVat() {
bitField0_ = (bitField0_ & ~0x00000004);
vat_ = getDefaultInstance().getVat();
onChanged();
return this;
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder setVatBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
vat_ = value;
onChanged();
return this;
}
private java.lang.Object grounds_ = "";
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGrounds(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
grounds_ = value;
onChanged();
return this;
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder clearGrounds() {
bitField0_ = (bitField0_ & ~0x00000008);
grounds_ = getDefaultInstance().getGrounds();
onChanged();
return this;
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGroundsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
grounds_ = value;
onChanged();
return this;
}
private java.lang.Object documentFunction_ = "";
/**
* <code>required string DocumentFunction = 5;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder setDocumentFunction(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
documentFunction_ = value;
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder clearDocumentFunction() {
bitField0_ = (bitField0_ & ~0x00000010);
documentFunction_ = getDefaultInstance().getDocumentFunction();
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder setDocumentFunctionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
documentFunction_ = value;
onChanged();
return this;
}
private int currency_ ;
/**
* <code>required int32 Currency = 6;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>required int32 Currency = 6;</code>
*/
public int getCurrency() {
return currency_;
}
/**
* <code>required int32 Currency = 6;</code>
*/
public Builder setCurrency(int value) {
bitField0_ |= 0x00000020;
currency_ = value;
onChanged();
return this;
}
/**
* <code>required int32 Currency = 6;</code>
*/
public Builder clearCurrency() {
bitField0_ = (bitField0_ & ~0x00000020);
currency_ = 0;
onChanged();
return this;
}
private long confirmationDateTimeTicks_ ;
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public Builder setConfirmationDateTimeTicks(long value) {
bitField0_ |= 0x00000040;
confirmationDateTimeTicks_ = value;
onChanged();
return this;
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 8;</code>
*/
public Builder clearConfirmationDateTimeTicks() {
bitField0_ = (bitField0_ & ~0x00000040);
confirmationDateTimeTicks_ = 0L;
onChanged();
return this;
}
private int invoiceAmendmentFlags_ ;
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public Builder setInvoiceAmendmentFlags(int value) {
bitField0_ |= 0x00000080;
invoiceAmendmentFlags_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 InvoiceAmendmentFlags = 9;</code>
*/
public Builder clearInvoiceAmendmentFlags() {
bitField0_ = (bitField0_ & ~0x00000080);
invoiceAmendmentFlags_ = 0;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata)
}
static {
defaultInstance = new UniversalTransferDocumentMetadata(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentMetadata)
}
public interface UniversalTransferDocumentRevisionMetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata)
com.google.protobuf.MessageOrBuilder {
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
boolean hasDocumentStatus();
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
boolean hasTotal();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
java.lang.String getTotal();
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
com.google.protobuf.ByteString
getTotalBytes();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
boolean hasVat();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
java.lang.String getVat();
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
com.google.protobuf.ByteString
getVatBytes();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
boolean hasGrounds();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
java.lang.String getGrounds();
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
com.google.protobuf.ByteString
getGroundsBytes();
/**
* <code>required string DocumentFunction = 5;</code>
*/
boolean hasDocumentFunction();
/**
* <code>required string DocumentFunction = 5;</code>
*/
java.lang.String getDocumentFunction();
/**
* <code>required string DocumentFunction = 5;</code>
*/
com.google.protobuf.ByteString
getDocumentFunctionBytes();
/**
* <code>required int32 Currency = 6;</code>
*/
boolean hasCurrency();
/**
* <code>required int32 Currency = 6;</code>
*/
int getCurrency();
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
boolean hasConfirmationDateTimeTicks();
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
long getConfirmationDateTimeTicks();
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
boolean hasInvoiceAmendmentFlags();
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
int getInvoiceAmendmentFlags();
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
boolean hasOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
java.lang.String getOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes();
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
boolean hasOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
java.lang.String getOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceDateBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata}
*/
public static final class UniversalTransferDocumentRevisionMetadata extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata)
UniversalTransferDocumentRevisionMetadataOrBuilder {
// Use UniversalTransferDocumentRevisionMetadata.newBuilder() to construct.
private UniversalTransferDocumentRevisionMetadata(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private UniversalTransferDocumentRevisionMetadata(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final UniversalTransferDocumentRevisionMetadata defaultInstance;
public static UniversalTransferDocumentRevisionMetadata getDefaultInstance() {
return defaultInstance;
}
public UniversalTransferDocumentRevisionMetadata getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private UniversalTransferDocumentRevisionMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.valueOf(rawValue);
if (value == null) {
unknownFields.mergeVarintField(1, rawValue);
} else {
bitField0_ |= 0x00000001;
documentStatus_ = value;
}
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
total_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
vat_ = bs;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000008;
grounds_ = bs;
break;
}
case 42: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000010;
documentFunction_ = bs;
break;
}
case 48: {
bitField0_ |= 0x00000020;
currency_ = input.readInt32();
break;
}
case 57: {
bitField0_ |= 0x00000040;
confirmationDateTimeTicks_ = input.readSFixed64();
break;
}
case 64: {
bitField0_ |= 0x00000080;
invoiceAmendmentFlags_ = input.readInt32();
break;
}
case 74: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000100;
originalInvoiceNumber_ = bs;
break;
}
case 82: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000200;
originalInvoiceDate_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.Builder.class);
}
public static com.google.protobuf.Parser<UniversalTransferDocumentRevisionMetadata> PARSER =
new com.google.protobuf.AbstractParser<UniversalTransferDocumentRevisionMetadata>() {
public UniversalTransferDocumentRevisionMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UniversalTransferDocumentRevisionMetadata(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<UniversalTransferDocumentRevisionMetadata> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int DOCUMENTSTATUS_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
public static final int TOTAL_FIELD_NUMBER = 2;
private java.lang.Object total_;
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public boolean hasTotal() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public java.lang.String getTotal() {
java.lang.Object ref = total_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
total_ = s;
}
return s;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public com.google.protobuf.ByteString
getTotalBytes() {
java.lang.Object ref = total_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
total_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VAT_FIELD_NUMBER = 3;
private java.lang.Object vat_;
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public boolean hasVat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public java.lang.String getVat() {
java.lang.Object ref = vat_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vat_ = s;
}
return s;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public com.google.protobuf.ByteString
getVatBytes() {
java.lang.Object ref = vat_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vat_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GROUNDS_FIELD_NUMBER = 4;
private java.lang.Object grounds_;
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DOCUMENTFUNCTION_FIELD_NUMBER = 5;
private java.lang.Object documentFunction_;
/**
* <code>required string DocumentFunction = 5;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CURRENCY_FIELD_NUMBER = 6;
private int currency_;
/**
* <code>required int32 Currency = 6;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>required int32 Currency = 6;</code>
*/
public int getCurrency() {
return currency_;
}
public static final int CONFIRMATIONDATETIMETICKS_FIELD_NUMBER = 7;
private long confirmationDateTimeTicks_;
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
public static final int INVOICEAMENDMENTFLAGS_FIELD_NUMBER = 8;
private int invoiceAmendmentFlags_;
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
public static final int ORIGINALINVOICENUMBER_FIELD_NUMBER = 9;
private java.lang.Object originalInvoiceNumber_;
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEDATE_FIELD_NUMBER = 10;
private java.lang.Object originalInvoiceDate_;
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
total_ = "";
vat_ = "";
grounds_ = "";
documentFunction_ = "";
currency_ = 0;
confirmationDateTimeTicks_ = 0L;
invoiceAmendmentFlags_ = 0;
originalInvoiceNumber_ = "";
originalInvoiceDate_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasDocumentStatus()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasTotal()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasDocumentFunction()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasCurrency()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasInvoiceAmendmentFlags()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceNumber()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceDate()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeEnum(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getTotalBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getVatBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getGroundsBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBytes(5, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeInt32(6, currency_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeSFixed64(7, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(8, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeBytes(9, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeBytes(10, getOriginalInvoiceDateBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getTotalBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getVatBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getGroundsBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(5, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(6, currency_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeSFixed64Size(7, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(8, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(9, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(10, getOriginalInvoiceDateBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata)
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.Builder.class);
}
// Construct using Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
bitField0_ = (bitField0_ & ~0x00000001);
total_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
vat_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
grounds_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
documentFunction_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
currency_ = 0;
bitField0_ = (bitField0_ & ~0x00000020);
confirmationDateTimeTicks_ = 0L;
bitField0_ = (bitField0_ & ~0x00000040);
invoiceAmendmentFlags_ = 0;
bitField0_ = (bitField0_ & ~0x00000080);
originalInvoiceNumber_ = "";
bitField0_ = (bitField0_ & ~0x00000100);
originalInvoiceDate_ = "";
bitField0_ = (bitField0_ & ~0x00000200);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata getDefaultInstanceForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.getDefaultInstance();
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata build() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata buildPartial() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata result = new Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.documentStatus_ = documentStatus_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.total_ = total_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.vat_ = vat_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.grounds_ = grounds_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.documentFunction_ = documentFunction_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.currency_ = currency_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.confirmationDateTimeTicks_ = confirmationDateTimeTicks_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.invoiceAmendmentFlags_ = invoiceAmendmentFlags_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.originalInvoiceNumber_ = originalInvoiceNumber_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.originalInvoiceDate_ = originalInvoiceDate_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata) {
return mergeFrom((Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata other) {
if (other == Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata.getDefaultInstance()) return this;
if (other.hasDocumentStatus()) {
setDocumentStatus(other.getDocumentStatus());
}
if (other.hasTotal()) {
bitField0_ |= 0x00000002;
total_ = other.total_;
onChanged();
}
if (other.hasVat()) {
bitField0_ |= 0x00000004;
vat_ = other.vat_;
onChanged();
}
if (other.hasGrounds()) {
bitField0_ |= 0x00000008;
grounds_ = other.grounds_;
onChanged();
}
if (other.hasDocumentFunction()) {
bitField0_ |= 0x00000010;
documentFunction_ = other.documentFunction_;
onChanged();
}
if (other.hasCurrency()) {
setCurrency(other.getCurrency());
}
if (other.hasConfirmationDateTimeTicks()) {
setConfirmationDateTimeTicks(other.getConfirmationDateTimeTicks());
}
if (other.hasInvoiceAmendmentFlags()) {
setInvoiceAmendmentFlags(other.getInvoiceAmendmentFlags());
}
if (other.hasOriginalInvoiceNumber()) {
bitField0_ |= 0x00000100;
originalInvoiceNumber_ = other.originalInvoiceNumber_;
onChanged();
}
if (other.hasOriginalInvoiceDate()) {
bitField0_ |= 0x00000200;
originalInvoiceDate_ = other.originalInvoiceDate_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasDocumentStatus()) {
return false;
}
if (!hasTotal()) {
return false;
}
if (!hasDocumentFunction()) {
return false;
}
if (!hasCurrency()) {
return false;
}
if (!hasInvoiceAmendmentFlags()) {
return false;
}
if (!hasOriginalInvoiceNumber()) {
return false;
}
if (!hasOriginalInvoiceDate()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentRevisionMetadata) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder setDocumentStatus(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
documentStatus_ = value;
onChanged();
return this;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder clearDocumentStatus() {
bitField0_ = (bitField0_ & ~0x00000001);
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
onChanged();
return this;
}
private java.lang.Object total_ = "";
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public boolean hasTotal() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public java.lang.String getTotal() {
java.lang.Object ref = total_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
total_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public com.google.protobuf.ByteString
getTotalBytes() {
java.lang.Object ref = total_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
total_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder setTotal(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
total_ = value;
onChanged();
return this;
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder clearTotal() {
bitField0_ = (bitField0_ & ~0x00000002);
total_ = getDefaultInstance().getTotal();
onChanged();
return this;
}
/**
* <code>required string Total = 2;</code>
*
* <pre>
* TotalSum;
* </pre>
*/
public Builder setTotalBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
total_ = value;
onChanged();
return this;
}
private java.lang.Object vat_ = "";
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public boolean hasVat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public java.lang.String getVat() {
java.lang.Object ref = vat_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vat_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public com.google.protobuf.ByteString
getVatBytes() {
java.lang.Object ref = vat_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vat_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder setVat(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
vat_ = value;
onChanged();
return this;
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder clearVat() {
bitField0_ = (bitField0_ & ~0x00000004);
vat_ = getDefaultInstance().getVat();
onChanged();
return this;
}
/**
* <code>optional string Vat = 3;</code>
*
* <pre>
*TotalVat;
* </pre>
*/
public Builder setVatBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
vat_ = value;
onChanged();
return this;
}
private java.lang.Object grounds_ = "";
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGrounds(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
grounds_ = value;
onChanged();
return this;
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder clearGrounds() {
bitField0_ = (bitField0_ & ~0x00000008);
grounds_ = getDefaultInstance().getGrounds();
onChanged();
return this;
}
/**
* <code>optional string Grounds = 4;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGroundsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
grounds_ = value;
onChanged();
return this;
}
private java.lang.Object documentFunction_ = "";
/**
* <code>required string DocumentFunction = 5;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder setDocumentFunction(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
documentFunction_ = value;
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder clearDocumentFunction() {
bitField0_ = (bitField0_ & ~0x00000010);
documentFunction_ = getDefaultInstance().getDocumentFunction();
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 5;</code>
*/
public Builder setDocumentFunctionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
documentFunction_ = value;
onChanged();
return this;
}
private int currency_ ;
/**
* <code>required int32 Currency = 6;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>required int32 Currency = 6;</code>
*/
public int getCurrency() {
return currency_;
}
/**
* <code>required int32 Currency = 6;</code>
*/
public Builder setCurrency(int value) {
bitField0_ |= 0x00000020;
currency_ = value;
onChanged();
return this;
}
/**
* <code>required int32 Currency = 6;</code>
*/
public Builder clearCurrency() {
bitField0_ = (bitField0_ & ~0x00000020);
currency_ = 0;
onChanged();
return this;
}
private long confirmationDateTimeTicks_ ;
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public Builder setConfirmationDateTimeTicks(long value) {
bitField0_ |= 0x00000040;
confirmationDateTimeTicks_ = value;
onChanged();
return this;
}
/**
* <code>optional sfixed64 ConfirmationDateTimeTicks = 7;</code>
*/
public Builder clearConfirmationDateTimeTicks() {
bitField0_ = (bitField0_ & ~0x00000040);
confirmationDateTimeTicks_ = 0L;
onChanged();
return this;
}
private int invoiceAmendmentFlags_ ;
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public Builder setInvoiceAmendmentFlags(int value) {
bitField0_ |= 0x00000080;
invoiceAmendmentFlags_ = value;
onChanged();
return this;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 8;</code>
*/
public Builder clearInvoiceAmendmentFlags() {
bitField0_ = (bitField0_ & ~0x00000080);
invoiceAmendmentFlags_ = 0;
onChanged();
return this;
}
private java.lang.Object originalInvoiceNumber_ = "";
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public Builder setOriginalInvoiceNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000100;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public Builder clearOriginalInvoiceNumber() {
bitField0_ = (bitField0_ & ~0x00000100);
originalInvoiceNumber_ = getDefaultInstance().getOriginalInvoiceNumber();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 9;</code>
*/
public Builder setOriginalInvoiceNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000100;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceDate_ = "";
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public Builder setOriginalInvoiceDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000200;
originalInvoiceDate_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public Builder clearOriginalInvoiceDate() {
bitField0_ = (bitField0_ & ~0x00000200);
originalInvoiceDate_ = getDefaultInstance().getOriginalInvoiceDate();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 10;</code>
*/
public Builder setOriginalInvoiceDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000200;
originalInvoiceDate_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata)
}
static {
defaultInstance = new UniversalTransferDocumentRevisionMetadata(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentRevisionMetadata)
}
public interface UniversalCorrectionDocumentMetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata)
com.google.protobuf.MessageOrBuilder {
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
boolean hasDocumentStatus();
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus();
/**
* <code>required string TotalInc = 2;</code>
*/
boolean hasTotalInc();
/**
* <code>required string TotalInc = 2;</code>
*/
java.lang.String getTotalInc();
/**
* <code>required string TotalInc = 2;</code>
*/
com.google.protobuf.ByteString
getTotalIncBytes();
/**
* <code>required string TotalDec = 3;</code>
*/
boolean hasTotalDec();
/**
* <code>required string TotalDec = 3;</code>
*/
java.lang.String getTotalDec();
/**
* <code>required string TotalDec = 3;</code>
*/
com.google.protobuf.ByteString
getTotalDecBytes();
/**
* <code>required string VatInc = 4;</code>
*/
boolean hasVatInc();
/**
* <code>required string VatInc = 4;</code>
*/
java.lang.String getVatInc();
/**
* <code>required string VatInc = 4;</code>
*/
com.google.protobuf.ByteString
getVatIncBytes();
/**
* <code>required string VatDec = 5;</code>
*/
boolean hasVatDec();
/**
* <code>required string VatDec = 5;</code>
*/
java.lang.String getVatDec();
/**
* <code>required string VatDec = 5;</code>
*/
com.google.protobuf.ByteString
getVatDecBytes();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
boolean hasGrounds();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
java.lang.String getGrounds();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
com.google.protobuf.ByteString
getGroundsBytes();
/**
* <code>required string DocumentFunction = 7;</code>
*/
boolean hasDocumentFunction();
/**
* <code>required string DocumentFunction = 7;</code>
*/
java.lang.String getDocumentFunction();
/**
* <code>required string DocumentFunction = 7;</code>
*/
com.google.protobuf.ByteString
getDocumentFunctionBytes();
/**
* <code>required int32 Currency = 8;</code>
*/
boolean hasCurrency();
/**
* <code>required int32 Currency = 8;</code>
*/
int getCurrency();
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
boolean hasConfirmationDateTimeTicks();
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
long getConfirmationDateTimeTicks();
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
boolean hasInvoiceAmendmentFlags();
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
int getInvoiceAmendmentFlags();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
boolean hasOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
java.lang.String getOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
boolean hasOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
java.lang.String getOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceDateBytes();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
boolean hasOriginalInvoiceRevisionNumber();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
java.lang.String getOriginalInvoiceRevisionNumber();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
boolean hasOriginalInvoiceRevisionDate();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
java.lang.String getOriginalInvoiceRevisionDate();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata}
*/
public static final class UniversalCorrectionDocumentMetadata extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata)
UniversalCorrectionDocumentMetadataOrBuilder {
// Use UniversalCorrectionDocumentMetadata.newBuilder() to construct.
private UniversalCorrectionDocumentMetadata(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private UniversalCorrectionDocumentMetadata(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final UniversalCorrectionDocumentMetadata defaultInstance;
public static UniversalCorrectionDocumentMetadata getDefaultInstance() {
return defaultInstance;
}
public UniversalCorrectionDocumentMetadata getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private UniversalCorrectionDocumentMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.valueOf(rawValue);
if (value == null) {
unknownFields.mergeVarintField(1, rawValue);
} else {
bitField0_ |= 0x00000001;
documentStatus_ = value;
}
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
totalInc_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
totalDec_ = bs;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000008;
vatInc_ = bs;
break;
}
case 42: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000010;
vatDec_ = bs;
break;
}
case 50: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000020;
grounds_ = bs;
break;
}
case 58: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000040;
documentFunction_ = bs;
break;
}
case 64: {
bitField0_ |= 0x00000080;
currency_ = input.readInt32();
break;
}
case 73: {
bitField0_ |= 0x00000100;
confirmationDateTimeTicks_ = input.readSFixed64();
break;
}
case 80: {
bitField0_ |= 0x00000200;
invoiceAmendmentFlags_ = input.readInt32();
break;
}
case 90: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = bs;
break;
}
case 98: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000800;
originalInvoiceDate_ = bs;
break;
}
case 106: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = bs;
break;
}
case 114: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.Builder.class);
}
public static com.google.protobuf.Parser<UniversalCorrectionDocumentMetadata> PARSER =
new com.google.protobuf.AbstractParser<UniversalCorrectionDocumentMetadata>() {
public UniversalCorrectionDocumentMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UniversalCorrectionDocumentMetadata(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<UniversalCorrectionDocumentMetadata> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int DOCUMENTSTATUS_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
public static final int TOTALINC_FIELD_NUMBER = 2;
private java.lang.Object totalInc_;
/**
* <code>required string TotalInc = 2;</code>
*/
public boolean hasTotalInc() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string TotalInc = 2;</code>
*/
public java.lang.String getTotalInc() {
java.lang.Object ref = totalInc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalInc_ = s;
}
return s;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public com.google.protobuf.ByteString
getTotalIncBytes() {
java.lang.Object ref = totalInc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TOTALDEC_FIELD_NUMBER = 3;
private java.lang.Object totalDec_;
/**
* <code>required string TotalDec = 3;</code>
*/
public boolean hasTotalDec() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string TotalDec = 3;</code>
*/
public java.lang.String getTotalDec() {
java.lang.Object ref = totalDec_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalDec_ = s;
}
return s;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public com.google.protobuf.ByteString
getTotalDecBytes() {
java.lang.Object ref = totalDec_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VATINC_FIELD_NUMBER = 4;
private java.lang.Object vatInc_;
/**
* <code>required string VatInc = 4;</code>
*/
public boolean hasVatInc() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>required string VatInc = 4;</code>
*/
public java.lang.String getVatInc() {
java.lang.Object ref = vatInc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatInc_ = s;
}
return s;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public com.google.protobuf.ByteString
getVatIncBytes() {
java.lang.Object ref = vatInc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VATDEC_FIELD_NUMBER = 5;
private java.lang.Object vatDec_;
/**
* <code>required string VatDec = 5;</code>
*/
public boolean hasVatDec() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string VatDec = 5;</code>
*/
public java.lang.String getVatDec() {
java.lang.Object ref = vatDec_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatDec_ = s;
}
return s;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public com.google.protobuf.ByteString
getVatDecBytes() {
java.lang.Object ref = vatDec_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GROUNDS_FIELD_NUMBER = 6;
private java.lang.Object grounds_;
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DOCUMENTFUNCTION_FIELD_NUMBER = 7;
private java.lang.Object documentFunction_;
/**
* <code>required string DocumentFunction = 7;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CURRENCY_FIELD_NUMBER = 8;
private int currency_;
/**
* <code>required int32 Currency = 8;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 Currency = 8;</code>
*/
public int getCurrency() {
return currency_;
}
public static final int CONFIRMATIONDATETIMETICKS_FIELD_NUMBER = 9;
private long confirmationDateTimeTicks_;
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
public static final int INVOICEAMENDMENTFLAGS_FIELD_NUMBER = 10;
private int invoiceAmendmentFlags_;
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
public static final int ORIGINALINVOICENUMBER_FIELD_NUMBER = 11;
private java.lang.Object originalInvoiceNumber_;
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEDATE_FIELD_NUMBER = 12;
private java.lang.Object originalInvoiceDate_;
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEREVISIONNUMBER_FIELD_NUMBER = 13;
private java.lang.Object originalInvoiceRevisionNumber_;
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public boolean hasOriginalInvoiceRevisionNumber() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public java.lang.String getOriginalInvoiceRevisionNumber() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionNumber_ = s;
}
return s;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEREVISIONDATE_FIELD_NUMBER = 14;
private java.lang.Object originalInvoiceRevisionDate_;
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public boolean hasOriginalInvoiceRevisionDate() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public java.lang.String getOriginalInvoiceRevisionDate() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionDate_ = s;
}
return s;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
totalInc_ = "";
totalDec_ = "";
vatInc_ = "";
vatDec_ = "";
grounds_ = "";
documentFunction_ = "";
currency_ = 0;
confirmationDateTimeTicks_ = 0L;
invoiceAmendmentFlags_ = 0;
originalInvoiceNumber_ = "";
originalInvoiceDate_ = "";
originalInvoiceRevisionNumber_ = "";
originalInvoiceRevisionDate_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasDocumentStatus()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasTotalInc()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasTotalDec()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasVatInc()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasVatDec()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasDocumentFunction()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasCurrency()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasConfirmationDateTimeTicks()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasInvoiceAmendmentFlags()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceNumber()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceDate()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeEnum(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getTotalIncBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getTotalDecBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getVatIncBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBytes(5, getVatDecBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeBytes(6, getGroundsBytes());
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBytes(7, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(8, currency_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeSFixed64(9, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeInt32(10, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeBytes(11, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeBytes(12, getOriginalInvoiceDateBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
output.writeBytes(13, getOriginalInvoiceRevisionNumberBytes());
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
output.writeBytes(14, getOriginalInvoiceRevisionDateBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getTotalIncBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getTotalDecBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getVatIncBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(5, getVatDecBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(6, getGroundsBytes());
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(7, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(8, currency_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeSFixed64Size(9, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(10, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(11, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(12, getOriginalInvoiceDateBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(13, getOriginalInvoiceRevisionNumberBytes());
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(14, getOriginalInvoiceRevisionDateBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata)
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.Builder.class);
}
// Construct using Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
bitField0_ = (bitField0_ & ~0x00000001);
totalInc_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
totalDec_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
vatInc_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
vatDec_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
grounds_ = "";
bitField0_ = (bitField0_ & ~0x00000020);
documentFunction_ = "";
bitField0_ = (bitField0_ & ~0x00000040);
currency_ = 0;
bitField0_ = (bitField0_ & ~0x00000080);
confirmationDateTimeTicks_ = 0L;
bitField0_ = (bitField0_ & ~0x00000100);
invoiceAmendmentFlags_ = 0;
bitField0_ = (bitField0_ & ~0x00000200);
originalInvoiceNumber_ = "";
bitField0_ = (bitField0_ & ~0x00000400);
originalInvoiceDate_ = "";
bitField0_ = (bitField0_ & ~0x00000800);
originalInvoiceRevisionNumber_ = "";
bitField0_ = (bitField0_ & ~0x00001000);
originalInvoiceRevisionDate_ = "";
bitField0_ = (bitField0_ & ~0x00002000);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata getDefaultInstanceForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.getDefaultInstance();
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata build() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata buildPartial() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata result = new Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.documentStatus_ = documentStatus_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.totalInc_ = totalInc_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.totalDec_ = totalDec_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.vatInc_ = vatInc_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.vatDec_ = vatDec_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.grounds_ = grounds_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.documentFunction_ = documentFunction_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.currency_ = currency_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.confirmationDateTimeTicks_ = confirmationDateTimeTicks_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.invoiceAmendmentFlags_ = invoiceAmendmentFlags_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.originalInvoiceNumber_ = originalInvoiceNumber_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.originalInvoiceDate_ = originalInvoiceDate_;
if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
to_bitField0_ |= 0x00001000;
}
result.originalInvoiceRevisionNumber_ = originalInvoiceRevisionNumber_;
if (((from_bitField0_ & 0x00002000) == 0x00002000)) {
to_bitField0_ |= 0x00002000;
}
result.originalInvoiceRevisionDate_ = originalInvoiceRevisionDate_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata) {
return mergeFrom((Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata other) {
if (other == Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata.getDefaultInstance()) return this;
if (other.hasDocumentStatus()) {
setDocumentStatus(other.getDocumentStatus());
}
if (other.hasTotalInc()) {
bitField0_ |= 0x00000002;
totalInc_ = other.totalInc_;
onChanged();
}
if (other.hasTotalDec()) {
bitField0_ |= 0x00000004;
totalDec_ = other.totalDec_;
onChanged();
}
if (other.hasVatInc()) {
bitField0_ |= 0x00000008;
vatInc_ = other.vatInc_;
onChanged();
}
if (other.hasVatDec()) {
bitField0_ |= 0x00000010;
vatDec_ = other.vatDec_;
onChanged();
}
if (other.hasGrounds()) {
bitField0_ |= 0x00000020;
grounds_ = other.grounds_;
onChanged();
}
if (other.hasDocumentFunction()) {
bitField0_ |= 0x00000040;
documentFunction_ = other.documentFunction_;
onChanged();
}
if (other.hasCurrency()) {
setCurrency(other.getCurrency());
}
if (other.hasConfirmationDateTimeTicks()) {
setConfirmationDateTimeTicks(other.getConfirmationDateTimeTicks());
}
if (other.hasInvoiceAmendmentFlags()) {
setInvoiceAmendmentFlags(other.getInvoiceAmendmentFlags());
}
if (other.hasOriginalInvoiceNumber()) {
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = other.originalInvoiceNumber_;
onChanged();
}
if (other.hasOriginalInvoiceDate()) {
bitField0_ |= 0x00000800;
originalInvoiceDate_ = other.originalInvoiceDate_;
onChanged();
}
if (other.hasOriginalInvoiceRevisionNumber()) {
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = other.originalInvoiceRevisionNumber_;
onChanged();
}
if (other.hasOriginalInvoiceRevisionDate()) {
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = other.originalInvoiceRevisionDate_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasDocumentStatus()) {
return false;
}
if (!hasTotalInc()) {
return false;
}
if (!hasTotalDec()) {
return false;
}
if (!hasVatInc()) {
return false;
}
if (!hasVatDec()) {
return false;
}
if (!hasDocumentFunction()) {
return false;
}
if (!hasCurrency()) {
return false;
}
if (!hasConfirmationDateTimeTicks()) {
return false;
}
if (!hasInvoiceAmendmentFlags()) {
return false;
}
if (!hasOriginalInvoiceNumber()) {
return false;
}
if (!hasOriginalInvoiceDate()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentMetadata) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder setDocumentStatus(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
documentStatus_ = value;
onChanged();
return this;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder clearDocumentStatus() {
bitField0_ = (bitField0_ & ~0x00000001);
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
onChanged();
return this;
}
private java.lang.Object totalInc_ = "";
/**
* <code>required string TotalInc = 2;</code>
*/
public boolean hasTotalInc() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string TotalInc = 2;</code>
*/
public java.lang.String getTotalInc() {
java.lang.Object ref = totalInc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalInc_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public com.google.protobuf.ByteString
getTotalIncBytes() {
java.lang.Object ref = totalInc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder setTotalInc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
totalInc_ = value;
onChanged();
return this;
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder clearTotalInc() {
bitField0_ = (bitField0_ & ~0x00000002);
totalInc_ = getDefaultInstance().getTotalInc();
onChanged();
return this;
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder setTotalIncBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
totalInc_ = value;
onChanged();
return this;
}
private java.lang.Object totalDec_ = "";
/**
* <code>required string TotalDec = 3;</code>
*/
public boolean hasTotalDec() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string TotalDec = 3;</code>
*/
public java.lang.String getTotalDec() {
java.lang.Object ref = totalDec_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalDec_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public com.google.protobuf.ByteString
getTotalDecBytes() {
java.lang.Object ref = totalDec_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder setTotalDec(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
totalDec_ = value;
onChanged();
return this;
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder clearTotalDec() {
bitField0_ = (bitField0_ & ~0x00000004);
totalDec_ = getDefaultInstance().getTotalDec();
onChanged();
return this;
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder setTotalDecBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
totalDec_ = value;
onChanged();
return this;
}
private java.lang.Object vatInc_ = "";
/**
* <code>required string VatInc = 4;</code>
*/
public boolean hasVatInc() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>required string VatInc = 4;</code>
*/
public java.lang.String getVatInc() {
java.lang.Object ref = vatInc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatInc_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public com.google.protobuf.ByteString
getVatIncBytes() {
java.lang.Object ref = vatInc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder setVatInc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
vatInc_ = value;
onChanged();
return this;
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder clearVatInc() {
bitField0_ = (bitField0_ & ~0x00000008);
vatInc_ = getDefaultInstance().getVatInc();
onChanged();
return this;
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder setVatIncBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
vatInc_ = value;
onChanged();
return this;
}
private java.lang.Object vatDec_ = "";
/**
* <code>required string VatDec = 5;</code>
*/
public boolean hasVatDec() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string VatDec = 5;</code>
*/
public java.lang.String getVatDec() {
java.lang.Object ref = vatDec_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatDec_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public com.google.protobuf.ByteString
getVatDecBytes() {
java.lang.Object ref = vatDec_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder setVatDec(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
vatDec_ = value;
onChanged();
return this;
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder clearVatDec() {
bitField0_ = (bitField0_ & ~0x00000010);
vatDec_ = getDefaultInstance().getVatDec();
onChanged();
return this;
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder setVatDecBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
vatDec_ = value;
onChanged();
return this;
}
private java.lang.Object grounds_ = "";
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGrounds(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
grounds_ = value;
onChanged();
return this;
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder clearGrounds() {
bitField0_ = (bitField0_ & ~0x00000020);
grounds_ = getDefaultInstance().getGrounds();
onChanged();
return this;
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGroundsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
grounds_ = value;
onChanged();
return this;
}
private java.lang.Object documentFunction_ = "";
/**
* <code>required string DocumentFunction = 7;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder setDocumentFunction(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
documentFunction_ = value;
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder clearDocumentFunction() {
bitField0_ = (bitField0_ & ~0x00000040);
documentFunction_ = getDefaultInstance().getDocumentFunction();
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder setDocumentFunctionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
documentFunction_ = value;
onChanged();
return this;
}
private int currency_ ;
/**
* <code>required int32 Currency = 8;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 Currency = 8;</code>
*/
public int getCurrency() {
return currency_;
}
/**
* <code>required int32 Currency = 8;</code>
*/
public Builder setCurrency(int value) {
bitField0_ |= 0x00000080;
currency_ = value;
onChanged();
return this;
}
/**
* <code>required int32 Currency = 8;</code>
*/
public Builder clearCurrency() {
bitField0_ = (bitField0_ & ~0x00000080);
currency_ = 0;
onChanged();
return this;
}
private long confirmationDateTimeTicks_ ;
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public Builder setConfirmationDateTimeTicks(long value) {
bitField0_ |= 0x00000100;
confirmationDateTimeTicks_ = value;
onChanged();
return this;
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public Builder clearConfirmationDateTimeTicks() {
bitField0_ = (bitField0_ & ~0x00000100);
confirmationDateTimeTicks_ = 0L;
onChanged();
return this;
}
private int invoiceAmendmentFlags_ ;
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public Builder setInvoiceAmendmentFlags(int value) {
bitField0_ |= 0x00000200;
invoiceAmendmentFlags_ = value;
onChanged();
return this;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public Builder clearInvoiceAmendmentFlags() {
bitField0_ = (bitField0_ & ~0x00000200);
invoiceAmendmentFlags_ = 0;
onChanged();
return this;
}
private java.lang.Object originalInvoiceNumber_ = "";
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder setOriginalInvoiceNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder clearOriginalInvoiceNumber() {
bitField0_ = (bitField0_ & ~0x00000400);
originalInvoiceNumber_ = getDefaultInstance().getOriginalInvoiceNumber();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder setOriginalInvoiceNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceDate_ = "";
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder setOriginalInvoiceDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000800;
originalInvoiceDate_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder clearOriginalInvoiceDate() {
bitField0_ = (bitField0_ & ~0x00000800);
originalInvoiceDate_ = getDefaultInstance().getOriginalInvoiceDate();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder setOriginalInvoiceDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000800;
originalInvoiceDate_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceRevisionNumber_ = "";
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public boolean hasOriginalInvoiceRevisionNumber() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public java.lang.String getOriginalInvoiceRevisionNumber() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder setOriginalInvoiceRevisionNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = value;
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder clearOriginalInvoiceRevisionNumber() {
bitField0_ = (bitField0_ & ~0x00001000);
originalInvoiceRevisionNumber_ = getDefaultInstance().getOriginalInvoiceRevisionNumber();
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder setOriginalInvoiceRevisionNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceRevisionDate_ = "";
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public boolean hasOriginalInvoiceRevisionDate() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public java.lang.String getOriginalInvoiceRevisionDate() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder setOriginalInvoiceRevisionDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = value;
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder clearOriginalInvoiceRevisionDate() {
bitField0_ = (bitField0_ & ~0x00002000);
originalInvoiceRevisionDate_ = getDefaultInstance().getOriginalInvoiceRevisionDate();
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder setOriginalInvoiceRevisionDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata)
}
static {
defaultInstance = new UniversalCorrectionDocumentMetadata(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentMetadata)
}
public interface UniversalCorrectionDocumentRevisionMetadataOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata)
com.google.protobuf.MessageOrBuilder {
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
boolean hasDocumentStatus();
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus();
/**
* <code>required string TotalInc = 2;</code>
*/
boolean hasTotalInc();
/**
* <code>required string TotalInc = 2;</code>
*/
java.lang.String getTotalInc();
/**
* <code>required string TotalInc = 2;</code>
*/
com.google.protobuf.ByteString
getTotalIncBytes();
/**
* <code>required string TotalDec = 3;</code>
*/
boolean hasTotalDec();
/**
* <code>required string TotalDec = 3;</code>
*/
java.lang.String getTotalDec();
/**
* <code>required string TotalDec = 3;</code>
*/
com.google.protobuf.ByteString
getTotalDecBytes();
/**
* <code>required string VatInc = 4;</code>
*/
boolean hasVatInc();
/**
* <code>required string VatInc = 4;</code>
*/
java.lang.String getVatInc();
/**
* <code>required string VatInc = 4;</code>
*/
com.google.protobuf.ByteString
getVatIncBytes();
/**
* <code>required string VatDec = 5;</code>
*/
boolean hasVatDec();
/**
* <code>required string VatDec = 5;</code>
*/
java.lang.String getVatDec();
/**
* <code>required string VatDec = 5;</code>
*/
com.google.protobuf.ByteString
getVatDecBytes();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
boolean hasGrounds();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
java.lang.String getGrounds();
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
com.google.protobuf.ByteString
getGroundsBytes();
/**
* <code>required string DocumentFunction = 7;</code>
*/
boolean hasDocumentFunction();
/**
* <code>required string DocumentFunction = 7;</code>
*/
java.lang.String getDocumentFunction();
/**
* <code>required string DocumentFunction = 7;</code>
*/
com.google.protobuf.ByteString
getDocumentFunctionBytes();
/**
* <code>required int32 Currency = 8;</code>
*/
boolean hasCurrency();
/**
* <code>required int32 Currency = 8;</code>
*/
int getCurrency();
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
boolean hasConfirmationDateTimeTicks();
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
long getConfirmationDateTimeTicks();
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
boolean hasInvoiceAmendmentFlags();
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
int getInvoiceAmendmentFlags();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
boolean hasOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
java.lang.String getOriginalInvoiceNumber();
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
boolean hasOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
java.lang.String getOriginalInvoiceDate();
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceDateBytes();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
boolean hasOriginalInvoiceRevisionNumber();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
java.lang.String getOriginalInvoiceRevisionNumber();
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
boolean hasOriginalInvoiceRevisionDate();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
java.lang.String getOriginalInvoiceRevisionDate();
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes();
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
boolean hasOriginalInvoiceCorrectionNumber();
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
java.lang.String getOriginalInvoiceCorrectionNumber();
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceCorrectionNumberBytes();
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
boolean hasOriginalInvoiceCorrectionDate();
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
java.lang.String getOriginalInvoiceCorrectionDate();
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
com.google.protobuf.ByteString
getOriginalInvoiceCorrectionDateBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata}
*/
public static final class UniversalCorrectionDocumentRevisionMetadata extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata)
UniversalCorrectionDocumentRevisionMetadataOrBuilder {
// Use UniversalCorrectionDocumentRevisionMetadata.newBuilder() to construct.
private UniversalCorrectionDocumentRevisionMetadata(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private UniversalCorrectionDocumentRevisionMetadata(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final UniversalCorrectionDocumentRevisionMetadata defaultInstance;
public static UniversalCorrectionDocumentRevisionMetadata getDefaultInstance() {
return defaultInstance;
}
public UniversalCorrectionDocumentRevisionMetadata getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private UniversalCorrectionDocumentRevisionMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
int rawValue = input.readEnum();
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.valueOf(rawValue);
if (value == null) {
unknownFields.mergeVarintField(1, rawValue);
} else {
bitField0_ |= 0x00000001;
documentStatus_ = value;
}
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
totalInc_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
totalDec_ = bs;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000008;
vatInc_ = bs;
break;
}
case 42: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000010;
vatDec_ = bs;
break;
}
case 50: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000020;
grounds_ = bs;
break;
}
case 58: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000040;
documentFunction_ = bs;
break;
}
case 64: {
bitField0_ |= 0x00000080;
currency_ = input.readInt32();
break;
}
case 73: {
bitField0_ |= 0x00000100;
confirmationDateTimeTicks_ = input.readSFixed64();
break;
}
case 80: {
bitField0_ |= 0x00000200;
invoiceAmendmentFlags_ = input.readInt32();
break;
}
case 90: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = bs;
break;
}
case 98: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000800;
originalInvoiceDate_ = bs;
break;
}
case 106: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = bs;
break;
}
case 114: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = bs;
break;
}
case 122: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00004000;
originalInvoiceCorrectionNumber_ = bs;
break;
}
case 130: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00008000;
originalInvoiceCorrectionDate_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.Builder.class);
}
public static com.google.protobuf.Parser<UniversalCorrectionDocumentRevisionMetadata> PARSER =
new com.google.protobuf.AbstractParser<UniversalCorrectionDocumentRevisionMetadata>() {
public UniversalCorrectionDocumentRevisionMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UniversalCorrectionDocumentRevisionMetadata(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<UniversalCorrectionDocumentRevisionMetadata> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int DOCUMENTSTATUS_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
public static final int TOTALINC_FIELD_NUMBER = 2;
private java.lang.Object totalInc_;
/**
* <code>required string TotalInc = 2;</code>
*/
public boolean hasTotalInc() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string TotalInc = 2;</code>
*/
public java.lang.String getTotalInc() {
java.lang.Object ref = totalInc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalInc_ = s;
}
return s;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public com.google.protobuf.ByteString
getTotalIncBytes() {
java.lang.Object ref = totalInc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TOTALDEC_FIELD_NUMBER = 3;
private java.lang.Object totalDec_;
/**
* <code>required string TotalDec = 3;</code>
*/
public boolean hasTotalDec() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string TotalDec = 3;</code>
*/
public java.lang.String getTotalDec() {
java.lang.Object ref = totalDec_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalDec_ = s;
}
return s;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public com.google.protobuf.ByteString
getTotalDecBytes() {
java.lang.Object ref = totalDec_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VATINC_FIELD_NUMBER = 4;
private java.lang.Object vatInc_;
/**
* <code>required string VatInc = 4;</code>
*/
public boolean hasVatInc() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>required string VatInc = 4;</code>
*/
public java.lang.String getVatInc() {
java.lang.Object ref = vatInc_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatInc_ = s;
}
return s;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public com.google.protobuf.ByteString
getVatIncBytes() {
java.lang.Object ref = vatInc_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VATDEC_FIELD_NUMBER = 5;
private java.lang.Object vatDec_;
/**
* <code>required string VatDec = 5;</code>
*/
public boolean hasVatDec() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string VatDec = 5;</code>
*/
public java.lang.String getVatDec() {
java.lang.Object ref = vatDec_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatDec_ = s;
}
return s;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public com.google.protobuf.ByteString
getVatDecBytes() {
java.lang.Object ref = vatDec_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int GROUNDS_FIELD_NUMBER = 6;
private java.lang.Object grounds_;
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DOCUMENTFUNCTION_FIELD_NUMBER = 7;
private java.lang.Object documentFunction_;
/**
* <code>required string DocumentFunction = 7;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CURRENCY_FIELD_NUMBER = 8;
private int currency_;
/**
* <code>required int32 Currency = 8;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 Currency = 8;</code>
*/
public int getCurrency() {
return currency_;
}
public static final int CONFIRMATIONDATETIMETICKS_FIELD_NUMBER = 9;
private long confirmationDateTimeTicks_;
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
public static final int INVOICEAMENDMENTFLAGS_FIELD_NUMBER = 10;
private int invoiceAmendmentFlags_;
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
public static final int ORIGINALINVOICENUMBER_FIELD_NUMBER = 11;
private java.lang.Object originalInvoiceNumber_;
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEDATE_FIELD_NUMBER = 12;
private java.lang.Object originalInvoiceDate_;
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEREVISIONNUMBER_FIELD_NUMBER = 13;
private java.lang.Object originalInvoiceRevisionNumber_;
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public boolean hasOriginalInvoiceRevisionNumber() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public java.lang.String getOriginalInvoiceRevisionNumber() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionNumber_ = s;
}
return s;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICEREVISIONDATE_FIELD_NUMBER = 14;
private java.lang.Object originalInvoiceRevisionDate_;
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public boolean hasOriginalInvoiceRevisionDate() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public java.lang.String getOriginalInvoiceRevisionDate() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionDate_ = s;
}
return s;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICECORRECTIONNUMBER_FIELD_NUMBER = 15;
private java.lang.Object originalInvoiceCorrectionNumber_;
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public boolean hasOriginalInvoiceCorrectionNumber() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public java.lang.String getOriginalInvoiceCorrectionNumber() {
java.lang.Object ref = originalInvoiceCorrectionNumber_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceCorrectionNumber_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceCorrectionNumberBytes() {
java.lang.Object ref = originalInvoiceCorrectionNumber_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceCorrectionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORIGINALINVOICECORRECTIONDATE_FIELD_NUMBER = 16;
private java.lang.Object originalInvoiceCorrectionDate_;
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public boolean hasOriginalInvoiceCorrectionDate() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public java.lang.String getOriginalInvoiceCorrectionDate() {
java.lang.Object ref = originalInvoiceCorrectionDate_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceCorrectionDate_ = s;
}
return s;
}
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceCorrectionDateBytes() {
java.lang.Object ref = originalInvoiceCorrectionDate_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceCorrectionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
totalInc_ = "";
totalDec_ = "";
vatInc_ = "";
vatDec_ = "";
grounds_ = "";
documentFunction_ = "";
currency_ = 0;
confirmationDateTimeTicks_ = 0L;
invoiceAmendmentFlags_ = 0;
originalInvoiceNumber_ = "";
originalInvoiceDate_ = "";
originalInvoiceRevisionNumber_ = "";
originalInvoiceRevisionDate_ = "";
originalInvoiceCorrectionNumber_ = "";
originalInvoiceCorrectionDate_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasDocumentStatus()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasTotalInc()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasTotalDec()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasVatInc()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasVatDec()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasDocumentFunction()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasCurrency()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasConfirmationDateTimeTicks()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasInvoiceAmendmentFlags()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceNumber()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceDate()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceCorrectionNumber()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasOriginalInvoiceCorrectionDate()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeEnum(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getTotalIncBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getTotalDecBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBytes(4, getVatIncBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBytes(5, getVatDecBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeBytes(6, getGroundsBytes());
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBytes(7, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(8, currency_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeSFixed64(9, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeInt32(10, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeBytes(11, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeBytes(12, getOriginalInvoiceDateBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
output.writeBytes(13, getOriginalInvoiceRevisionNumberBytes());
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
output.writeBytes(14, getOriginalInvoiceRevisionDateBytes());
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
output.writeBytes(15, getOriginalInvoiceCorrectionNumberBytes());
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
output.writeBytes(16, getOriginalInvoiceCorrectionDateBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(1, documentStatus_.getNumber());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getTotalIncBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getTotalDecBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(4, getVatIncBytes());
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(5, getVatDecBytes());
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(6, getGroundsBytes());
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(7, getDocumentFunctionBytes());
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(8, currency_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeSFixed64Size(9, confirmationDateTimeTicks_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(10, invoiceAmendmentFlags_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(11, getOriginalInvoiceNumberBytes());
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(12, getOriginalInvoiceDateBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(13, getOriginalInvoiceRevisionNumberBytes());
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(14, getOriginalInvoiceRevisionDateBytes());
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(15, getOriginalInvoiceCorrectionNumberBytes());
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(16, getOriginalInvoiceCorrectionDateBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata)
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.class, Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.Builder.class);
}
// Construct using Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
bitField0_ = (bitField0_ & ~0x00000001);
totalInc_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
totalDec_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
vatInc_ = "";
bitField0_ = (bitField0_ & ~0x00000008);
vatDec_ = "";
bitField0_ = (bitField0_ & ~0x00000010);
grounds_ = "";
bitField0_ = (bitField0_ & ~0x00000020);
documentFunction_ = "";
bitField0_ = (bitField0_ & ~0x00000040);
currency_ = 0;
bitField0_ = (bitField0_ & ~0x00000080);
confirmationDateTimeTicks_ = 0L;
bitField0_ = (bitField0_ & ~0x00000100);
invoiceAmendmentFlags_ = 0;
bitField0_ = (bitField0_ & ~0x00000200);
originalInvoiceNumber_ = "";
bitField0_ = (bitField0_ & ~0x00000400);
originalInvoiceDate_ = "";
bitField0_ = (bitField0_ & ~0x00000800);
originalInvoiceRevisionNumber_ = "";
bitField0_ = (bitField0_ & ~0x00001000);
originalInvoiceRevisionDate_ = "";
bitField0_ = (bitField0_ & ~0x00002000);
originalInvoiceCorrectionNumber_ = "";
bitField0_ = (bitField0_ & ~0x00004000);
originalInvoiceCorrectionDate_ = "";
bitField0_ = (bitField0_ & ~0x00008000);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata getDefaultInstanceForType() {
return Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.getDefaultInstance();
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata build() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata buildPartial() {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata result = new Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.documentStatus_ = documentStatus_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.totalInc_ = totalInc_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.totalDec_ = totalDec_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.vatInc_ = vatInc_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.vatDec_ = vatDec_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.grounds_ = grounds_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.documentFunction_ = documentFunction_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.currency_ = currency_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.confirmationDateTimeTicks_ = confirmationDateTimeTicks_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.invoiceAmendmentFlags_ = invoiceAmendmentFlags_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.originalInvoiceNumber_ = originalInvoiceNumber_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.originalInvoiceDate_ = originalInvoiceDate_;
if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
to_bitField0_ |= 0x00001000;
}
result.originalInvoiceRevisionNumber_ = originalInvoiceRevisionNumber_;
if (((from_bitField0_ & 0x00002000) == 0x00002000)) {
to_bitField0_ |= 0x00002000;
}
result.originalInvoiceRevisionDate_ = originalInvoiceRevisionDate_;
if (((from_bitField0_ & 0x00004000) == 0x00004000)) {
to_bitField0_ |= 0x00004000;
}
result.originalInvoiceCorrectionNumber_ = originalInvoiceCorrectionNumber_;
if (((from_bitField0_ & 0x00008000) == 0x00008000)) {
to_bitField0_ |= 0x00008000;
}
result.originalInvoiceCorrectionDate_ = originalInvoiceCorrectionDate_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata) {
return mergeFrom((Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata other) {
if (other == Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata.getDefaultInstance()) return this;
if (other.hasDocumentStatus()) {
setDocumentStatus(other.getDocumentStatus());
}
if (other.hasTotalInc()) {
bitField0_ |= 0x00000002;
totalInc_ = other.totalInc_;
onChanged();
}
if (other.hasTotalDec()) {
bitField0_ |= 0x00000004;
totalDec_ = other.totalDec_;
onChanged();
}
if (other.hasVatInc()) {
bitField0_ |= 0x00000008;
vatInc_ = other.vatInc_;
onChanged();
}
if (other.hasVatDec()) {
bitField0_ |= 0x00000010;
vatDec_ = other.vatDec_;
onChanged();
}
if (other.hasGrounds()) {
bitField0_ |= 0x00000020;
grounds_ = other.grounds_;
onChanged();
}
if (other.hasDocumentFunction()) {
bitField0_ |= 0x00000040;
documentFunction_ = other.documentFunction_;
onChanged();
}
if (other.hasCurrency()) {
setCurrency(other.getCurrency());
}
if (other.hasConfirmationDateTimeTicks()) {
setConfirmationDateTimeTicks(other.getConfirmationDateTimeTicks());
}
if (other.hasInvoiceAmendmentFlags()) {
setInvoiceAmendmentFlags(other.getInvoiceAmendmentFlags());
}
if (other.hasOriginalInvoiceNumber()) {
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = other.originalInvoiceNumber_;
onChanged();
}
if (other.hasOriginalInvoiceDate()) {
bitField0_ |= 0x00000800;
originalInvoiceDate_ = other.originalInvoiceDate_;
onChanged();
}
if (other.hasOriginalInvoiceRevisionNumber()) {
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = other.originalInvoiceRevisionNumber_;
onChanged();
}
if (other.hasOriginalInvoiceRevisionDate()) {
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = other.originalInvoiceRevisionDate_;
onChanged();
}
if (other.hasOriginalInvoiceCorrectionNumber()) {
bitField0_ |= 0x00004000;
originalInvoiceCorrectionNumber_ = other.originalInvoiceCorrectionNumber_;
onChanged();
}
if (other.hasOriginalInvoiceCorrectionDate()) {
bitField0_ |= 0x00008000;
originalInvoiceCorrectionDate_ = other.originalInvoiceCorrectionDate_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasDocumentStatus()) {
return false;
}
if (!hasTotalInc()) {
return false;
}
if (!hasTotalDec()) {
return false;
}
if (!hasVatInc()) {
return false;
}
if (!hasVatDec()) {
return false;
}
if (!hasDocumentFunction()) {
return false;
}
if (!hasCurrency()) {
return false;
}
if (!hasConfirmationDateTimeTicks()) {
return false;
}
if (!hasInvoiceAmendmentFlags()) {
return false;
}
if (!hasOriginalInvoiceNumber()) {
return false;
}
if (!hasOriginalInvoiceDate()) {
return false;
}
if (!hasOriginalInvoiceCorrectionNumber()) {
return false;
}
if (!hasOriginalInvoiceCorrectionDate()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalCorrectionDocumentRevisionMetadata) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public boolean hasDocumentStatus() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus getDocumentStatus() {
return documentStatus_;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder setDocumentStatus(Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
documentStatus_ = value;
onChanged();
return this;
}
/**
* <code>required .Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentStatus DocumentStatus = 1;</code>
*/
public Builder clearDocumentStatus() {
bitField0_ = (bitField0_ & ~0x00000001);
documentStatus_ = Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalTransferDocumentProtos.UniversalTransferDocumentStatus.UnknownDocumentStatus;
onChanged();
return this;
}
private java.lang.Object totalInc_ = "";
/**
* <code>required string TotalInc = 2;</code>
*/
public boolean hasTotalInc() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string TotalInc = 2;</code>
*/
public java.lang.String getTotalInc() {
java.lang.Object ref = totalInc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalInc_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public com.google.protobuf.ByteString
getTotalIncBytes() {
java.lang.Object ref = totalInc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder setTotalInc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
totalInc_ = value;
onChanged();
return this;
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder clearTotalInc() {
bitField0_ = (bitField0_ & ~0x00000002);
totalInc_ = getDefaultInstance().getTotalInc();
onChanged();
return this;
}
/**
* <code>required string TotalInc = 2;</code>
*/
public Builder setTotalIncBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
totalInc_ = value;
onChanged();
return this;
}
private java.lang.Object totalDec_ = "";
/**
* <code>required string TotalDec = 3;</code>
*/
public boolean hasTotalDec() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string TotalDec = 3;</code>
*/
public java.lang.String getTotalDec() {
java.lang.Object ref = totalDec_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
totalDec_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public com.google.protobuf.ByteString
getTotalDecBytes() {
java.lang.Object ref = totalDec_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
totalDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder setTotalDec(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
totalDec_ = value;
onChanged();
return this;
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder clearTotalDec() {
bitField0_ = (bitField0_ & ~0x00000004);
totalDec_ = getDefaultInstance().getTotalDec();
onChanged();
return this;
}
/**
* <code>required string TotalDec = 3;</code>
*/
public Builder setTotalDecBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
totalDec_ = value;
onChanged();
return this;
}
private java.lang.Object vatInc_ = "";
/**
* <code>required string VatInc = 4;</code>
*/
public boolean hasVatInc() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>required string VatInc = 4;</code>
*/
public java.lang.String getVatInc() {
java.lang.Object ref = vatInc_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatInc_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public com.google.protobuf.ByteString
getVatIncBytes() {
java.lang.Object ref = vatInc_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatInc_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder setVatInc(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
vatInc_ = value;
onChanged();
return this;
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder clearVatInc() {
bitField0_ = (bitField0_ & ~0x00000008);
vatInc_ = getDefaultInstance().getVatInc();
onChanged();
return this;
}
/**
* <code>required string VatInc = 4;</code>
*/
public Builder setVatIncBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
vatInc_ = value;
onChanged();
return this;
}
private java.lang.Object vatDec_ = "";
/**
* <code>required string VatDec = 5;</code>
*/
public boolean hasVatDec() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
/**
* <code>required string VatDec = 5;</code>
*/
public java.lang.String getVatDec() {
java.lang.Object ref = vatDec_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
vatDec_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public com.google.protobuf.ByteString
getVatDecBytes() {
java.lang.Object ref = vatDec_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vatDec_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder setVatDec(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
vatDec_ = value;
onChanged();
return this;
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder clearVatDec() {
bitField0_ = (bitField0_ & ~0x00000010);
vatDec_ = getDefaultInstance().getVatDec();
onChanged();
return this;
}
/**
* <code>required string VatDec = 5;</code>
*/
public Builder setVatDecBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000010;
vatDec_ = value;
onChanged();
return this;
}
private java.lang.Object grounds_ = "";
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public boolean hasGrounds() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public java.lang.String getGrounds() {
java.lang.Object ref = grounds_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
grounds_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public com.google.protobuf.ByteString
getGroundsBytes() {
java.lang.Object ref = grounds_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
grounds_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGrounds(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
grounds_ = value;
onChanged();
return this;
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder clearGrounds() {
bitField0_ = (bitField0_ & ~0x00000020);
grounds_ = getDefaultInstance().getGrounds();
onChanged();
return this;
}
/**
* <code>optional string Grounds = 6;</code>
*
* <pre>
* DocumentGrounds
* </pre>
*/
public Builder setGroundsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000020;
grounds_ = value;
onChanged();
return this;
}
private java.lang.Object documentFunction_ = "";
/**
* <code>required string DocumentFunction = 7;</code>
*/
public boolean hasDocumentFunction() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public java.lang.String getDocumentFunction() {
java.lang.Object ref = documentFunction_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
documentFunction_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public com.google.protobuf.ByteString
getDocumentFunctionBytes() {
java.lang.Object ref = documentFunction_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
documentFunction_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder setDocumentFunction(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
documentFunction_ = value;
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder clearDocumentFunction() {
bitField0_ = (bitField0_ & ~0x00000040);
documentFunction_ = getDefaultInstance().getDocumentFunction();
onChanged();
return this;
}
/**
* <code>required string DocumentFunction = 7;</code>
*/
public Builder setDocumentFunctionBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000040;
documentFunction_ = value;
onChanged();
return this;
}
private int currency_ ;
/**
* <code>required int32 Currency = 8;</code>
*/
public boolean hasCurrency() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
/**
* <code>required int32 Currency = 8;</code>
*/
public int getCurrency() {
return currency_;
}
/**
* <code>required int32 Currency = 8;</code>
*/
public Builder setCurrency(int value) {
bitField0_ |= 0x00000080;
currency_ = value;
onChanged();
return this;
}
/**
* <code>required int32 Currency = 8;</code>
*/
public Builder clearCurrency() {
bitField0_ = (bitField0_ & ~0x00000080);
currency_ = 0;
onChanged();
return this;
}
private long confirmationDateTimeTicks_ ;
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public boolean hasConfirmationDateTimeTicks() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public long getConfirmationDateTimeTicks() {
return confirmationDateTimeTicks_;
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public Builder setConfirmationDateTimeTicks(long value) {
bitField0_ |= 0x00000100;
confirmationDateTimeTicks_ = value;
onChanged();
return this;
}
/**
* <code>required sfixed64 ConfirmationDateTimeTicks = 9;</code>
*/
public Builder clearConfirmationDateTimeTicks() {
bitField0_ = (bitField0_ & ~0x00000100);
confirmationDateTimeTicks_ = 0L;
onChanged();
return this;
}
private int invoiceAmendmentFlags_ ;
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public boolean hasInvoiceAmendmentFlags() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public int getInvoiceAmendmentFlags() {
return invoiceAmendmentFlags_;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public Builder setInvoiceAmendmentFlags(int value) {
bitField0_ |= 0x00000200;
invoiceAmendmentFlags_ = value;
onChanged();
return this;
}
/**
* <code>required int32 InvoiceAmendmentFlags = 10;</code>
*/
public Builder clearInvoiceAmendmentFlags() {
bitField0_ = (bitField0_ & ~0x00000200);
invoiceAmendmentFlags_ = 0;
onChanged();
return this;
}
private java.lang.Object originalInvoiceNumber_ = "";
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public boolean hasOriginalInvoiceNumber() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public java.lang.String getOriginalInvoiceNumber() {
java.lang.Object ref = originalInvoiceNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceNumberBytes() {
java.lang.Object ref = originalInvoiceNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder setOriginalInvoiceNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder clearOriginalInvoiceNumber() {
bitField0_ = (bitField0_ & ~0x00000400);
originalInvoiceNumber_ = getDefaultInstance().getOriginalInvoiceNumber();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceNumber = 11;</code>
*/
public Builder setOriginalInvoiceNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000400;
originalInvoiceNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceDate_ = "";
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public boolean hasOriginalInvoiceDate() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public java.lang.String getOriginalInvoiceDate() {
java.lang.Object ref = originalInvoiceDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceDateBytes() {
java.lang.Object ref = originalInvoiceDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder setOriginalInvoiceDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000800;
originalInvoiceDate_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder clearOriginalInvoiceDate() {
bitField0_ = (bitField0_ & ~0x00000800);
originalInvoiceDate_ = getDefaultInstance().getOriginalInvoiceDate();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceDate = 12;</code>
*/
public Builder setOriginalInvoiceDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000800;
originalInvoiceDate_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceRevisionNumber_ = "";
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public boolean hasOriginalInvoiceRevisionNumber() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public java.lang.String getOriginalInvoiceRevisionNumber() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionNumberBytes() {
java.lang.Object ref = originalInvoiceRevisionNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder setOriginalInvoiceRevisionNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = value;
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder clearOriginalInvoiceRevisionNumber() {
bitField0_ = (bitField0_ & ~0x00001000);
originalInvoiceRevisionNumber_ = getDefaultInstance().getOriginalInvoiceRevisionNumber();
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionNumber = 13;</code>
*/
public Builder setOriginalInvoiceRevisionNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00001000;
originalInvoiceRevisionNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceRevisionDate_ = "";
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public boolean hasOriginalInvoiceRevisionDate() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public java.lang.String getOriginalInvoiceRevisionDate() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceRevisionDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceRevisionDateBytes() {
java.lang.Object ref = originalInvoiceRevisionDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceRevisionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder setOriginalInvoiceRevisionDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = value;
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder clearOriginalInvoiceRevisionDate() {
bitField0_ = (bitField0_ & ~0x00002000);
originalInvoiceRevisionDate_ = getDefaultInstance().getOriginalInvoiceRevisionDate();
onChanged();
return this;
}
/**
* <code>optional string OriginalInvoiceRevisionDate = 14;</code>
*/
public Builder setOriginalInvoiceRevisionDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00002000;
originalInvoiceRevisionDate_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceCorrectionNumber_ = "";
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public boolean hasOriginalInvoiceCorrectionNumber() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public java.lang.String getOriginalInvoiceCorrectionNumber() {
java.lang.Object ref = originalInvoiceCorrectionNumber_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceCorrectionNumber_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceCorrectionNumberBytes() {
java.lang.Object ref = originalInvoiceCorrectionNumber_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceCorrectionNumber_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public Builder setOriginalInvoiceCorrectionNumber(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00004000;
originalInvoiceCorrectionNumber_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public Builder clearOriginalInvoiceCorrectionNumber() {
bitField0_ = (bitField0_ & ~0x00004000);
originalInvoiceCorrectionNumber_ = getDefaultInstance().getOriginalInvoiceCorrectionNumber();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceCorrectionNumber = 15;</code>
*/
public Builder setOriginalInvoiceCorrectionNumberBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00004000;
originalInvoiceCorrectionNumber_ = value;
onChanged();
return this;
}
private java.lang.Object originalInvoiceCorrectionDate_ = "";
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public boolean hasOriginalInvoiceCorrectionDate() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public java.lang.String getOriginalInvoiceCorrectionDate() {
java.lang.Object ref = originalInvoiceCorrectionDate_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
originalInvoiceCorrectionDate_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public com.google.protobuf.ByteString
getOriginalInvoiceCorrectionDateBytes() {
java.lang.Object ref = originalInvoiceCorrectionDate_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
originalInvoiceCorrectionDate_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public Builder setOriginalInvoiceCorrectionDate(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00008000;
originalInvoiceCorrectionDate_ = value;
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public Builder clearOriginalInvoiceCorrectionDate() {
bitField0_ = (bitField0_ & ~0x00008000);
originalInvoiceCorrectionDate_ = getDefaultInstance().getOriginalInvoiceCorrectionDate();
onChanged();
return this;
}
/**
* <code>required string OriginalInvoiceCorrectionDate = 16;</code>
*/
public Builder setOriginalInvoiceCorrectionDateBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00008000;
originalInvoiceCorrectionDate_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata)
}
static {
defaultInstance = new UniversalCorrectionDocumentRevisionMetadata(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.Documents.UniversalTransferDocument.UniversalCorrectionDocumentRevisionMetadata)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n)Documents/UniversalTransferDocument.pr" +
"oto\0224Diadoc.Api.Proto.Documents.Universa" +
"lTransferDocument\"\305\002\n!UniversalTransferD" +
"ocumentMetadata\022\204\001\n\016DocumentStatus\030\001 \001(\016" +
"2U.Diadoc.Api.Proto.Documents.UniversalT" +
"ransferDocument.UniversalTransferDocumen" +
"tStatus:\025UnknownDocumentStatus\022\r\n\005Total\030" +
"\002 \002(\t\022\013\n\003Vat\030\003 \001(\t\022\017\n\007Grounds\030\004 \001(\t\022\030\n\020D" +
"ocumentFunction\030\005 \002(\t\022\020\n\010Currency\030\006 \002(\005\022" +
"!\n\031ConfirmationDateTimeTicks\030\010 \001(\020\022\035\n\025In",
"voiceAmendmentFlags\030\t \001(\005\"\361\002\n)UniversalT" +
"ransferDocumentRevisionMetadata\022m\n\016Docum" +
"entStatus\030\001 \002(\0162U.Diadoc.Api.Proto.Docum" +
"ents.UniversalTransferDocument.Universal" +
"TransferDocumentStatus\022\r\n\005Total\030\002 \002(\t\022\013\n" +
"\003Vat\030\003 \001(\t\022\017\n\007Grounds\030\004 \001(\t\022\030\n\020DocumentF" +
"unction\030\005 \002(\t\022\020\n\010Currency\030\006 \002(\005\022!\n\031Confi" +
"rmationDateTimeTicks\030\007 \001(\020\022\035\n\025InvoiceAme" +
"ndmentFlags\030\010 \002(\005\022\035\n\025OriginalInvoiceNumb" +
"er\030\t \002(\t\022\033\n\023OriginalInvoiceDate\030\n \002(\t\"\337\003",
"\n#UniversalCorrectionDocumentMetadata\022m\n" +
"\016DocumentStatus\030\001 \002(\0162U.Diadoc.Api.Proto" +
".Documents.UniversalTransferDocument.Uni" +
"versalTransferDocumentStatus\022\020\n\010TotalInc" +
"\030\002 \002(\t\022\020\n\010TotalDec\030\003 \002(\t\022\016\n\006VatInc\030\004 \002(\t" +
"\022\016\n\006VatDec\030\005 \002(\t\022\017\n\007Grounds\030\006 \001(\t\022\030\n\020Doc" +
"umentFunction\030\007 \002(\t\022\020\n\010Currency\030\010 \002(\005\022!\n" +
"\031ConfirmationDateTimeTicks\030\t \002(\020\022\035\n\025Invo" +
"iceAmendmentFlags\030\n \002(\005\022\035\n\025OriginalInvoi" +
"ceNumber\030\013 \002(\t\022\033\n\023OriginalInvoiceDate\030\014 ",
"\002(\t\022%\n\035OriginalInvoiceRevisionNumber\030\r \001" +
"(\t\022#\n\033OriginalInvoiceRevisionDate\030\016 \001(\t\"" +
"\267\004\n+UniversalCorrectionDocumentRevisionM" +
"etadata\022m\n\016DocumentStatus\030\001 \002(\0162U.Diadoc" +
".Api.Proto.Documents.UniversalTransferDo" +
"cument.UniversalTransferDocumentStatus\022\020" +
"\n\010TotalInc\030\002 \002(\t\022\020\n\010TotalDec\030\003 \002(\t\022\016\n\006Va" +
"tInc\030\004 \002(\t\022\016\n\006VatDec\030\005 \002(\t\022\017\n\007Grounds\030\006 " +
"\001(\t\022\030\n\020DocumentFunction\030\007 \002(\t\022\020\n\010Currenc" +
"y\030\010 \002(\005\022!\n\031ConfirmationDateTimeTicks\030\t \002",
"(\020\022\035\n\025InvoiceAmendmentFlags\030\n \002(\005\022\035\n\025Ori" +
"ginalInvoiceNumber\030\013 \002(\t\022\033\n\023OriginalInvo" +
"iceDate\030\014 \002(\t\022%\n\035OriginalInvoiceRevision" +
"Number\030\r \001(\t\022#\n\033OriginalInvoiceRevisionD" +
"ate\030\016 \001(\t\022\'\n\037OriginalInvoiceCorrectionNu" +
"mber\030\017 \002(\t\022%\n\035OriginalInvoiceCorrectionD" +
"ate\030\020 \002(\t*\341\004\n\037UniversalTransferDocumentS" +
"tatus\022\031\n\025UnknownDocumentStatus\020\000\022%\n!Outb" +
"oundWaitingForSenderSignature\020\001\0229\n5Outbo" +
"undWaitingForInvoiceReceiptAndRecipientS",
"ignature\020\002\022$\n OutboundWaitingForInvoiceR" +
"eceipt\020\003\022(\n$OutboundWaitingForRecipientS" +
"ignature\020\004\022\"\n\036OutboundWithRecipientSigna" +
"ture\020\005\022-\n)OutboundRecipientSignatureRequ" +
"estRejected\020\006\022\"\n\036OutboundInvalidSenderSi" +
"gnature\020\007\022\027\n\023OutboundNotFinished\020\010\022\024\n\020Ou" +
"tboundFinished\020\t\022\'\n#InboundWaitingForRec" +
"ipientSignature\020\020\022!\n\035InboundWithRecipien" +
"tSignature\020\021\022,\n(InboundRecipientSignatur" +
"eRequestRejected\020\022\022$\n InboundInvalidReci",
"pientSignature\020\023\022\026\n\022InboundNotFinished\020\024" +
"\022\023\n\017InboundFinished\020\025B!B\037UniversalTransf" +
"erDocumentProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentMetadata_descriptor,
new java.lang.String[] { "DocumentStatus", "Total", "Vat", "Grounds", "DocumentFunction", "Currency", "ConfirmationDateTimeTicks", "InvoiceAmendmentFlags", });
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalTransferDocumentRevisionMetadata_descriptor,
new java.lang.String[] { "DocumentStatus", "Total", "Vat", "Grounds", "DocumentFunction", "Currency", "ConfirmationDateTimeTicks", "InvoiceAmendmentFlags", "OriginalInvoiceNumber", "OriginalInvoiceDate", });
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentMetadata_descriptor,
new java.lang.String[] { "DocumentStatus", "TotalInc", "TotalDec", "VatInc", "VatDec", "Grounds", "DocumentFunction", "Currency", "ConfirmationDateTimeTicks", "InvoiceAmendmentFlags", "OriginalInvoiceNumber", "OriginalInvoiceDate", "OriginalInvoiceRevisionNumber", "OriginalInvoiceRevisionDate", });
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_Documents_UniversalTransferDocument_UniversalCorrectionDocumentRevisionMetadata_descriptor,
new java.lang.String[] { "DocumentStatus", "TotalInc", "TotalDec", "VatInc", "VatDec", "Grounds", "DocumentFunction", "Currency", "ConfirmationDateTimeTicks", "InvoiceAmendmentFlags", "OriginalInvoiceNumber", "OriginalInvoiceDate", "OriginalInvoiceRevisionNumber", "OriginalInvoiceRevisionDate", "OriginalInvoiceCorrectionNumber", "OriginalInvoiceCorrectionDate", });
}
// @@protoc_insertion_point(outer_class_scope)
}
| mit |
quchunguang/test | testjava/TIJ4-code/gui/SubmitLabelManipulationTask.java | 671 | //: gui/SubmitLabelManipulationTask.java
package gui; /* Added by Eclipse.py */
import javax.swing.*;
import java.util.concurrent.*;
public class SubmitLabelManipulationTask {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Hello Swing");
final JLabel label = new JLabel("A Label");
frame.add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 100);
frame.setVisible(true);
TimeUnit.SECONDS.sleep(1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText("Hey! This is Different!");
}
});
}
} ///:~
| mit |
patbos/jenkins | core/src/test/java/hudson/model/ChoiceParameterDefinitionTest.java | 1379 | package hudson.model;
import hudson.util.FormValidation;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class ChoiceParameterDefinitionTest {
@Test
public void shouldValidateChoices(){
assertFalse(ChoiceParameterDefinition.areValidChoices(""));
assertFalse(ChoiceParameterDefinition.areValidChoices(" "));
assertTrue(ChoiceParameterDefinition.areValidChoices("abc"));
assertTrue(ChoiceParameterDefinition.areValidChoices("abc\ndef"));
assertTrue(ChoiceParameterDefinition.areValidChoices("abc\r\ndef"));
}
@Test
public void testCheckChoices() throws Exception {
ChoiceParameterDefinition.DescriptorImpl descriptorImpl = new ChoiceParameterDefinition.DescriptorImpl();
assertEquals(FormValidation.Kind.OK, descriptorImpl.doCheckChoices("abc\ndef").kind);
assertEquals(FormValidation.Kind.ERROR, descriptorImpl.doCheckChoices("").kind);
}
@Test
@Issue("JENKINS-60721")
public void testNullDefaultParameter() {
ChoiceParameterDefinition param = new ChoiceParameterDefinition("name", new String[0], null);
assertNull(param.getDefaultParameterValue());
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_02_01/src/main/java/com/microsoft/azure/management/network/v2019_02_01/NetworkSecurityGroup.java | 8538 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_02_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_02_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.management.network.v2019_02_01.implementation.SecurityRuleInner;
import com.microsoft.azure.management.network.v2019_02_01.implementation.NetworkSecurityGroupInner;
/**
* Type representing NetworkSecurityGroup.
*/
public interface NetworkSecurityGroup extends HasInner<NetworkSecurityGroupInner>, Resource, GroupableResourceCore<NetworkManager, NetworkSecurityGroupInner>, HasResourceGroup, Refreshable<NetworkSecurityGroup>, Updatable<NetworkSecurityGroup.Update>, HasManager<NetworkManager> {
/**
* @return the defaultSecurityRules value.
*/
List<NetworkSecurityGroupSecurityRule> defaultSecurityRules();
/**
* @return the etag value.
*/
String etag();
/**
* @return the networkInterfaces value.
*/
List<NetworkInterface> networkInterfaces();
/**
* @return the provisioningState value.
*/
String provisioningState();
/**
* @return the resourceGuid value.
*/
String resourceGuid();
/**
* @return the securityRules value.
*/
List<NetworkSecurityGroupSecurityRule> securityRules();
/**
* @return the subnets value.
*/
List<Subnet> subnets();
/**
* The entirety of the NetworkSecurityGroup definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate {
}
/**
* Grouping of NetworkSecurityGroup definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a NetworkSecurityGroup definition.
*/
interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> {
}
/**
* The stage of the NetworkSecurityGroup definition allowing to specify the resource group.
*/
interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreate> {
}
/**
* The stage of the networksecuritygroup definition allowing to specify DefaultSecurityRules.
*/
interface WithDefaultSecurityRules {
/**
* Specifies defaultSecurityRules.
* @param defaultSecurityRules The default security rules of network security group
* @return the next definition stage
*/
WithCreate withDefaultSecurityRules(List<SecurityRuleInner> defaultSecurityRules);
}
/**
* The stage of the networksecuritygroup definition allowing to specify Etag.
*/
interface WithEtag {
/**
* Specifies etag.
* @param etag A unique read-only string that changes whenever the resource is updated
* @return the next definition stage
*/
WithCreate withEtag(String etag);
}
/**
* The stage of the networksecuritygroup definition allowing to specify ProvisioningState.
*/
interface WithProvisioningState {
/**
* Specifies provisioningState.
* @param provisioningState The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'
* @return the next definition stage
*/
WithCreate withProvisioningState(String provisioningState);
}
/**
* The stage of the networksecuritygroup definition allowing to specify ResourceGuid.
*/
interface WithResourceGuid {
/**
* Specifies resourceGuid.
* @param resourceGuid The resource GUID property of the network security group resource
* @return the next definition stage
*/
WithCreate withResourceGuid(String resourceGuid);
}
/**
* The stage of the networksecuritygroup definition allowing to specify SecurityRules.
*/
interface WithSecurityRules {
/**
* Specifies securityRules.
* @param securityRules A collection of security rules of the network security group
* @return the next definition stage
*/
WithCreate withSecurityRules(List<SecurityRuleInner> securityRules);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<NetworkSecurityGroup>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithDefaultSecurityRules, DefinitionStages.WithEtag, DefinitionStages.WithProvisioningState, DefinitionStages.WithResourceGuid, DefinitionStages.WithSecurityRules {
}
}
/**
* The template for a NetworkSecurityGroup update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<NetworkSecurityGroup>, Resource.UpdateWithTags<Update>, UpdateStages.WithDefaultSecurityRules, UpdateStages.WithEtag, UpdateStages.WithProvisioningState, UpdateStages.WithResourceGuid, UpdateStages.WithSecurityRules {
}
/**
* Grouping of NetworkSecurityGroup update stages.
*/
interface UpdateStages {
/**
* The stage of the networksecuritygroup update allowing to specify DefaultSecurityRules.
*/
interface WithDefaultSecurityRules {
/**
* Specifies defaultSecurityRules.
* @param defaultSecurityRules The default security rules of network security group
* @return the next update stage
*/
Update withDefaultSecurityRules(List<SecurityRuleInner> defaultSecurityRules);
}
/**
* The stage of the networksecuritygroup update allowing to specify Etag.
*/
interface WithEtag {
/**
* Specifies etag.
* @param etag A unique read-only string that changes whenever the resource is updated
* @return the next update stage
*/
Update withEtag(String etag);
}
/**
* The stage of the networksecuritygroup update allowing to specify ProvisioningState.
*/
interface WithProvisioningState {
/**
* Specifies provisioningState.
* @param provisioningState The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'
* @return the next update stage
*/
Update withProvisioningState(String provisioningState);
}
/**
* The stage of the networksecuritygroup update allowing to specify ResourceGuid.
*/
interface WithResourceGuid {
/**
* Specifies resourceGuid.
* @param resourceGuid The resource GUID property of the network security group resource
* @return the next update stage
*/
Update withResourceGuid(String resourceGuid);
}
/**
* The stage of the networksecuritygroup update allowing to specify SecurityRules.
*/
interface WithSecurityRules {
/**
* Specifies securityRules.
* @param securityRules A collection of security rules of the network security group
* @return the next update stage
*/
Update withSecurityRules(List<SecurityRuleInner> securityRules);
}
}
}
| mit |
eriqadams/computer-graphics | lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/templates/org/lwjgl/opengl/ARB_vertex_buffer_object.java | 2790 | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.opengl;
public interface ARB_vertex_buffer_object extends ARB_buffer_object {
/**
* Accepted by the <target> parameters of BindBufferARB, BufferDataARB,
* BufferSubDataARB, MapBufferARB, UnmapBufferARB,
* GetBufferSubDataARB, GetBufferParameterivARB, and
* GetBufferPointervARB:
*/
int GL_ARRAY_BUFFER_ARB = 0x8892;
int GL_ELEMENT_ARRAY_BUFFER_ARB = 0x8893;
/**
* Accepted by the <pname> parameter of GetBooleanv, GetIntegerv,
* GetFloatv, and GetDoublev:
*/
int GL_ARRAY_BUFFER_BINDING_ARB = 0x8894;
int GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB = 0x8895;
int GL_VERTEX_ARRAY_BUFFER_BINDING_ARB = 0x8896;
int GL_NORMAL_ARRAY_BUFFER_BINDING_ARB = 0x8897;
int GL_COLOR_ARRAY_BUFFER_BINDING_ARB = 0x8898;
int GL_INDEX_ARRAY_BUFFER_BINDING_ARB = 0x8899;
int GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB = 0x889A;
int GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB = 0x889B;
int GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB = 0x889C;
int GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB = 0x889D;
int GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB = 0x889E;
/**
* Accepted by the <pname> parameter of GetVertexAttribivARB:
*/
int GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB = 0x889F;
}
| mit |
DTL-FAIRData/FAIRifier | src/org/deri/grefine/rdf/vocab/VocabularySaveException.java | 250 | package org.deri.grefine.rdf.vocab;
import java.io.IOException;
@SuppressWarnings("serial")
public class VocabularySaveException extends IOException{
public VocabularySaveException(String message, Throwable cause) {
super(message, cause);
}
}
| mit |
GraphWalker/graphwalker-project | graphwalker-core/src/main/java/org/graphwalker/core/condition/StopConditionException.java | 1381 | package org.graphwalker.core.condition;
/*
* #%L
* GraphWalker Core
* %%
* Copyright (C) 2005 - 2014 GraphWalker
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
/**
* @author Nils Olsson
*/
public class StopConditionException extends RuntimeException {
public StopConditionException(String message) {
super(message);
}
}
| mit |
pplante/droidtowers | main/source/com/happydroids/droidtowers/gui/StatusBarPanel.java | 8324 | /*
* Copyright (c) 2012. HappyDroids LLC, All rights reserved.
*/
package com.happydroids.droidtowers.gui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Slider;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.google.common.eventbus.Subscribe;
import com.happydroids.droidtowers.Colors;
import com.happydroids.droidtowers.TowerAssetManager;
import com.happydroids.droidtowers.TowerConsts;
import com.happydroids.droidtowers.achievements.Achievement;
import com.happydroids.droidtowers.achievements.AchievementEngine;
import com.happydroids.droidtowers.entities.Player;
import com.happydroids.droidtowers.events.GameSpeedChangeEvent;
import com.happydroids.droidtowers.scenes.components.SceneManager;
import static com.happydroids.droidtowers.platform.Display.devicePixel;
import static com.happydroids.droidtowers.utils.StringUtils.formatNumber;
public class StatusBarPanel extends Table {
public static final float INACTIVE_BUTTON_ALPHA = 0.5f;
public static final float ACTIVE_BUTTON_ALPHA = 0.85f;
public static final float BUTTON_FADE_DURATION = 0.25f;
public static final int LINE_WIDTH = 2;
private final Label moneyLabel;
private final Label experienceLabel;
private final Label gameSpeedLabel;
private final Label populationLabel;
private final Label employmentLabel;
private final Label moneyIncomeLabel;
private final Label moneyExpensesLabel;
private final RatingBar starRatingBar;
private float lastUpdated = TowerConsts.HUD_UPDATE_FREQUENCY;
private float starRating;
private final PopOver starRatingPopOver;
private final Texture whiteSwatch;
private final PopOver gameSpeedOverlay;
private final Texture backgroundTexture;
private final Slider gameSpeedSlider;
private final Achievement dubai7StarWonder;
public StatusBarPanel() {
setTouchable(Touchable.childrenOnly);
moneyLabel = makeValueLabel("0");
moneyIncomeLabel = makeValueLabel("0");
moneyExpensesLabel = makeValueLabel("0");
experienceLabel = makeValueLabel("0");
populationLabel = makeValueLabel("0");
employmentLabel = makeValueLabel("0");
gameSpeedLabel = makeValueLabel(SceneManager.activeScene().getTimeMultiplier() + "x");
starRatingBar = new RatingBar(0, 5);
whiteSwatch = TowerAssetManager.texture(TowerAssetManager.WHITE_SWATCH);
backgroundTexture = TowerAssetManager.texture("hud/window-bg.png");
backgroundTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
defaults();
center();
row().pad(devicePixel(2)).padBottom(0);
add(makeHeader("COINS", Color.LIGHT_GRAY)).center();
add(makeHeader("INCOME", Color.LIGHT_GRAY)).center();
add(makeHeader("EXPENSES", Color.LIGHT_GRAY)).center();
add(makeHeader("POPULATION", Color.LIGHT_GRAY)).center();
add(makeHeader("EMPLOYMENT", Color.LIGHT_GRAY)).center();
Label gameSpeedHeader = makeHeader("GAME SPEED", Color.LIGHT_GRAY);
add(gameSpeedHeader).center();
Label starRatingHeader = makeHeader("STAR RATING", Color.LIGHT_GRAY);
add(starRatingHeader).center();
row().pad(devicePixel(2)).padTop(0);
add(moneyLabel);
add(moneyIncomeLabel);
add(moneyExpensesLabel);
add(populationLabel);
add(employmentLabel);
add(gameSpeedLabel);
add(starRatingBar);
if (TowerConsts.ENABLE_NEWS_TICKER) {
row().pad(devicePixel(2)).padLeft(devicePixel(-4)).padRight(devicePixel(-4));
add(new HorizontalRule(Colors.ICS_BLUE_SEMI_TRANSPARENT, 1)).fillX().colspan(7);
row().pad(0);
add(new NewsTickerPanel()).colspan(7).left();
}
dubai7StarWonder = AchievementEngine.instance().findById("dubai-7-star-wonder");
gameSpeedOverlay = new PopOver();
gameSpeedOverlay.alignArrow(Align.left);
gameSpeedOverlay.add(new Image(TowerAssetManager.textureFromAtlas("snail", "hud/buttons.txt"))).center();
gameSpeedSlider = new Slider(TowerConsts.GAME_SPEED_MIN, TowerConsts.GAME_SPEED_MAX, 0.5f, false, TowerAssetManager.getCustomSkin());
gameSpeedOverlay.add(gameSpeedSlider).width(devicePixel(150));
gameSpeedOverlay.add(new Image(TowerAssetManager.textureFromAtlas("rabbit", "hud/buttons.txt"))).center();
gameSpeedOverlay.pack();
gameSpeedOverlay.setVisible(false);
gameSpeedSlider.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
float remainder = gameSpeedSlider.getValue() * 2f / 2f;
SceneManager.activeScene().setTimeMultiplier(remainder);
}
});
SceneManager.activeScene().events().register(this);
starRatingPopOver = new TowerRatingPopOver();
starRatingPopOver.setVisible(false);
pack();
VibrateClickListener gameSpeedToggleListener = new VibrateClickListener() {
@Override
public void onClick(InputEvent event, float x, float y) {
gameSpeedOverlay.toggle(StatusBarPanel.this, gameSpeedLabel);
}
};
gameSpeedHeader.addListener(gameSpeedToggleListener);
gameSpeedLabel.addListener(gameSpeedToggleListener);
VibrateClickListener starRatingListener = new VibrateClickListener() {
@Override
public void onClick(InputEvent event, float x, float y) {
starRatingPopOver.toggle(StatusBarPanel.this, starRatingBar);
}
};
starRatingHeader.addListener(starRatingListener);
starRatingBar.addListener(starRatingListener);
setTouchable(Touchable.enabled);
addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
}
});
}
private Label makeValueLabel(String labelText) {
Label label = FontManager.RobotoBold18.makeLabel(labelText);
label.setAlignment(Align.center);
return label;
}
private Label makeHeader(String headerText, Color tint) {
Label label = FontManager.Roboto12.makeLabel(headerText);
label.setAlignment(Align.center);
label.setColor(tint);
return label;
}
@Override
public void act(float delta) {
super.act(delta);
lastUpdated += delta;
if (lastUpdated >= TowerConsts.HUD_UPDATE_FREQUENCY) {
lastUpdated = 0f;
Player player = Player.instance();
starRatingBar.setValue(player.getStarRating());
if (dubai7StarWonder.isCompleted() && starRatingBar.getMaxValue() == 5) {
starRatingBar.setMaxValue(7);
}
experienceLabel.setText(formatNumber(player.getExperience()));
moneyLabel.setText(TowerConsts.CURRENCY_SYMBOL + formatNumber(player.getCoins()));
moneyIncomeLabel.setText(TowerConsts.CURRENCY_SYMBOL + formatNumber(player.getCurrentIncome()));
moneyExpensesLabel.setText(TowerConsts.CURRENCY_SYMBOL + formatNumber(player.getCurrentExpenses()));
populationLabel.setText(formatNumber(player.getPopulationResidency()) + "/" + formatNumber(player.getMaxPopulation()));
employmentLabel.setText(formatNumber(player.getJobsFilled()) + "/" + formatNumber(player.getJobsMax()));
pack();
}
}
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
super.draw(batch, parentAlpha);
batch.setColor(Colors.ICS_BLUE_SEMI_TRANSPARENT);
batch.draw(whiteSwatch, getX(), getY() - LINE_WIDTH, getWidth(), LINE_WIDTH);
batch.draw(whiteSwatch, getX() + getWidth(), getY() - LINE_WIDTH, LINE_WIDTH, getHeight() + LINE_WIDTH * 2);
}
@Override
protected void drawBackground(SpriteBatch batch, float parentAlpha) {
batch.setColor(getColor());
batch.draw(backgroundTexture, getX(), getY(), getWidth(), getHeight());
}
@Subscribe
public void TowerScene_onGameSpeedChange(GameSpeedChangeEvent event) {
gameSpeedSlider.setValue(event.scene.getTimeMultiplier());
gameSpeedLabel.setText(event.scene.getTimeMultiplier() + "x");
}
}
| mit |