index
int64 0
0
| repo_id
stringlengths 9
205
| file_path
stringlengths 31
246
| content
stringlengths 1
12.2M
| __index_level_0__
int64 0
10k
|
---|---|---|---|---|
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/KEKRecipientInfo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1SequenceType;
/**
* KEKRecipientInfo ::= SEQUENCE {
* version CMSVersion, -- always set to 4
* kekid KEKIdentifier,
* keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
* encryptedKey EncryptedKey }
*/
public class KEKRecipientInfo extends Asn1SequenceType {
protected enum KEKRecipientInfoField implements EnumType {
VERSION,
KE_KID,
KEY_ENCRYPTION_ALGORITHM,
ENCRYPTED_KEY;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(KEKRecipientInfoField.VERSION, CmsVersion.class),
new Asn1FieldInfo(KEKRecipientInfoField.KE_KID, KEKIdentifier.class),
new Asn1FieldInfo(KEKRecipientInfoField.KEY_ENCRYPTION_ALGORITHM, KeyEncryptionAlgorithmIdentifier.class),
new Asn1FieldInfo(KEKRecipientInfoField.ENCRYPTED_KEY, EncryptedKey.class)
};
public KEKRecipientInfo() {
super(fieldInfos);
}
public CmsVersion getVersion() {
return getFieldAs(KEKRecipientInfoField.VERSION, CmsVersion.class);
}
public void setVersion(CmsVersion version) {
setFieldAs(KEKRecipientInfoField.VERSION, version);
}
public KEKIdentifier getKEKIdentifier() {
return getFieldAs(KEKRecipientInfoField.KE_KID, KEKIdentifier.class);
}
public void setKEKIdentifier(KEKIdentifier kekIdentifier) {
setFieldAs(KEKRecipientInfoField.KE_KID, kekIdentifier);
}
public KeyEncryptionAlgorithmIdentifier getKeyEncryptionAlgorithmIdentifier() {
return getFieldAs(KEKRecipientInfoField.KEY_ENCRYPTION_ALGORITHM, KeyEncryptionAlgorithmIdentifier.class);
}
public void setKeyEncryptionAlgorithmIdentifier(KeyEncryptionAlgorithmIdentifier
keyEncryptionAlgorithmIdentifier) {
setFieldAs(KEKRecipientInfoField.KEY_ENCRYPTION_ALGORITHM, keyEncryptionAlgorithmIdentifier);
}
public EncryptedKey getEncryptedKey() {
return getFieldAs(KEKRecipientInfoField.ENCRYPTED_KEY, EncryptedKey.class);
}
public void setEncryptedKey(EncryptedKey encryptedKey) {
setFieldAs(KEKRecipientInfoField.ENCRYPTED_KEY, encryptedKey);
}
}
| 600 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/SignerIdentifier.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.ImplicitField;
import org.apache.kerby.asn1.type.Asn1Choice;
import org.apache.kerby.x509.type.SubjectKeyIdentifier;
/**
* Ref. RFC 5652
* <pre>
* SignerIdentifier ::= CHOICE {
* issuerAndSerialNumber IssuerAndSerialNumber,
* subjectKeyIdentifier [0] SubjectKeyIdentifier
* }
*
* SubjectKeyIdentifier ::= OCTET STRING
* </pre>
*/
public class SignerIdentifier extends Asn1Choice {
protected enum SignerIdentifierField implements EnumType {
ISSUER_AND_SERIAL_NUMBER,
SUBJECT_KEY_IDENTIFIER;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[]{
new Asn1FieldInfo(SignerIdentifierField.ISSUER_AND_SERIAL_NUMBER, IssuerAndSerialNumber.class),
new ImplicitField(SignerIdentifierField.SUBJECT_KEY_IDENTIFIER, 0, SubjectKeyIdentifier.class)
};
public SignerIdentifier() {
super(fieldInfos);
}
public IssuerAndSerialNumber getIssuerAndSerialNumber() {
return getChoiceValueAs(SignerIdentifierField.ISSUER_AND_SERIAL_NUMBER, IssuerAndSerialNumber.class);
}
public void setIssuerAndSerialNumber(IssuerAndSerialNumber issuerAndSerialNumber) {
setChoiceValue(SignerIdentifierField.ISSUER_AND_SERIAL_NUMBER, issuerAndSerialNumber);
}
public SubjectKeyIdentifier getSubjectKeyIdentifier() {
return getChoiceValueAs(SignerIdentifierField.SUBJECT_KEY_IDENTIFIER, SubjectKeyIdentifier.class);
}
public void setSubjectKeyIdentifier(SubjectKeyIdentifier subjectKeyIdentifier) {
setChoiceValue(SignerIdentifierField.SUBJECT_KEY_IDENTIFIER, subjectKeyIdentifier);
}
}
| 601 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/CompressedData.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1SequenceType;
import org.apache.kerby.x509.type.AlgorithmIdentifier;
/**
* Ref. RFC 3274
*
* <pre>
* CompressedData ::= SEQUENCE {
* version CMSVersion,
* compressionAlgorithm CompressionAlgorithmIdentifier,
* encapContentInfo EncapsulatedContentInfo
* }
* </pre>
*/
public class CompressedData extends Asn1SequenceType {
protected enum CompressedDataField implements EnumType {
VERSION,
COMPRESSION_ALGORITHM,
ENCAP_CONTENT_INFO;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(CompressedDataField.VERSION, CmsVersion.class),
new Asn1FieldInfo(CompressedDataField.COMPRESSION_ALGORITHM, AlgorithmIdentifier.class),
new Asn1FieldInfo(CompressedDataField.ENCAP_CONTENT_INFO, EncapsulatedContentInfo.class)
};
public CompressedData() {
super(fieldInfos);
}
public CmsVersion getVersion() {
return getFieldAs(CompressedDataField.VERSION, CmsVersion.class);
}
public void setVersion(CmsVersion version) {
setFieldAs(CompressedDataField.VERSION, version);
}
public AlgorithmIdentifier getCompressionAlgorithm() {
return getFieldAs(CompressedDataField.COMPRESSION_ALGORITHM, AlgorithmIdentifier.class);
}
public void setCompressionAlgorithm(AlgorithmIdentifier compressionAlgorithm) {
setFieldAs(CompressedDataField.COMPRESSION_ALGORITHM, compressionAlgorithm);
}
public EncapsulatedContentInfo getEncapContentInfo() {
return getFieldAs(CompressedDataField.ENCAP_CONTENT_INFO, EncapsulatedContentInfo.class);
}
public void setEncapContentInfo(EncapsulatedContentInfo encapContentInfo) {
setFieldAs(CompressedDataField.ENCAP_CONTENT_INFO, encapContentInfo);
}
}
| 602 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/RevocationInfoChoice.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.ImplicitField;
import org.apache.kerby.asn1.type.Asn1Choice;
import org.apache.kerby.x509.type.CertificateList;
/**
* RevocationInfoChoice ::= CHOICE {
* crl CertificateList,
* other [1] IMPLICIT OtherRevocationInfoFormat
* }
*/
public class RevocationInfoChoice extends Asn1Choice {
protected enum RevocationInfoChoiceField implements EnumType {
CRL,
OTHER;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(RevocationInfoChoiceField.CRL, CertificateList.class),
new ImplicitField(RevocationInfoChoiceField.OTHER, OtherRevocationInfoFormat.class)
};
public RevocationInfoChoice() {
super(fieldInfos);
}
public CertificateList getCRL() {
return getChoiceValueAs(RevocationInfoChoiceField.CRL, CertificateList.class);
}
public void setCRL(CertificateList crl) {
setChoiceValue(RevocationInfoChoiceField.CRL, crl);
}
public OtherRevocationInfoFormat getOther() {
return getChoiceValueAs(RevocationInfoChoiceField.OTHER, OtherRevocationInfoFormat.class);
}
public void setOther(OtherRevocationInfoFormat other) {
setChoiceValue(RevocationInfoChoiceField.OTHER, other);
}
}
| 603 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/RecipientEncryptedKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1SequenceType;
/**
* RecipientEncryptedKey ::= SEQUENCE {
* rid KeyAgreeRecipientIdentifier,
* encryptedKey EncryptedKey }
*/
public class RecipientEncryptedKey extends Asn1SequenceType {
protected enum RecipientEncryptedKeyField implements EnumType {
RID,
ENCRYPTED_KEY;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(RecipientEncryptedKeyField.RID, KeyAgreeRecipientIdentifier.class),
new Asn1FieldInfo(RecipientEncryptedKeyField.ENCRYPTED_KEY, EncryptedKey.class)
};
public RecipientEncryptedKey() {
super(fieldInfos);
}
public KeyAgreeRecipientIdentifier getRid() {
return getFieldAs(RecipientEncryptedKeyField.RID, KeyAgreeRecipientIdentifier.class);
}
public void setRid(KeyAgreeRecipientIdentifier rid) {
setFieldAs(RecipientEncryptedKeyField.RID, rid);
}
public EncryptedKey getEncryptedKey() {
return getFieldAs(RecipientEncryptedKeyField.ENCRYPTED_KEY, EncryptedKey.class);
}
public void setEncryptedKey(EncryptedKey encryptedKey) {
setFieldAs(RecipientEncryptedKeyField.ENCRYPTED_KEY, encryptedKey);
}
}
| 604 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/OtherKeyAttribute.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1Any;
import org.apache.kerby.asn1.type.Asn1ObjectIdentifier;
import org.apache.kerby.asn1.type.Asn1SequenceType;
import org.apache.kerby.asn1.type.Asn1Type;
/**
* OtherKeyAttribute ::= SEQUENCE {
* keyAttrId OBJECT IDENTIFIER,
* keyAttr ANY DEFINED BY keyAttrId OPTIONAL }
*/
public class OtherKeyAttribute extends Asn1SequenceType {
protected enum OtherKeyAttributeField implements EnumType {
KEY_ATTR_ID,
KEY_ATTR;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(OtherKeyAttributeField.KEY_ATTR_ID, Asn1ObjectIdentifier.class),
new Asn1FieldInfo(OtherKeyAttributeField.KEY_ATTR, Asn1Any.class)
};
public OtherKeyAttribute() {
super(fieldInfos);
}
public Asn1ObjectIdentifier getAlgorithm() {
return getFieldAs(OtherKeyAttributeField.KEY_ATTR_ID, Asn1ObjectIdentifier.class);
}
public void setAlgorithm(Asn1ObjectIdentifier keyAttrId) {
setFieldAs(OtherKeyAttributeField.KEY_ATTR_ID, keyAttrId);
}
public <T extends Asn1Type> T getKeyAttrAs(Class<T> t) {
return getFieldAsAny(OtherKeyAttributeField.KEY_ATTR, t);
}
public void setKeyAttr(Asn1Type keyAttr) {
setFieldAsAny(OtherKeyAttributeField.KEY_ATTR, keyAttr);
}
}
| 605 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/RecipientIdentifier.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.ImplicitField;
import org.apache.kerby.asn1.type.Asn1Choice;
import org.apache.kerby.x509.type.SubjectKeyIdentifier;
/**
* RecipientIdentifier ::= CHOICE {
* issuerAndSerialNumber IssuerAndSerialNumber,
* subjectKeyIdentifier [0] SubjectKeyIdentifier
* }
*/
public class RecipientIdentifier extends Asn1Choice {
protected enum RecipientIdentifierField implements EnumType {
ISSUER_AND_SERIAL_NUMBER,
SUBJECT_KEY_IDENTIFIER;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[]{
new Asn1FieldInfo(RecipientIdentifierField.ISSUER_AND_SERIAL_NUMBER, IssuerAndSerialNumber.class),
new ImplicitField(RecipientIdentifierField.SUBJECT_KEY_IDENTIFIER, 0, SubjectKeyIdentifier.class)
};
public RecipientIdentifier() {
super(fieldInfos);
}
public IssuerAndSerialNumber getIssuerAndSerialNumber() {
return getChoiceValueAs(RecipientIdentifierField.ISSUER_AND_SERIAL_NUMBER, IssuerAndSerialNumber.class);
}
public void setIssuerAndSerialNumber(IssuerAndSerialNumber issuerAndSerialNumber) {
setChoiceValue(RecipientIdentifierField.ISSUER_AND_SERIAL_NUMBER, issuerAndSerialNumber);
}
public SubjectKeyIdentifier getSubjectKeyIdentifier() {
return getChoiceValueAs(RecipientIdentifierField.SUBJECT_KEY_IDENTIFIER, SubjectKeyIdentifier.class);
}
public void setSubjectKeyIdentifier(SubjectKeyIdentifier subjectKeyIdentifier) {
setChoiceValue(RecipientIdentifierField.SUBJECT_KEY_IDENTIFIER, subjectKeyIdentifier);
}
}
| 606 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/OtherCertificateFormat.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1Any;
import org.apache.kerby.asn1.type.Asn1ObjectIdentifier;
import org.apache.kerby.asn1.type.Asn1SequenceType;
import org.apache.kerby.asn1.type.Asn1Type;
/**
* OtherCertificateFormat ::= SEQUENCE {
* otherCertFormat OBJECT IDENTIFIER,
* otherCert ANY DEFINED BY otherCertFormat
* }
*/
public class OtherCertificateFormat extends Asn1SequenceType {
protected enum OtherCertificateFormatField implements EnumType {
OTHER_CERT_FORMAT,
OTHER_CERT;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(OtherCertificateFormatField.OTHER_CERT_FORMAT, Asn1ObjectIdentifier.class),
new Asn1FieldInfo(OtherCertificateFormatField.OTHER_CERT, Asn1Any.class),
};
public OtherCertificateFormat() {
super(fieldInfos);
}
public Asn1ObjectIdentifier getOtherCertFormat() {
return getFieldAs(OtherCertificateFormatField.OTHER_CERT_FORMAT, Asn1ObjectIdentifier.class);
}
public void setOtherCertFormat(Asn1ObjectIdentifier otherCertFormat) {
setFieldAs(OtherCertificateFormatField.OTHER_CERT_FORMAT, otherCertFormat);
}
public <T extends Asn1Type> T getOtherCertAs(Class<T> t) {
return getFieldAsAny(OtherCertificateFormatField.OTHER_CERT, t);
}
public void setOtherCert(Asn1Type otherCert) {
setFieldAsAny(OtherCertificateFormatField.OTHER_CERT, otherCert);
}
}
| 607 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/AttributeCertificateV1.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.asn1.Asn1FieldInfo;
import org.apache.kerby.asn1.EnumType;
import org.apache.kerby.asn1.type.Asn1BitString;
import org.apache.kerby.asn1.type.Asn1SequenceType;
import org.apache.kerby.x509.type.AlgorithmIdentifier;
import org.apache.kerby.x509.type.AttributeCertificateInfo;
/**
* AttributeCertificateV1 ::= SEQUENCE {
* acInfo AttributeCertificateInfoV1,
* signatureAlgorithm AlgorithmIdentifier,
* signature BIT STRING
* }
*/
public class AttributeCertificateV1 extends Asn1SequenceType {
protected enum AttributeCertificateV1Field implements EnumType {
ACI_INFO,
SIGNATURE_ALGORITHM,
SIGNATURE;
@Override
public int getValue() {
return ordinal();
}
@Override
public String getName() {
return name();
}
}
static Asn1FieldInfo[] fieldInfos = new Asn1FieldInfo[] {
new Asn1FieldInfo(AttributeCertificateV1Field.ACI_INFO, AttributeCertificateInfoV1.class),
new Asn1FieldInfo(AttributeCertificateV1Field.SIGNATURE_ALGORITHM, AlgorithmIdentifier.class),
new Asn1FieldInfo(AttributeCertificateV1Field.SIGNATURE, Asn1BitString.class)
};
public AttributeCertificateV1() {
super(fieldInfos);
}
public AttributeCertificateInfo getAcinfo() {
return getFieldAs(AttributeCertificateV1Field.ACI_INFO, AttributeCertificateInfo.class);
}
public void setAciInfo(AttributeCertificateInfo aciInfo) {
setFieldAs(AttributeCertificateV1Field.ACI_INFO, aciInfo);
}
public AlgorithmIdentifier getSignatureAlgorithm() {
return getFieldAs(AttributeCertificateV1Field.SIGNATURE_ALGORITHM, AlgorithmIdentifier.class);
}
public void setSignatureAlgorithm(AlgorithmIdentifier signatureAlgorithm) {
setFieldAs(AttributeCertificateV1Field.SIGNATURE_ALGORITHM, signatureAlgorithm);
}
public Asn1BitString getSignatureValue() {
return getFieldAs(AttributeCertificateV1Field.SIGNATURE, Asn1BitString.class);
}
public void setSignatureValue(Asn1BitString signatureValue) {
setFieldAs(AttributeCertificateV1Field.SIGNATURE, signatureValue);
}
}
| 608 |
0 | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms | Create_ds/directory-kerby/kerby-pkix/src/main/java/org/apache/kerby/cms/type/KeyEncryptionAlgorithmIdentifier.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.cms.type;
import org.apache.kerby.x509.type.AlgorithmIdentifier;
/**
* KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*/
public class KeyEncryptionAlgorithmIdentifier extends AlgorithmIdentifier {
}
| 609 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/ZookeeperBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.kerby.config.Conf;
import org.apache.kerby.kerberos.kdc.identitybackend.ZKConfKey;
import org.apache.kerby.kerberos.kdc.identitybackend.ZookeeperIdentityBackend;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import java.io.File;
/**
* Zookeeper backend test
*/
public class ZookeeperBackendTest extends BackendTestBase {
private static File instanceDir;
private static File dataDir;
@BeforeAll
public static void setup() throws KrbException {
Conf config = new Conf();
File testdir = new File(System.getProperty("test.dir", "target"));
instanceDir = new File(testdir, "zookeeper");
instanceDir.mkdirs();
dataDir = new File(instanceDir, "data");
dataDir.mkdirs();
config.setString(ZKConfKey.DATA_DIR.getPropertyKey(), dataDir.getAbsolutePath());
backend = new ZookeeperIdentityBackend(config);
backend.initialize();
backend.start();
}
@AfterAll
public static void tearDown() throws KrbException {
if (dataDir.exists()) {
dataDir.delete();
}
if (instanceDir.exists()) {
instanceDir.delete();
}
if (backend != null) {
backend.stop();
backend.release();
}
}
}
| 610 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/ZookeeperBackendKdcTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.kerby.kerberos.kdc.identitybackend.ZKConfKey;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
import org.apache.kerby.kerberos.kerb.server.KdcTestBase;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
public class ZookeeperBackendKdcTest extends KdcTestBase {
@Override
protected void prepareKdc() throws KrbException {
BackendConfig backendConfig = getKdcServer().getBackendConfig();
File testDir = getTestDir();
File instanceDir = new File(testDir, "zookeeper");
instanceDir.mkdirs();
File dataDir = new File(instanceDir, "data");
dataDir.mkdirs();
backendConfig.setString(ZKConfKey.DATA_DIR.getPropertyKey(), dataDir.getAbsolutePath());
backendConfig.setString(KdcConfigKey.KDC_IDENTITY_BACKEND,
"org.apache.kerby.kerberos.kdc.identitybackend.ZookeeperIdentityBackend");
super.prepareKdc();
}
@Test
public void testKdc() throws Exception {
TgtTicket tgt;
SgtTicket tkt;
try {
tgt = getKrbClient().requestTgt(
getClientPrincipal(), getClientPassword());
assertThat(tgt).isNotNull();
tkt = getKrbClient().requestSgt(tgt, getServerPrincipal());
assertThat(tkt).isNotNull();
} catch (Exception e) {
Assertions.fail("Exception occurred with good password. "
+ e.toString());
}
}
}
| 611 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/ZookeeperIdentityBackend.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.kerby.config.Config;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.backend.AbstractIdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
* A Zookeeper based backend implementation. Currently it uses an embedded
* Zookeeper. In follow up it will be enhanced to support standalone Zookeeper
* cluster for replication and reliability.
*
*/
public class ZookeeperIdentityBackend extends AbstractIdentityBackend {
private static Thread zookeeperThread;
private final ZooKeeperServerMain zooKeeperServer = new ZooKeeperServerMain();
private String zkHosts;
private int zkPort;
private String serverStr;
private File dataDir;
private ZooKeeper zooKeeper;
private static final Logger LOG = LoggerFactory.getLogger(ZookeeperIdentityBackend.class);
public ZookeeperIdentityBackend() {
}
/**
* Constructing an instance using specified config that contains anything
* to be used to init the Zookeeper backend.
* @param config The configuration for zookeeper identity backend.
*/
public ZookeeperIdentityBackend(Config config) {
setConfig(config);
}
/**
* {@inheritDoc}
*/
@Override
protected void doInitialize() throws KrbException {
LOG.info("Initializing the Zookeeper identity backend.");
init();
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() throws KrbException {
try {
zooKeeper.close();
} catch (InterruptedException e) {
LOG.error("Closing zookeeper interrupted." + e);
}
LOG.info("Zookeeper session closed.");
}
/**
* Init Zookeeper Server and connection service, used to initialize the backend.
*/
private void init() throws KrbException {
zkHosts = getConfig().getString(ZKConfKey.ZK_HOST, true);
zkPort = getConfig().getInt(ZKConfKey.ZK_PORT, true);
String[] array = zkHosts.split(",");
if (array.length == 1) {
serverStr = array[0] + ":" + zkPort;
} else {
serverStr = zkHosts;
for (int i = 0; i != array.length; ++i) {
serverStr = serverStr.replaceAll(array[i], array[i] + ":" + zkPort);
}
}
if (getConfig().getBoolean(ZKConfKey.EMBEDDED_ZK, true)) {
String dataDirString = getConfig().getString(ZKConfKey.DATA_DIR, true);
if (dataDirString == null || dataDirString.isEmpty()) {
File zooKeeperDir = new File(getBackendConfig().getConfDir(), "zookeeper");
dataDir = new File(zooKeeperDir, "data");
} else {
dataDir = new File(dataDirString);
}
if (!dataDir.exists() && !dataDir.mkdirs()) {
throw new KrbException("could not create data file dir " + dataDir);
}
LOG.info("Data dir: " + dataDir);
startEmbeddedZookeeper();
}
connectZK();
}
/**
* Prepare connection to Zookeeper server.
*/
private void connectZK() throws KrbException {
assert !serverStr.isEmpty() : " zkHosts may be empty ";
try {
zooKeeper = new ZooKeeper(serverStr, 10000, new MyWatcher());
while (true) {
if (!zooKeeper.getState().isConnected()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
LOG.error("Some thread has interrupted the current thread" + e);
}
} else {
LOG.info("Success connect to zookeeper server.");
break;
}
}
} catch (IOException e) {
LOG.error("Error occurred while connecting to zookeeper.");
throw new KrbException("Failed to prepare Zookeeper connection");
}
}
/**
* Start the Zookeeper server
*/
private void startEmbeddedZookeeper() throws KrbException {
assert dataDir != null : "data dir of embedded zk is null";
Properties startupProperties = new Properties();
startupProperties.put("dataDir", dataDir.getAbsolutePath());
startupProperties.put("clientPort", zkPort);
QuorumPeerConfig quorumConfiguration = new QuorumPeerConfig();
try {
quorumConfiguration.parseProperties(startupProperties);
} catch (Exception e) {
throw new KrbException("Loading quorum configuraiton failed", e);
}
final ServerConfig configuration = new ServerConfig();
configuration.readFrom(quorumConfiguration);
if (zookeeperThread == null) {
zookeeperThread = new Thread() {
public void run() {
try {
zooKeeperServer.runFromConfig(configuration);
} catch (org.apache.zookeeper.server.admin.AdminServer.AdminServerException | IOException e) {
LOG.warn(e.getMessage());
}
}
};
zookeeperThread.setDaemon(true);
zookeeperThread.start();
}
LOG.info("Embedded Zookeeper started.");
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doGetIdentity(String principalName) throws KrbException {
principalName = replaceSlash(principalName);
IdentityZNode identityZNode = new IdentityZNode(zooKeeper, principalName);
KrbIdentity krb = new KrbIdentity(principalName);
try {
if (!identityZNode.exist()) {
return null;
}
krb.setPrincipal(identityZNode.getPrincipalName());
krb.setCreatedTime(identityZNode.getCreatedTime());
krb.setDisabled(identityZNode.getDisabled());
krb.setExpireTime(identityZNode.getExpireTime());
krb.setKdcFlags(identityZNode.getKdcFlags());
krb.addKeys(identityZNode.getKeys());
krb.setKeyVersion(identityZNode.getKeyVersion());
krb.setLocked(identityZNode.getLocked());
} catch (KeeperException e) {
throw new KrbException("Fail to get identity from zookeeper", e);
}
return krb;
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException {
try {
setIdentity(identity);
} catch (Exception e) {
throw new KrbException("Fail to add identity to zookeeper", e);
}
return doGetIdentity(identity.getPrincipalName());
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException {
try {
setIdentity(identity);
} catch (Exception e) {
throw new KrbException("Fail to update identity in zookeeper", e);
}
return doGetIdentity(identity.getPrincipalName());
}
/**
* {@inheritDoc}
*/
@Override
protected void doDeleteIdentity(String principalName) throws KrbException {
principalName = replaceSlash(principalName);
IdentityZNode identityZNode = new IdentityZNode(zooKeeper, principalName);
try {
identityZNode.deleteIdentity();
} catch (KeeperException e) {
throw new KrbException("Fail to delete identity in zookeeper", e);
}
}
/**
* {@inheritDoc}
*/
@Override
protected Iterable<String> doGetIdentities() throws KrbException {
List<String> identityNames;
try {
// The identities getting from zookeeper is unordered
identityNames = IdentityZNodeHelper.getIdentityNames(zooKeeper);
} catch (KeeperException e) {
throw new KrbException("Fail to get identities from zookeeper", e);
}
if (identityNames == null || identityNames.isEmpty()) {
return null;
}
List<String> newIdentities = new ArrayList<>(identityNames.size());
for (String name : identityNames) {
if (name.contains("\\")) {
name = name.replace("\\", "/");
}
newIdentities.add(name);
}
Collections.sort(newIdentities);
return newIdentities;
}
/**
* Set the identity to add or update an indentity in the backend.
* @param identity . The identity to update
* @throws org.apache.zookeeper.KeeperException
*/
private void setIdentity(KrbIdentity identity) throws KeeperException, IOException {
String principalName = identity.getPrincipalName();
principalName = replaceSlash(principalName);
IdentityZNode identityZNode = new IdentityZNode(zooKeeper, principalName);
identityZNode.setPrincipalName(identity.getPrincipalName());
identityZNode.setCreatedTime(identity.getCreatedTime());
identityZNode.setDisabled(identity.isDisabled());
identityZNode.setExpireTime(identity.getExpireTime());
identityZNode.setKdcFlags(identity.getKdcFlags());
identityZNode.setKeys(identity.getKeys());
identityZNode.setKeyVersion(identity.getKeyVersion());
identityZNode.setLocked(identity.isLocked());
}
/**
* Use "\\" to replace "/" in a String object.
* @param name . The the name string to convert
* @return
*/
private String replaceSlash(String name) {
if (name.contains("/")) {
name = name.replace("/", "\\");
}
return name;
}
private static class MyWatcher implements Watcher {
/**
* This will watch all the kdb update event so that it's timely synced.
* @param event The kdb update event ot watch.
*/
public void process(WatchedEvent event) {
// System.out.println("I got an event: " + event.getPath());
}
}
}
| 612 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/IdentityZNode.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.kerby.kerberos.kerb.crypto.util.BytesUtil;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.util.Utf8;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class IdentityZNode {
private static final Logger LOG = LoggerFactory.getLogger(IdentityZNode.class);
private ZooKeeper zk;
private String identityName;
public IdentityZNode(ZooKeeper zk, String identityName) {
this.zk = zk;
this.identityName = identityName;
}
public boolean exist() throws KeeperException {
String znode = IdentityZNodeHelper.getIndentityZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
return false;
} else {
return true;
}
}
public PrincipalName getPrincipalName() throws KeeperException {
String znode = IdentityZNodeHelper.getPrincipalNameZnode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data;
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return null;
}
if (data != null) {
return new PrincipalName(Utf8.toString(data));
} else {
LOG.warn("can't get the date from znode: " + znode);
return null;
}
}
public void setPrincipalName(String principal) throws KeeperException {
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getPrincipalNameZnode(this.identityName),
Utf8.toBytes(principal));
}
public int getKeyVersion() throws KeeperException {
String znode = IdentityZNodeHelper.getKeyVersionZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
return BytesUtil.bytes2int(data, true);
} else {
LOG.warn("can't get the date from znode: " + znode);
return -1;
}
}
public void setKeyVersion(int keyVersion) throws KeeperException {
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getKeyVersionZNode(this.identityName),
BytesUtil.int2bytes(keyVersion, true));
}
public int getKdcFlags() throws KeeperException {
String znode = IdentityZNodeHelper.getKdcFlagsZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
return BytesUtil.bytes2int(data, true);
} else {
LOG.warn("can't get the date from znode: " + znode);
return -1;
}
}
public void setKdcFlags(int kdcFlags) throws KeeperException {
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getKdcFlagsZNode(this.identityName),
BytesUtil.int2bytes(kdcFlags, true));
}
public boolean getDisabled() throws KeeperException {
String znode = IdentityZNodeHelper.getDisabledZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
int disabled = BytesUtil.bytes2int(data, true);
return disabled == 1;
} else {
LOG.warn("can't get the date from znode: " + znode);
return false;
}
}
public void setDisabled(boolean disabled) throws KeeperException {
int value;
if (disabled) {
value = 1;
} else {
value = 0;
}
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getDisabledZNode(this.identityName),
BytesUtil.int2bytes(value, true));
}
public boolean getLocked() throws KeeperException {
String znode = IdentityZNodeHelper.getLockedZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
int locked = BytesUtil.bytes2int(data, true);
return locked == 1;
} else {
LOG.warn("can't get the date from znode: " + znode);
return false;
}
}
public void setLocked(boolean locked) throws KeeperException {
int value;
if (locked) {
value = 1;
} else {
value = 0;
}
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getLockedZNode(this.identityName),
BytesUtil.int2bytes(value, true));
}
public KerberosTime getExpireTime() throws KeeperException {
String znode = IdentityZNodeHelper.getExpireTimeZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
long time = BytesUtil.bytes2long(data, true);
return new KerberosTime(time);
} else {
LOG.warn("can't get the date from znode:" + znode);
return null;
}
}
public void setExpireTime(KerberosTime time) throws KeeperException {
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getExpireTimeZNode(this.identityName),
BytesUtil.long2bytes(time.getTime(), true));
}
public KerberosTime getCreatedTime() throws KeeperException {
String znode = IdentityZNodeHelper.getCreatedTimeZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
long time = BytesUtil.bytes2long(data, true);
return new KerberosTime(time);
} else {
LOG.warn("can't get the date from znode: " + znode);
return null;
}
}
public void setCreatedTime(KerberosTime time) throws KeeperException {
ZKUtil.createSetData(this.zk,
IdentityZNodeHelper.getCreatedTimeZNode(this.identityName),
BytesUtil.long2bytes(time.getTime(), true));
}
public EncryptionType getEncryptionKeyType(String type) throws KeeperException {
String znode = IdentityZNodeHelper.getEncryptionKeyTypeZNode(this.identityName, type);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
return EncryptionType.fromName(Utf8.toString(data));
} else {
LOG.warn("can't get the date from znode: " + znode);
return null;
}
}
public byte[] getEncryptionKey(String type) throws KeeperException {
String znode = IdentityZNodeHelper.getEncryptionKeyZNode(this.identityName, type);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data == null) {
LOG.warn("can't get the date from znode: " + znode);
}
return data;
}
public int getEncryptionKeyNo(String type) throws KeeperException {
String znode = IdentityZNodeHelper.getEncryptionKeyNoZNode(this.identityName, type);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
byte[] data = new byte[0];
try {
data = ZKUtil.getData(this.zk, znode);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (data != null) {
return BytesUtil.bytes2int(data, true);
} else {
LOG.warn("can't get the date from znode: " + znode);
return -1;
}
}
public List<EncryptionKey> getKeys() throws KeeperException {
String znode = IdentityZNodeHelper.getKeysZNode(this.identityName);
if (ZKUtil.checkExists(this.zk, znode) == -1) {
throw new IllegalArgumentException("The znode " + znode + " is not found");
}
List<String> typeNames = ZKUtil.listChildrenNoWatch(this.zk, znode);
List<EncryptionKey> keys = new ArrayList<>(typeNames.size());
for (String typeName : typeNames) {
byte[] key = getEncryptionKey(typeName);
EncryptionKey encryptionKey = new EncryptionKey();
try {
encryptionKey.decode(key);
} catch (IOException e) {
LOG.error("Fail to decode the encryption key. " + e);
}
encryptionKey.setKvno(getEncryptionKeyNo(typeName));
keys.add(encryptionKey);
}
return keys;
}
public void setKeys(Map<EncryptionType, EncryptionKey> keys) throws KeeperException, IOException {
if (ZKUtil.checkExists(this.zk, IdentityZNodeHelper.getKeysZNode(this.identityName)) == -1) {
ZKUtil.createWithParents(this.zk, IdentityZNodeHelper.getKeysZNode(this.identityName));
}
Iterator<Map.Entry<EncryptionType, EncryptionKey>> it = keys.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<EncryptionType, EncryptionKey> pair = it.next();
EncryptionType key = (EncryptionType) pair.getKey();
ZKUtil.createWithParents(this.zk, IdentityZNodeHelper.getKeyTypeZNode(this.identityName, key.getName()));
EncryptionKey value = (EncryptionKey) pair.getValue();
ZKUtil.createSetData(this.zk, IdentityZNodeHelper.getEncryptionKeyZNode(this.identityName, key.getName()),
value.encode());
ZKUtil.createSetData(this.zk, IdentityZNodeHelper.getEncryptionKeyNoZNode(this.identityName, key.getName()),
BytesUtil.int2bytes(value.getKvno(), true));
}
}
public void deleteIdentity() throws KeeperException {
ZKUtil.deleteNodeRecursively(this.zk, IdentityZNodeHelper.getIndentityZNode(this.identityName));
}
}
| 613 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/IdentityZNodeHelper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import java.util.List;
public class IdentityZNodeHelper {
private static final String IDENTITIES_ZNODE_NAME = "identities";
private static final String PRINCIPAL_NAME_ZNODE_NAME = "principalName";
private static final String KEY_VERSION_ZNODE_NAME = "keyVersion";
private static final String KDC_FLAGS_ZNODE_NAME = "kdcFlags";
private static final String DISABLED_ZNODE_NAME = "disabled";
private static final String LOCKED_ZNODE_NAME = "locked";
private static final String EXPIRE_TIME_ZNODE_NAME = "expireTime";
private static final String CREATED_TIME_ZNODE_NAME = "createdTime";
private static final String KEYS_ZNODE_NAME = "keys";
private static final String KEY_TYPE_ZNODE_NAME = "keyType";
private static final String KEY_ZNODE_NAME = "keyData";
private static final String ENCRYPTION_KEY_NO_ZNODE_NAME = "keyNo";
private static String baseZNode = "/kerby";
/**
* Get base znode.
* @return Base
*/
public static String getBaseZNode() {
return baseZNode;
}
/**
* Get identities znode.
* @return Identities.
*/
public static String getIdentitiesZNode() {
return ZKUtil.joinZNode(getBaseZNode(), IDENTITIES_ZNODE_NAME);
}
/**
* Get identity znode.
* @param principalName Principal name
* @return Identity
*/
public static String getIndentityZNode(String principalName) {
return ZKUtil.joinZNode(getIdentitiesZNode(), principalName);
}
/**
* Get principal name znode.
* @param principalName Principal name.
* @return Principal name
*/
public static String getPrincipalNameZnode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), PRINCIPAL_NAME_ZNODE_NAME);
}
/**
* Get key version znode.
* @param principalName Principal name.
* @return Key version
*/
public static String getKeyVersionZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), KEY_VERSION_ZNODE_NAME);
}
/**
* Get kdc flags znode.
* @param principalName Principal name.
* @return Kdc flags
*/
public static String getKdcFlagsZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), KDC_FLAGS_ZNODE_NAME);
}
/**
* Get disabled znode.
* @param principalName Principal name.
* @return Whether this principal's account is disabled.
*/
public static String getDisabledZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), DISABLED_ZNODE_NAME);
}
/**
* Get locked znode.
* @param principalName Principal name.
* @return Whether principal's account is locked
*/
public static String getLockedZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), LOCKED_ZNODE_NAME);
}
/**
* Get expire time znode.
* @param principalName Principal name.
* @return Expired time.
*/
public static String getExpireTimeZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), EXPIRE_TIME_ZNODE_NAME);
}
/**
* Get created time znode.
* @param principalName Principal name.
* @return Created time.
*/
public static String getCreatedTimeZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), CREATED_TIME_ZNODE_NAME);
}
/**
* Get keys znode.
* @param principalName Principal name.
* @return Key
*/
public static String getKeysZNode(String principalName) {
return ZKUtil.joinZNode(getIndentityZNode(principalName), KEYS_ZNODE_NAME);
}
/**
* Get key type znode.
* @param principalName Principal name.
* @param type Key type.
* @return Key type.
*/
public static String getKeyTypeZNode(String principalName, String type) {
return ZKUtil.joinZNode(getKeysZNode(principalName), type);
}
/**
* Get encryption key type znode.
* @param principalName Principal name.
* @param type Encryption type.
* @return Encryption key type
*/
public static String getEncryptionKeyTypeZNode(String principalName, String type) {
return ZKUtil.joinZNode(getKeyTypeZNode(principalName, type), KEY_TYPE_ZNODE_NAME);
}
/**
* Get encryption key znode.
* @param principalName Principal Name.
* @param type Encryption type.
* @return Encryption key
*/
public static String getEncryptionKeyZNode(String principalName, String type) {
return ZKUtil.joinZNode(getKeyTypeZNode(principalName, type), KEY_ZNODE_NAME);
}
/**
* Get encryption key kvno znode.
* @param principalName Principal name.
* @param type Key type.
* @return Encryption key
*/
public static String getEncryptionKeyNoZNode(String principalName, String type) {
return ZKUtil.joinZNode(getKeyTypeZNode(principalName, type), ENCRYPTION_KEY_NO_ZNODE_NAME);
}
/**
* Get identity names.
*
* @throws org.apache.zookeeper.KeeperException e
* @param zk The zookeeper
* @return The list of principal names.
*/
public static List<String> getIdentityNames(ZooKeeper zk) throws KeeperException {
List<String> identityNames = ZKUtil.listChildrenNoWatch(zk, getIdentitiesZNode());
return identityNames;
}
} | 614 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/ZKUtil.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* utility class for ZooKeeper
*/
public class ZKUtil {
public static final char ZNODE_PATH_SEPARATOR = '/';
private static final Logger LOG = LoggerFactory.getLogger(ZKUtil.class);
public static String joinZNode(String prefix, String suffix) {
return prefix + ZNODE_PATH_SEPARATOR + suffix;
}
/**
* Check if the specified node exists. Sets no watches.
* @throws org.apache.zookeeper.KeeperException e
* @param zk Zookeeper.
* @param node Node.
* @return The version.
*/
public static int checkExists(ZooKeeper zk, String node)
throws KeeperException {
try {
Stat s = zk.exists(node, null);
return s != null ? s.getVersion() : -1;
} catch (KeeperException e) {
return -1;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return -1;
}
}
/**
* Sets the data of the existing znode to be the specified data.
* @throws org.apache.zookeeper.KeeperException e
* @param zk Zookeeper
* @param node Node
* @param data Data
* @return Whether the data is set or not.
*/
public static boolean setData(ZooKeeper zk, String node, byte[] data)
throws KeeperException {
try {
return zk.setData(node, data, -1) != null;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
/**
* Set data into node creating node if it doesn't yet exist.
* Does not set watch.
* @param zk Zookeeper.
* @param node Node.
* @param data Data.
* @throws KeeperException e
*/
public static void createSetData(final ZooKeeper zk, final String node,
final byte[] data)
throws KeeperException {
if (checkExists(zk, node) == -1) {
ZKUtil.createWithParents(zk, node, data);
} else {
ZKUtil.setData(zk, node, data);
}
}
/**
* Creates the specified node and all parent nodes required for it to exist.
* @param zk The zookeeper
* @param node The znode
* @throws org.apache.zookeeper.KeeperException e
*/
public static void createWithParents(ZooKeeper zk, String node)
throws KeeperException {
createWithParents(zk, node, new byte[0]);
}
/**
* Creates the specified node and all parent nodes required for it to exist. The creation of
* parent znodes is not atomic with the leafe znode creation but the data is written atomically
* when the leaf node is created.
* @throws org.apache.zookeeper.KeeperException e
* @param zk zookeeper.
* @param node node
* @param data data
*/
public static void createWithParents(ZooKeeper zk, String node, byte[] data)
throws KeeperException {
try {
if (node == null) {
return;
}
zk.create(node, data, createACL(zk, node),
CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException nee) {
return;
} catch (KeeperException.NoNodeException nne) {
createWithParents(zk, getParent(node));
createWithParents(zk, node, data);
} catch (InterruptedException ie) {
LOG.warn("Fail to create node: " + node, ie);
}
}
/**
* Returns the ACL list
* @param zk zookeeper
* @param node node
* @return The acl created.
*/
private static ArrayList<ACL> createACL(ZooKeeper zk, String node) { //NOPMD
return ZooDefs.Ids.OPEN_ACL_UNSAFE; //TODO
}
/**
* Returns the full path of the immediate parent of the specified node.
* null if passed the root node or an invalid node
* @param node The znode
* @return index
*/
public static String getParent(String node) {
int idx = node.lastIndexOf(ZNODE_PATH_SEPARATOR);
return idx <= 0 ? null : node.substring(0, idx);
}
/**
* Get znode data. Does not set a watcher.
* @param zk The zookeeper
* @param node The znode
* @throws org.apache.zookeeper.KeeperException e
* @throws java.lang.InterruptedException e
* @return Data of the node
*/
public static byte[] getData(ZooKeeper zk, String node)
throws KeeperException, InterruptedException {
try {
byte[] data = zk.getData(node, false, null);
return data;
} catch (KeeperException.NoNodeException e) {
LOG.debug("Unable to get data of znode " + node + " because node does not exist");
return null;
} catch (KeeperException e) {
LOG.warn("Unable to get data of znode " + node, e);
return null;
}
}
/**
* Lists the children of the specified node without setting any watches.
* null if parent does not exist
* @param zk The zookeeper.
* @param node The znode
* @throws org.apache.zookeeper.KeeperException e
* @return children
*/
public static List<String> listChildrenNoWatch(ZooKeeper zk, String node)
throws KeeperException {
List<String> children = null;
try {
// List the children without watching
children = zk.getChildren(node, null);
} catch (KeeperException.NoNodeException nne) {
return null;
} catch (InterruptedException ie) {
LOG.warn("Fail to list children of node: " + node, ie);
}
return children;
}
/**
* Delete the specified node and all of it's children.
* If the node does not exist, just returns.
* Sets no watches. Throws all exceptions besides dealing with deletion of
* children.
* @throws KeeperException e
* @param zk The zookeeper.
* @param node The node to be deleted.
*/
public static void deleteNodeRecursively(ZooKeeper zk, String node) throws KeeperException {
List<String> children = ZKUtil.listChildrenNoWatch(zk, node);
if (children == null) {
return;
}
if (!children.isEmpty()) {
for (String child : children) {
deleteNodeRecursively(zk, joinZNode(node, child));
}
}
try {
zk.delete(node, -1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} | 615 |
0 | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/zookeeper-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/ZKConfKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.kerby.config.ConfigKey;
/**
* Define all the ZK backend related configuration items with default values.
*/
public enum ZKConfKey implements ConfigKey {
EMBEDDED_ZK(true),
ZK_HOST("127.0.0.1"),
ZK_PORT(2180),
DATA_DIR("/tmp/kerby/zookeeper/data");
private Object defaultValue;
ZKConfKey() {
this.defaultValue = null;
}
ZKConfKey(Object defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public String getPropertyKey() {
return name().toLowerCase();
}
@Override
public Object getDefaultValue() {
return this.defaultValue;
}
}
| 616 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/AbstractLdapIdentityBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.kerby.kerberos.kdc.identitybackend.LdapIdentityBackend;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public abstract class AbstractLdapIdentityBackendTest extends AbstractLdapTestUnit {
protected LdapIdentityBackend backend;
/** The used DirectoryService instance */
private static DirectoryService service;
public static DirectoryService getDirectoryService() {
return service;
}
public static void setDirectoryService(DirectoryService service) {
AbstractLdapIdentityBackendTest.service = service;
}
private BackendTest test = new LdapBackendTest();
@AfterEach
public void tearDown() throws Exception {
backend.stop();
backend.release();
}
@Test
public void testGet() throws KrbException {
test.testGet(backend);
}
@Test
public void testStore() throws KrbException {
test.testStore(backend);
}
@Test
public void testUpdate() throws KrbException {
test.testUpdate(backend);
}
@Test
public void testDelete() throws KrbException {
test.testDelete(backend);
}
@Test
public void testGetIdentities() throws KrbException {
test.testGetIdentities(backend);
}
private static class LdapBackendTest extends BackendTest {
}
}
| 617 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/AbstractLdapBackendKdcTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.directory.server.core.api.DirectoryService;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.client.KrbClient;
import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
import org.apache.kerby.kerberos.kerb.server.KdcTestBase;
import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer;
public class AbstractLdapBackendKdcTest extends AbstractLdapTestUnit {
protected static final String BASE_DN = "ou=users,dc=example,dc=com";
protected static final String ADMIN_DN = "uid=admin,ou=system";
protected static final String ADMIN_PW = "secret";
/** The used DirectoryService instance */
private static DirectoryService service;
protected LdapKdcTestBase test = new LdapKdcTestBase();
public static DirectoryService getDirectoryService() {
return service;
}
public static void setDirectoryService(DirectoryService service) {
AbstractLdapBackendKdcTest.service = service;
}
protected class LdapKdcTestBase extends KdcTestBase {
private int port;
public void setPort(int port) {
this.port = port;
}
@Override
public SimpleKdcServer getKdcServer() { //NOPMD
return super.getKdcServer();
}
@Override
public KrbClient getKrbClient() { //NOPMD
return super.getKrbClient();
}
@Override
public String getClientPrincipal() { //NOPMD
return super.getClientPrincipal();
}
@Override
public String getClientPassword() { //NOPMD
return super.getClientPassword();
}
@Override
public String getServerPrincipal() { //NOPMD
return super.getServerPrincipal();
}
@Override
public void prepareKdc() throws KrbException {
BackendConfig backendConfig = getKdcServer().getBackendConfig();
backendConfig.setString("host", "localhost");
backendConfig.setString("admin_dn", ADMIN_DN);
backendConfig.setString("admin_pw", ADMIN_PW);
backendConfig.setString("base_dn", BASE_DN);
backendConfig.setInt("port", port);
backendConfig.setString(KdcConfigKey.KDC_IDENTITY_BACKEND,
"org.apache.kerby.kerberos.kdc.identitybackend.LdapIdentityBackend");
super.prepareKdc();
}
}
}
| 618 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/LdapIdentityBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifs;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.ApacheDSTestExtension;
import org.apache.kerby.config.Conf;
import org.apache.kerby.kerberos.kdc.identitybackend.LdapIdentityBackend;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith({ ApacheDSTestExtension.class })
@CreateDS(name = "KerberosKRBProtocolTest-class",
partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com")
})
@CreateLdapServer(
transports =
{
@CreateTransport(protocol = "LDAP", address = "127.0.0.1")
})
@ApplyLdifs(
{
"dn: dc=example,dc=com",
"objectClass: top",
"objectClass: domain",
"dc: example",
"dn: ou=users,dc=example,dc=com",
"objectClass: top",
"objectClass: organizationalUnit",
"ou: users"
}
)
public class LdapIdentityBackendTest extends AbstractLdapIdentityBackendTest {
private static final String BASE_DN = "ou=users,dc=example,dc=com";
private static final String ADMIN_DN = "uid=admin,ou=system";
private static final String ADMIN_PW = "secret";
@BeforeEach
public void setUp() throws Exception {
Conf config = new Conf();
config.setString("host", "127.0.0.1");
config.setInt("port", getLdapServer().getPort());
config.setString("admin_dn", ADMIN_DN);
config.setString("admin_pw", ADMIN_PW);
config.setString("base_dn", BASE_DN);
backend = new LdapIdentityBackend(config);
backend.initialize();
backend.start();
}
} | 619 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/DirectoryLdapIdentityBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifs;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.api.LdapCoreSessionConnection;
import org.apache.directory.server.core.integ.ApacheDSTestExtension;
import org.apache.kerby.config.Conf;
import org.apache.kerby.kerberos.kdc.identitybackend.LdapIdentityBackend;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith({ ApacheDSTestExtension.class })
@CreateDS(name = "KerberosKRBProtocolTest-class",
partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com")
})
@CreateLdapServer(
transports =
{
@CreateTransport(protocol = "LDAP", address = "127.0.0.1")
})
@ApplyLdifs(
{
"dn: dc=example,dc=com",
"objectClass: top",
"objectClass: domain",
"dc: example",
"dn: ou=users,dc=example,dc=com",
"objectClass: top",
"objectClass: organizationalUnit",
"ou: users"
}
)
public class DirectoryLdapIdentityBackendTest extends AbstractLdapIdentityBackendTest {
private static final String BASE_DN = "ou=users,dc=example,dc=com";
private static final String ADMIN_DN = "uid=admin,ou=system";
private static final String ADMIN_PW = "secret";
@BeforeEach
public void setUp() throws Exception {
Conf config = new Conf();
config.setString("admin_dn", ADMIN_DN);
config.setString("admin_pw", ADMIN_PW);
config.setString("base_dn", BASE_DN);
LdapConnection connection = new LdapCoreSessionConnection(getService());
backend = new LdapIdentityBackend(config, connection);
backend.initialize();
backend.start();
}
} | 620 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/LdapBackendKdcTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifs;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.ApacheDSTestExtension;
import org.apache.kerby.config.Conf;
import org.apache.kerby.kerberos.kdc.identitybackend.LdapIdentityBackend;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith({ ApacheDSTestExtension.class })
@CreateDS(name = "KerberosKRBProtocolTest-class",
partitions =
{
@CreatePartition(
name = "example",
suffix = "dc=example,dc=com")
})
@CreateLdapServer(
transports =
{
@CreateTransport(protocol = "LDAP", address = "127.0.0.1")
})
@ApplyLdifs(
{
"dn: dc=example,dc=com",
"objectClass: top",
"objectClass: domain",
"dc: example",
"dn: ou=users,dc=example,dc=com",
"objectClass: top",
"objectClass: organizationalUnit",
"ou: users"
}
)
public class LdapBackendKdcTest extends AbstractLdapBackendKdcTest {
private LdapIdentityBackend backend;
@BeforeEach
public void startUp() throws Exception {
Conf config = new Conf();
config.setString("host", "127.0.0.1");
config.setString("admin_dn", ADMIN_DN);
config.setString("admin_pw", ADMIN_PW);
config.setString("base_dn", BASE_DN);
int port = getLdapServer().getPort();
config.setInt("port", port);
test.setPort(port);
this.backend = new LdapIdentityBackend(config);
backend.initialize();
backend.start();
test.createTestDir();
test.setUp();
}
@AfterEach
public void tearDown() throws Exception {
backend.stop();
backend.release();
test.deleteTestDir();
}
@Test
public void testKdc() throws Exception {
TgtTicket tgt;
SgtTicket tkt;
try {
tgt = test.getKrbClient().requestTgt(
test.getClientPrincipal(), test.getClientPassword());
assertThat(tgt).isNotNull();
tkt = test.getKrbClient().requestSgt(tgt, test.getServerPrincipal());
assertThat(tkt).isNotNull();
} catch (Exception e) {
e.printStackTrace();
Assertions.fail("Exception occurred with good password. "
+ e.toString());
}
}
}
| 621 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/LdapIdentityGetHelper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.util.GeneralizedTime;
import org.apache.directory.shared.kerberos.KerberosAttribute;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class LdapIdentityGetHelper {
private Entry entry;
public LdapIdentityGetHelper(Entry entry) {
this.entry = entry;
}
/**
* Get principal name.
* @throws LdapInvalidAttributeValueException e
* @return principal name
*/
public PrincipalName getPrincipalName() throws LdapInvalidAttributeValueException {
String principalNameStr = entry.get(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT).getString();
PrincipalName principalName = new PrincipalName(principalNameStr);
return principalName;
}
/**
* Get key version.
* @throws LdapInvalidAttributeValueException e
* @return key version
*/
public int getKeyVersion() throws LdapInvalidAttributeValueException {
String keyVersionStr = entry.get(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT).getString();
int keyVersion = Integer.parseInt(keyVersionStr);
return keyVersion;
}
/**
* Get keys.
* @throws IOException e
* @return keys
*/
public List<EncryptionKey> getKeys() throws IOException {
Iterator<Value> iterator1 = entry.get(KerberosAttribute.KRB5_KEY_AT).iterator();
List<EncryptionKey> keys = new ArrayList<>();
while (iterator1.hasNext()) {
byte[] encryKey = iterator1.next().getBytes();
EncryptionKey key = new EncryptionKey();
key.decode(encryKey);
key.setKvno(1); // TODO: kvno should be correctly stored and retrieved
keys.add(key);
}
return keys;
}
/**
* Get created time.
* @throws LdapInvalidAttributeValueException e
* @throws ParseException e
* @return created time
*/
public KerberosTime getCreatedTime() throws LdapInvalidAttributeValueException,
ParseException {
String createTime = entry.get("createTimestamp").getString();
return createKerberosTime(createTime);
}
/**
* Get expire time.
* @throws LdapInvalidAttributeValueException e
* @throws ParseException e
* @return the expire time
*/
public KerberosTime getExpireTime() throws LdapInvalidAttributeValueException,
ParseException {
String expirationTime = entry.get(KerberosAttribute.KRB5_ACCOUNT_EXPIRATION_TIME_AT).getString();
return createKerberosTime(expirationTime);
}
/**
* Get whether disabled.
* @throws LdapInvalidAttributeValueException e
* @return whether this krb5 account is disabled
*/
public boolean getDisabled() throws LdapInvalidAttributeValueException {
String disabled = entry.get(KerberosAttribute.KRB5_ACCOUNT_DISABLED_AT).getString();
return Boolean.parseBoolean(disabled);
}
/**
* Get kdc flags.
* @throws LdapInvalidAttributeValueException e
* @return kdc flags
*/
public int getKdcFlags() throws LdapInvalidAttributeValueException {
String krb5KDCFlags = entry.get("krb5KDCFlags").getString();
return Integer.parseInt(krb5KDCFlags);
}
/**
* Get whether locked.
* @throws LdapInvalidAttributeValueException e
* @return whether the krb5 account is locked
*/
public boolean getLocked() throws LdapInvalidAttributeValueException {
String lockedOut = entry.get(KerberosAttribute.KRB5_ACCOUNT_LOCKEDOUT_AT).getString();
return Boolean.parseBoolean(lockedOut);
}
/**
* Create kerberos time.
*/
private KerberosTime createKerberosTime(String generalizedTime)
throws ParseException {
long time = new GeneralizedTime(generalizedTime).getTime();
return new KerberosTime(time);
}
} | 622 |
0 | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/ldap-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/LdapIdentityBackend.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.api.ldap.model.message.ModifyRequest;
import org.apache.directory.api.ldap.model.message.ModifyRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.name.Rdn;
import org.apache.directory.api.util.GeneralizedTime;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.apache.directory.shared.kerberos.KerberosAttribute;
import org.apache.kerby.config.Config;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.backend.AbstractIdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/**
* An LDAP based backend implementation.
*/
public class LdapIdentityBackend extends AbstractIdentityBackend {
private int currentConnectionIndex = 0;
private Map<String, LdapConnection> connections = new HashMap<>();
//The LdapConnection, may be LdapNetworkConnection or LdapCoreSessionConnection
private LdapConnection connection;
private String[] hosts;
//This is used as a flag to represent the connection whether is
// LdapNetworkConnection object or not
private boolean isLdapNetworkConnection;
private static final Logger LOG = LoggerFactory.getLogger(LdapIdentityBackend.class);
public LdapIdentityBackend() {
this.isLdapNetworkConnection = true;
}
/**
* Constructing an instance using specified config that contains anything
* to be used to initialize an LdapConnection and necessary baseDn.
* @param config . The config is used to config the backend.
*/
public LdapIdentityBackend(Config config) {
setConfig(config);
this.isLdapNetworkConnection = true;
}
/**
* Constructing an instance using a LdapConnection and a specified config
* that contains anything to be used to initialize a necessary baseDn.
* @param config The config is used to config the backend
* @param connection The connection to be used to handle the operations,
* may be a LdapNetworkConnection or a LdapCoreSessionConnection.
*/
public LdapIdentityBackend(Config config,
LdapConnection connection) {
setConfig(config);
if (isHa()) {
throw new IllegalArgumentException("Only one ldap connection provided, but two needed "
+ "when set ha hosts[" + config.getString("host") + "]");
}
this.connection = connection;
String hostConfig = getConfig().getString("host");
hosts = new String[]{hostConfig};
connections.put(hostConfig, connection);
}
public LdapIdentityBackend(Config config, Map<String, LdapConnection> connections) {
setConfig(config);
String hostConfig = getConfig().getString("host");
hosts = hostConfig.trim().split(",");
if (hosts.length > 2) {
throw new IllegalArgumentException("More than two ldap hosts is not supported.");
}
if (hosts.length != connections.size()) {
throw new IllegalArgumentException("Number of ldap hosts[" + hosts.length
+ "] not equal to ldap connections[" + connections.size() + "].");
}
this.connections = new HashMap<>(connections);
connection = connections.get(hosts[currentConnectionIndex]);
}
/**
* Start the connection for the initialize()
*/
private void startConnection() throws LdapException {
if (isLdapNetworkConnection) {
String hostConfig = getConfig().getString("host");
hosts = hostConfig.trim().split(",");
if (hosts.length > 2) {
throw new IllegalArgumentException("More than two ldap hosts is not supported.");
}
for (String host: hosts) {
LdapConnection connection =
new LdapNetworkConnection(host, getConfig().getInt("port"));
connections.put(host, connection);
}
String currentHost = hosts[currentConnectionIndex];
connection = connections.get(currentHost);
}
for (LdapConnection connection: connections.values()) {
connection.bind(getConfig().getString("admin_dn"),
getConfig().getString("admin_pw"));
}
LOG.info("Start connection with ldap host[" + getConfig().getString("host") + "]");
}
/**
* {@inheritDoc}
*/
@Override
protected void doInitialize() throws KrbException {
LOG.info("Initializing the Ldap identity backend.");
try {
startConnection();
} catch (LdapException e) {
LOG.error("Failed to start connection with LDAP", e);
throw new KrbException("Failed to start connection with LDAP", e);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() throws KrbException {
try {
closeConnection();
} catch (IOException e) {
LOG.error("Failed to close connection with LDAP", e);
throw new KrbException("Failed to close connection with LDAP", e);
}
LOG.info("closed connection with LDAP.");
}
/**
* Close the connection for stop()
*/
private void closeConnection() throws IOException {
IOException cause = null;
for (Map.Entry<String, LdapConnection> entry: connections.entrySet()) {
LdapConnection connection = entry.getValue();
try {
if (connection.isConnected()) {
connection.close();
}
} catch (IOException e) {
LOG.error("Catch exception when close connection with host[" + entry.getKey() + "].");
if (cause == null) {
cause = e;
} else {
cause.addSuppressed(e);
}
}
}
if (cause != null) {
throw cause;
}
}
/**
* Convert a KerberosTime type obeject to a generalized time form of String
* @param kerberosTime The kerberostime to convert
*/
private String toGeneralizedTime(KerberosTime kerberosTime) {
GeneralizedTime generalizedTime = new GeneralizedTime(kerberosTime.getValue());
return generalizedTime.toString();
}
/**
* An inner class, used to encapsulate key information
*/
static class KeysInfo {
private String[] etypes;
private byte[][] keys;
private String[] kvnos;
KeysInfo(KrbIdentity identity) throws KrbException {
Map<EncryptionType, EncryptionKey> keymap = identity.getKeys();
this.etypes = new String[keymap.size()];
this.keys = new byte[keymap.size()][];
this.kvnos = new String[keymap.size()];
int i = 0;
for (Map.Entry<EncryptionType, EncryptionKey> entryKey : keymap.entrySet()) {
etypes[i] = entryKey.getKey().getValue() + "";
try {
keys[i] = entryKey.getValue().encode();
} catch (IOException e) {
throw new KrbException("encode key failed", e);
}
kvnos[i] = entryKey.getValue().getKvno() + "";
i++;
}
}
public String[] getEtypes() {
return etypes;
}
public byte[][] getKeys() {
return keys;
}
public String[] getKvnos() {
return kvnos;
}
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException {
String principalName = identity.getPrincipalName();
String[] names = principalName.split("@");
Entry entry = new DefaultEntry();
KeysInfo keysInfo = new KeysInfo(identity);
try {
Dn dn = toDn(principalName);
entry.setDn(dn);
entry.add("objectClass", "top", "person", "inetOrgPerson",
"krb5principal", "krb5kdcentry");
entry.add("uid", names[0]);
entry.add("cn", names[0]);
entry.add("sn", names[0]);
entry.add(KerberosAttribute.KRB5_KEY_AT, keysInfo.getKeys());
entry.add("krb5EncryptionType", keysInfo.getEtypes());
entry.add(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT, principalName);
entry.add(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT,
identity.getKeyVersion() + "");
entry.add("krb5KDCFlags", "" + identity.getKdcFlags());
entry.add(KerberosAttribute.KRB5_ACCOUNT_DISABLED_AT, ""
+ identity.isDisabled());
entry.add(KerberosAttribute.KRB5_ACCOUNT_LOCKEDOUT_AT, ""
+ identity.isLocked());
entry.add(KerberosAttribute.KRB5_ACCOUNT_EXPIRATION_TIME_AT,
toGeneralizedTime(identity.getExpireTime()));
new FailoverInvocationHandler<Void>() {
@Override
public Void execute() throws LdapException {
connection.add(entry);
return null;
}
}.run();
} catch (LdapInvalidDnException e) {
LOG.error("Error occurred while adding identity", e);
throw new KrbException("Failed to add identity", e);
} catch (LdapException e) {
LOG.error("Error occurred while adding identity", e);
throw new KrbException("Failed to add identity", e);
}
return getIdentity(principalName);
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doGetIdentity(String principalName) throws KrbException {
KrbIdentity krbIdentity = new KrbIdentity(principalName);
String searchFilter = FilterBuilder.and(
FilterBuilder.equal("objectclass", "krb5principal"),
FilterBuilder.equal("krb5PrincipalName", principalName)
).toString();
try {
EntryCursor cursor = new FailoverInvocationHandler<EntryCursor>() {
@Override
public EntryCursor execute() throws LdapException {
return connection.search(getConfig().getString("base_dn"), searchFilter,
SearchScope.SUBTREE, "dn");
}
}.run();
// there should be at most one entry with this principal name
if (cursor == null || !cursor.next()) {
return null;
}
Dn dn = cursor.get().getDn();
cursor.close();
Entry entry = new FailoverInvocationHandler<Entry>() {
@Override
public Entry execute() throws LdapException {
return connection.lookup(dn, "*", "+");
}
}.run();
if (entry == null) {
return null;
}
LdapIdentityGetHelper getHelper = new LdapIdentityGetHelper(entry);
krbIdentity.setPrincipal(getHelper.getPrincipalName());
krbIdentity.setKeyVersion(getHelper.getKeyVersion());
krbIdentity.addKeys(getHelper.getKeys());
krbIdentity.setCreatedTime(getHelper.getCreatedTime());
krbIdentity.setExpireTime(getHelper.getExpireTime());
krbIdentity.setDisabled(getHelper.getDisabled());
krbIdentity.setKdcFlags(getHelper.getKdcFlags());
krbIdentity.setLocked(getHelper.getLocked());
} catch (LdapException e) {
throw new KrbException("Failed to retrieve identity", e);
} catch (CursorException e) {
throw new KrbException("Failed to retrieve identity", e);
} catch (ParseException e) {
throw new KrbException("Failed to retrieve identity", e);
} catch (IOException e) {
throw new KrbException("Failed to retrieve identity", e);
}
return krbIdentity;
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException {
String principalName = identity.getPrincipalName();
KeysInfo keysInfo = new KeysInfo(identity);
try {
Dn dn = toDn(principalName);
ModifyRequest modifyRequest = new ModifyRequestImpl();
modifyRequest.setName(dn);
modifyRequest.replace(KerberosAttribute.KRB5_KEY_VERSION_NUMBER_AT,
"" + identity.getKeyVersion());
modifyRequest.replace(KerberosAttribute.KRB5_KEY_AT, keysInfo.getKeys());
modifyRequest.replace("krb5EncryptionType", keysInfo.getEtypes());
modifyRequest.replace(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT,
identity.getPrincipalName());
modifyRequest.replace(KerberosAttribute.KRB5_ACCOUNT_EXPIRATION_TIME_AT,
toGeneralizedTime(identity.getExpireTime()));
modifyRequest.replace(KerberosAttribute.KRB5_ACCOUNT_DISABLED_AT, ""
+ identity.isDisabled());
modifyRequest.replace("krb5KDCFlags", "" + identity.getKdcFlags());
modifyRequest.replace(KerberosAttribute.KRB5_ACCOUNT_LOCKEDOUT_AT, ""
+ identity.isLocked());
new FailoverInvocationHandler<Void>() {
@Override
public Void execute() throws LdapException {
connection.modify(modifyRequest);
return null;
}
}.run();
} catch (LdapException e) {
LOG.error("Error occurred while updating identity: " + principalName, e);
throw new KrbException("Failed to update identity", e);
}
return getIdentity(principalName);
}
/**
* {@inheritDoc}
*/
@Override
protected void doDeleteIdentity(String principalName) throws KrbException {
try {
Dn dn = toDn(principalName);
new FailoverInvocationHandler<Void>() {
@Override
public Void execute() throws LdapException {
connection.delete(dn);
return null;
}
}.run();
} catch (LdapException e) {
LOG.error("Error occurred while deleting identity: " + principalName);
throw new KrbException("Failed to remove identity", e);
}
}
/**
* Used to convert a dn of String to a Dn object
* @param principalName The principal name to be convert.
* @return
* @throws org.apache.directory.api.ldap.model.exception.LdapInvalidDnException if a remote exception occurs.
* @throws LdapInvalidAttributeValueException
*/
private Dn toDn(String principalName) throws LdapInvalidDnException, LdapInvalidAttributeValueException {
String[] names = principalName.split("@");
String uid = names[0];
Dn dn = new Dn(new Rdn("uid", uid), new Dn(getConfig().getString("base_dn")));
return dn;
}
/**
* {@inheritDoc}
*/
@Override
protected Iterable<String> doGetIdentities() {
List<String> identityNames = new ArrayList<>();
EntryCursor cursor;
Entry entry;
try {
cursor = new FailoverInvocationHandler<EntryCursor>() {
@Override
public EntryCursor execute() throws LdapException {
return connection.search(getConfig().getString("base_dn"), "(objectclass=krb5principal)",
SearchScope.SUBTREE, KerberosAttribute.KRB5_PRINCIPAL_NAME_AT);
}
}.run();
if (cursor == null) {
return null;
}
while (cursor.next()) {
entry = cursor.get();
Attribute krb5PrincipalNameAt = entry.get(KerberosAttribute.KRB5_PRINCIPAL_NAME_AT);
if (krb5PrincipalNameAt != null) {
identityNames.add(krb5PrincipalNameAt.getString());
}
}
cursor.close();
Collections.sort(identityNames);
} catch (LdapException e) {
LOG.error("With LdapException when LdapConnection searching. " + e);
} catch (CursorException e) {
LOG.error("With CursorException when EntryCursor getting. " + e);
} catch (IOException e) {
LOG.error("With IOException when closing EntryCursor. " + e);
}
return identityNames;
}
private void performFailover() {
currentConnectionIndex = (currentConnectionIndex + 1) % hosts.length;
String host = hosts[currentConnectionIndex];
connection = connections.get(host);
}
private boolean isHa() {
String host = getConfig().getString("host");
if (host != null) {
return host.trim().split(",").length == 2;
}
return false;
}
abstract class FailoverInvocationHandler<T> {
public abstract T execute() throws LdapException;
public T run() throws LdapException {
try {
return execute();
} catch (LdapException e) {
if (!isHa()) {
throw e;
}
String host = hosts[currentConnectionIndex];
LOG.error("Catch exception with ldap host[" + host + "].", e);
performFailover();
host = hosts[currentConnectionIndex];
LOG.info("Failover to ldap host:" + host + ".");
return execute();
}
}
}
}
| 623 |
0 | Create_ds/directory-kerby/kerby-backend/json-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/json-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/JsonBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.kerby.config.Conf;
import org.apache.kerby.config.Config;
import org.apache.kerby.kerberos.kdc.identitybackend.JsonIdentityBackend;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import java.io.File;
/**
* Json backend test
*/
public class JsonBackendTest extends BackendTestBase {
private static File jsonBackendFile;
@BeforeAll
public static void setup() throws KrbException {
File testDir = new File(System.getProperty("test.dir", "target"));
jsonBackendFile = new File(testDir, "json-identity-backend-file");
String jsonBackendFileString = jsonBackendFile.getAbsolutePath();
Config backendConfig = new Conf();
backendConfig.setString(JsonIdentityBackend.JSON_IDENTITY_BACKEND_DIR,
jsonBackendFileString);
backend = new JsonIdentityBackend(backendConfig);
backend.initialize();
}
@AfterAll
public static void cleanJsonBackendFile() {
if (jsonBackendFile.exists()) {
jsonBackendFile.delete();
}
}
}
| 624 |
0 | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/JsonIdentityBackend.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.kerby.config.Config;
import org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter.EncryptionKeyAdapter;
import org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter.KerberosTimeAdapter;
import org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter.PrincipalNameAdapter;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.BatchTrans;
import org.apache.kerby.kerberos.kerb.identity.backend.AbstractIdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import org.apache.kerby.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A Json file based backend implementation.
*/
public class JsonIdentityBackend extends AbstractIdentityBackend {
private static final Logger LOG =
LoggerFactory.getLogger(JsonIdentityBackend.class);
public static final String JSON_IDENTITY_BACKEND_DIR = "backend.json.dir";
private File jsonKdbFile;
private Gson gson;
// Identities loaded from file
private final Map<String, KrbIdentity> identities =
new ConcurrentHashMap<>(new TreeMap<String, KrbIdentity>());
private long kdbFileUpdateTime = -1;
private Lock lock = new ReentrantLock();
public JsonIdentityBackend() {
}
/**
* Constructing an instance using specified config that contains anything
* to be used to initialize the json format database.
* @param config The configuration for json identity backend
*/
public JsonIdentityBackend(Config config) {
setConfig(config);
}
/**
* {@inheritDoc}
*/
@Override
public boolean supportBatchTrans() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public BatchTrans startBatchTrans() throws KrbException {
if (lock.tryLock()) {
checkAndReload();
return new JsonBatchTrans();
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void doInitialize() throws KrbException {
LOG.info("Initializing the Json identity backend.");
initGsonBuilder();
String dirPath = getConfig().getString(JSON_IDENTITY_BACKEND_DIR);
File jsonFileDir;
if (dirPath == null || dirPath.isEmpty()) {
jsonFileDir = getBackendConfig().getConfDir();
} else {
jsonFileDir = new File(dirPath);
if (!jsonFileDir.exists() && !jsonFileDir.mkdirs()) {
throw new KrbException("Failed to create json file dir " + jsonFileDir);
}
}
jsonKdbFile = new File(jsonFileDir, "json-backend.json");
if (!jsonKdbFile.exists()) {
try {
jsonKdbFile.createNewFile();
} catch (IOException e) {
throw new KrbException("Failed to create " + jsonKdbFile.getAbsolutePath());
}
}
}
private void load() throws KrbException {
LOG.info("Loading the identities from json file.");
long nowTimeStamp = jsonKdbFile.lastModified();
String reloadedJsonContent;
if (lock.tryLock()) {
try {
try {
reloadedJsonContent = IOUtil.readFile(jsonKdbFile);
} catch (IOException e) {
throw new KrbException("Failed to read file", e);
}
Map<String, KrbIdentity> reloadedEntries =
gson.fromJson(reloadedJsonContent,
new TypeToken<HashMap<String, KrbIdentity>>() {
}.getType());
if (reloadedEntries != null) {
identities.clear();
identities.putAll(reloadedEntries);
}
kdbFileUpdateTime = nowTimeStamp;
} finally {
lock.unlock();
}
}
}
/**
* Check kdb file timestamp to see if it's changed or not. If
* necessary load the kdb again.
*/
private void checkAndReload() throws KrbException {
long nowTimeStamp = jsonKdbFile.lastModified();
if (nowTimeStamp != kdbFileUpdateTime) {
load();
}
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doGetIdentity(String principalName) throws KrbException {
checkAndReload();
return identities.get(principalName);
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException {
checkAndReload();
if (lock.tryLock()) {
try {
identities.put(identity.getPrincipalName(), identity);
persistToFile();
} finally {
lock.unlock();
}
}
return doGetIdentity(identity.getPrincipalName());
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException {
checkAndReload();
if (lock.tryLock()) {
try {
identities.put(identity.getPrincipalName(), identity);
persistToFile();
} finally {
lock.unlock();
}
}
return doGetIdentity(identity.getPrincipalName());
}
/**
* {@inheritDoc}
*/
@Override
protected void doDeleteIdentity(String principalName) throws KrbException {
checkAndReload();
if (!identities.containsKey(principalName)) {
return;
}
if (lock.tryLock()) {
try {
identities.remove(principalName);
persistToFile();
} finally {
lock.unlock();
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected Iterable<String> doGetIdentities() throws KrbException {
load();
List<String> principals = new ArrayList<>(identities.keySet());
Collections.sort(principals);
return principals;
}
private void initGsonBuilder() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(EncryptionKey.class, new EncryptionKeyAdapter());
gsonBuilder.registerTypeAdapter(PrincipalName.class, new PrincipalNameAdapter());
gsonBuilder.registerTypeAdapter(KerberosTime.class, new KerberosTimeAdapter());
gsonBuilder.enableComplexMapKeySerialization();
gsonBuilder.setPrettyPrinting();
gson = gsonBuilder.create();
}
private void persistToFile() throws KrbException {
String newJsonContent = gson.toJson(identities);
try {
File newJsonKdbFile = Files.createTempFile(jsonKdbFile.getParentFile().toPath(), "kerby-kdb",
".json").toFile();
IOUtil.writeFile(newJsonContent, newJsonKdbFile);
boolean delete = jsonKdbFile.delete();
if (!delete) {
throw new RuntimeException("File delete error!");
}
boolean rename = newJsonKdbFile.renameTo(jsonKdbFile);
if (!rename) {
throw new RuntimeException("File rename error!");
}
kdbFileUpdateTime = jsonKdbFile.lastModified();
} catch (IOException e) {
LOG.error("Error occurred while writing identities to file: " + jsonKdbFile);
throw new KrbException("Failed to write file", e);
}
}
class JsonBatchTrans implements BatchTrans {
@Override
public void commit() throws KrbException {
try {
// Force to persist memory states to disk file.
persistToFile();
} finally {
lock.unlock();
}
}
@Override
public void rollback() throws KrbException {
// Force to reload from disk file and disgard the memory states.
try {
load();
} finally {
lock.unlock();
}
}
@Override
public BatchTrans addIdentity(KrbIdentity identity) throws KrbException {
if (identity != null
&& identities.containsKey(identity.getPrincipalName())) {
identities.put(identity.getPrincipalName(), identity);
}
return this;
}
@Override
public BatchTrans updateIdentity(KrbIdentity identity) throws KrbException {
if (identity != null
&& identities.containsKey(identity.getPrincipalName())) {
identities.put(identity.getPrincipalName(), identity);
}
return this;
}
@Override
public BatchTrans deleteIdentity(String principalName) throws KrbException {
if (principalName != null && identities.containsKey(principalName)) {
identities.remove(principalName);
}
return this;
}
}
}
| 625 |
0 | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/typeAdapter/EncryptionKeyAdapter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.apache.kerby.kerberos.kerb.KrbCodec;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.util.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Type;
public class EncryptionKeyAdapter implements JsonSerializer<EncryptionKey>,
JsonDeserializer<EncryptionKey> {
private static final Logger LOG = LoggerFactory.getLogger(EncryptionKeyAdapter.class);
@Override
public EncryptionKey deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException {
JsonObject jsonObject = (JsonObject) jsonElement;
EncryptionKey encryptionKey = new EncryptionKey();
try {
encryptionKey.decode(HexUtil.hex2bytes(jsonObject.get("key").getAsString()));
} catch (IOException e) {
LOG.error("Fail to decode encryption key. " + e);
}
encryptionKey.setKvno(jsonObject.get("kvno").getAsInt());
return encryptionKey;
}
@Override
public JsonElement serialize(EncryptionKey encryptionKey,
Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("kvno", encryptionKey.getKvno());
try {
jsonObject.addProperty("key", HexUtil.bytesToHex(KrbCodec.encode(encryptionKey)));
} catch (KrbException e) {
throw new RuntimeException(e);
}
return jsonObject;
}
}
| 626 |
0 | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/typeAdapter/KerberosTimeAdapter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import java.lang.reflect.Type;
public class KerberosTimeAdapter implements JsonSerializer<KerberosTime>,
JsonDeserializer<KerberosTime> {
@Override
public KerberosTime deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException {
String timeString = jsonElement.getAsString();
long time = Long.parseLong(timeString);
return new KerberosTime(time);
}
@Override
public JsonElement serialize(KerberosTime kerberosTime, Type type,
JsonSerializationContext jsonSerializationContext) {
String timeString = String.valueOf(kerberosTime.getTime());
return new JsonPrimitive(timeString);
}
}
| 627 |
0 | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend | Create_ds/directory-kerby/kerby-backend/json-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/typeAdapter/PrincipalNameAdapter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend.typeAdapter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
import java.lang.reflect.Type;
public class PrincipalNameAdapter implements JsonSerializer<PrincipalName>,
JsonDeserializer<PrincipalName> {
@Override
public PrincipalName deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext)
throws JsonParseException {
return new PrincipalName(jsonElement.getAsString());
}
@Override
public JsonElement serialize(PrincipalName principalName,
Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(principalName.getName());
}
}
| 628 |
0 | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/test/java/org/apache | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/test/java/org/apache/kerby/MavibotBackendTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.backend.BackendTestBase;
import org.apache.kerby.kerberos.kerb.identity.backend.BackendTestUtil;
import org.apache.kerby.kerberos.kerb.identity.backend.IdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests for MavibotBackend.
*
* @author <a href="mailto:[email protected]">Apache Kerby Project</a>
*/
public class MavibotBackendTest extends BackendTestBase {
@TempDir
static Path tmpFolder;
@BeforeAll
public static void setup() throws Exception {
File dbFile = tmpFolder.toFile();
backend = new MavibotBackend(dbFile);
backend.initialize();
}
// overriding this cause MavibotBackend doesn't support range search
@Override
protected void testGetIdentities(IdentityBackend backend) throws KrbException {
KrbIdentity[] identities = BackendTestUtil.createManyIdentities();
for (KrbIdentity identity : identities) {
backend.addIdentity(identity);
}
// clear the identity cache.
backend.release();
List<String> principals = new LinkedList<>();
Iterator<String> iterator = backend.getIdentities().iterator();
while (iterator.hasNext()) {
principals.add(iterator.next());
}
assertThat(principals).hasSize(identities.length);
for (KrbIdentity entry : identities) {
assertTrue(principals.contains(entry.getPrincipalName()));
}
for (KrbIdentity identity : identities) {
backend.deleteIdentity(identity.getPrincipalName());
}
}
}
| 629 |
0 | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/test/java/org/apache | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/test/java/org/apache/kerby/KrbIdentitySerializerTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests for KrbIdentity serializer.
*
* @author <a href="mailto:[email protected]">Apache Kerby Project</a>
*/
public class KrbIdentitySerializerTest {
private KrbIdentitySerializer serializer = KrbIdentitySerializer.INSTANCE;
@Test
public void testSerialization() throws Exception {
KrbIdentity entry = new KrbIdentity("[email protected]");
entry.setCreatedTime(new KerberosTime(System.currentTimeMillis()));
entry.setDisabled(true);
entry.setKeyVersion(1);
entry.setLocked(true);
byte[] junk = new byte[11];
Arrays.fill(junk, (byte) 1);
EncryptionKey key1 = new EncryptionKey(EncryptionType.AES128_CTS, junk);
entry.addKey(key1);
EncryptionKey key2 = new EncryptionKey(EncryptionType.AES128_CTS_HMAC_SHA1_96, junk);
entry.addKey(key2);
byte[] serialized = serializer.serialize(entry);
KrbIdentity deserialized = serializer.fromBytes(serialized);
verifyEquality(entry, deserialized);
deserialized = serializer.fromBytes(serialized, 0);
verifyEquality(entry, deserialized);
deserialized = serializer.deserialize(ByteBuffer.wrap(serialized));
verifyEquality(entry, deserialized);
try {
deserialized = serializer.fromBytes(serialized, 1);
fail("shouldn't deserialize");
} catch (Exception e) {
// expected
System.out.println(e);
}
}
private void verifyEquality(KrbIdentity expected, KrbIdentity actual) {
assertNotNull(actual);
assertEquals(expected.getPrincipalName(), actual.getPrincipalName());
assertEquals(expected.getCreatedTime().getTime(), actual.getCreatedTime().getTime());
assertEquals(expected.getExpireTime().getTime(), actual.getExpireTime().getTime());
assertEquals(expected.isDisabled(), actual.isDisabled());
assertEquals(expected.isLocked(), actual.isLocked());
assertEquals(expected.getKeyVersion(), actual.getKeyVersion());
assertEquals(expected.getKdcFlags(), actual.getKdcFlags());
assertEquals(expected.getKeys().size(), actual.getKeys().size());
Map<EncryptionType, EncryptionKey> exKeys = expected.getKeys();
Map<EncryptionType, EncryptionKey> acKeys = actual.getKeys();
for (EncryptionType et : exKeys.keySet()) {
EncryptionKey exKey = exKeys.get(et);
EncryptionKey acKey = acKeys.get(et);
assertEquals(exKey.getKvno(), acKey.getKvno());
assertEquals(exKey.getKeyType(), acKey.getKeyType());
boolean equal = Arrays.equals(exKey.getKeyData(), acKey.getKeyData());
assertTrue(equal);
}
}
}
| 630 |
0 | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache/kerby/MavibotBackend.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby;
import org.apache.directory.mavibot.btree.BTree;
import org.apache.directory.mavibot.btree.BTreeFactory;
import org.apache.directory.mavibot.btree.BTreeTypeEnum;
import org.apache.directory.mavibot.btree.KeyCursor;
import org.apache.directory.mavibot.btree.PersistedBTreeConfiguration;
import org.apache.directory.mavibot.btree.RecordManager;
import org.apache.directory.mavibot.btree.Tuple;
import org.apache.directory.mavibot.btree.exception.KeyNotFoundException;
import org.apache.directory.mavibot.btree.serializer.StringSerializer;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.backend.AbstractIdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* A backend based on Apache Mavibot(an MVCC BTree library).
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class MavibotBackend extends AbstractIdentityBackend {
//Name of the database
private static final String DATA_TREE = "kerby-data";
// Name of the database file
private static final String DATABASE_NAME = "kerby-data.db";
private static final Logger LOG = LoggerFactory.getLogger(MavibotBackend.class);
//The RecordManager of Mavibot
private RecordManager rm;
//The BTree holding all data
private BTree<String, KrbIdentity> database;
/**
* Creates a new instance of MavibotBackend.
*
* @param location
* the File handle pointing to the database file or the directory
* where it is present
* @throws Exception e
*/
public MavibotBackend(File location) throws Exception {
String dbPath = location.getAbsolutePath();
LOG.info("Initializing the mavibot backend");
if (!location.exists() && !location.mkdirs()) {
throw new KrbException("Can't create location file");
}
if (location.isDirectory()) {
dbPath += File.separator + DATABASE_NAME;
}
rm = new RecordManager(dbPath);
if (rm.getManagedTrees().contains(DATA_TREE)) {
database = rm.getManagedTree(DATA_TREE);
} else {
PersistedBTreeConfiguration<String, KrbIdentity> config =
new PersistedBTreeConfiguration<>();
// _no_ duplicates
config.setAllowDuplicates(false);
config.setBtreeType(BTreeTypeEnum.PERSISTED);
config.setFilePath(dbPath);
config.setKeySerializer(StringSerializer.INSTANCE);
config.setName(DATA_TREE);
config.setValueSerializer(KrbIdentitySerializer.INSTANCE);
database = BTreeFactory.createPersistedBTree(config);
rm.manage(database);
}
}
/**
* {@inheritDoc}
*/
@Override
protected Iterable<String> doGetIdentities() throws KrbException {
List<String> keys = new ArrayList<>();
KeyCursor<String> cursor = null;
try {
cursor = database.browseKeys();
while (cursor.hasNext()) {
keys.add(cursor.next());
}
} catch (Exception e) {
throw new KrbException("Errors occurred while fetching the principals", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
return keys;
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doGetIdentity(String principalName) throws KrbException {
try {
return database.get(principalName);
} catch (KeyNotFoundException e) {
LOG.debug("Identity {} doesn't exist", principalName);
return null;
} catch (IOException e) {
throw new KrbException("Failed to get the identity " + principalName);
}
}
/**
* {@inheritDoc}
*/
@Override
protected synchronized KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException {
String p = identity.getPrincipalName();
try {
if (database.hasKey(p)) {
throw new KrbException("Identity already exists " + p);
}
return database.insert(p, identity);
} catch (KeyNotFoundException e) {
throw new KrbException("No such identity exists " + p);
} catch (IOException e) {
throw new KrbException("Failed to add the identity " + p);
}
}
/**
* {@inheritDoc}
*/
@Override
protected synchronized KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException {
String p = identity.getPrincipalName();
try {
if (!database.hasKey(p)) {
throw new KrbException("No identity found with the principal " + p);
}
database.delete(p);
return database.insert(p, identity);
} catch (Exception e) {
throw new KrbException("Failed to update the identity " + p);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doDeleteIdentity(String principalName) throws KrbException {
try {
Tuple<String, KrbIdentity> t = database.delete(principalName);
if (t == null) {
throw new KrbException("Not existing, identity = " + principalName);
}
} catch (IOException e) {
throw new KrbException("Failed to delete the identity " + principalName);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() throws KrbException {
try {
rm.close();
} catch (IOException e) {
throw new KrbException("Failed to close the database", e);
}
}
}
| 631 |
0 | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache/kerby/KrbIdentitySerializer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby;
import org.apache.directory.mavibot.btree.serializer.BufferHandler;
import org.apache.directory.mavibot.btree.serializer.ElementSerializer;
import org.apache.directory.mavibot.btree.serializer.IntSerializer;
import org.apache.directory.mavibot.btree.serializer.LongSerializer;
import org.apache.directory.mavibot.btree.serializer.StringSerializer;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.Map;
/**
* Serializer for KrbIdentity.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class KrbIdentitySerializer implements ElementSerializer<KrbIdentity> {
/** the static instance of the serializer */
public static final KrbIdentitySerializer INSTANCE = new KrbIdentitySerializer();
/** comparator for KrbIdentity */
private KrbIdentityComparator comparator = KrbIdentityComparator.INSTANCE;
@Override
public byte[] serialize(KrbIdentity entry) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
// the principalName
out.write(StringSerializer.INSTANCE.serialize(entry.getPrincipalName()));
// key version
out.write(IntSerializer.serialize(entry.getKeyVersion()));
out.write(IntSerializer.serialize(entry.getKdcFlags()));
// mask for disabled and lock flags
byte mask = 0;
if (entry.isDisabled()) {
mask |= 1 << 1;
}
if (entry.isLocked()) {
mask |= 1 << 2;
}
out.write(mask);
// creation time
out.write(LongSerializer.serialize(entry.getCreatedTime().getTime()));
// expiration time
out.write(LongSerializer.serialize(entry.getExpireTime().getTime()));
Map<EncryptionType, EncryptionKey> keys = entry.getKeys();
// num keys
out.write(IntSerializer.serialize(keys.size()));
for (EncryptionKey ek : keys.values()) {
int type = ek.getKeyType().getValue();
out.write(IntSerializer.serialize(type));
byte[] data = ek.getKeyData();
out.write(IntSerializer.serialize(data.length));
out.write(data);
}
return out.toByteArray();
} catch (Exception e) {
throw new IllegalStateException("Failed to serialize the identity " + entry);
}
}
@Override
public KrbIdentity deserialize(BufferHandler bufferHandler)
throws IOException {
return fromBytes(bufferHandler.getBuffer());
}
@Override
public KrbIdentity deserialize(ByteBuffer buffer) throws IOException {
KrbIdentity id = null;
String principal = StringSerializer.INSTANCE.deserialize(buffer);
id = new KrbIdentity(principal);
int kvno = IntSerializer.INSTANCE.deserialize(buffer);
id.setKeyVersion(kvno);
int flags = IntSerializer.INSTANCE.deserialize(buffer);
id.setKdcFlags(flags);
byte mask = buffer.get();
if ((mask & 2) != 0) {
id.setDisabled(true);
}
if ((mask & 4) != 0) {
id.setLocked(true);
}
long creationTime = LongSerializer.INSTANCE.deserialize(buffer);
id.setCreatedTime(new KerberosTime(creationTime));
long exprTime = LongSerializer.INSTANCE.deserialize(buffer);
id.setExpireTime(new KerberosTime(exprTime));
int numKeys = IntSerializer.INSTANCE.deserialize(buffer);
for (int i = 0; i < numKeys; i++) {
int keyType = IntSerializer.INSTANCE.deserialize(buffer);
int keyLen = IntSerializer.INSTANCE.deserialize(buffer);
byte[] keyData = new byte[keyLen];
buffer.get(keyData);
EncryptionKey ek = new EncryptionKey(keyType, keyData);
id.addKey(ek);
}
return id;
}
@Override
public KrbIdentity fromBytes(byte[] buffer) throws IOException {
ByteBuffer buf = ByteBuffer.wrap(buffer);
return deserialize(buf);
}
@Override
public KrbIdentity fromBytes(byte[] buffer, int pos) throws IOException {
ByteBuffer buf = ByteBuffer.wrap(buffer, pos, buffer.length - pos);
return deserialize(buf);
}
@Override
public int compare(KrbIdentity type1, KrbIdentity type2) {
return comparator.compare(type1, type2);
}
@Override
public Comparator<KrbIdentity> getComparator() {
return comparator;
}
@Override
public Class<?> getType() {
return KrbIdentity.class;
}
}
| 632 |
0 | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache | Create_ds/directory-kerby/kerby-backend/mavibot-backend/src/main/java/org/apache/kerby/KrbIdentityComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby;
import java.util.Comparator;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
/**
* Comparator for KrbIdentity
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public final class KrbIdentityComparator implements Comparator<KrbIdentity> {
public static final KrbIdentityComparator INSTANCE = new KrbIdentityComparator();
private KrbIdentityComparator() {
}
@Override
public int compare(KrbIdentity o1, KrbIdentity o2) {
return o1.getPrincipalName().compareTo(o2.getPrincipalName());
}
}
| 633 |
0 | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/MySQLBackendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.kerby.config.Conf;
import org.apache.kerby.kerberos.kdc.identitybackend.MySQLConfKey;
import org.apache.kerby.kerberos.kdc.identitybackend.MySQLIdentityBackend;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import java.io.File;
import java.io.IOException;
public class MySQLBackendTest extends BackendTestBase {
private static File testDir = new File(System.getProperty("test.dir", "target"));
private static File dbFile = new File(testDir, "mysqlbackend.mv.db");
@BeforeAll
public static void setup() throws KrbException, IOException {
Conf config = new Conf();
config.setString(MySQLConfKey.MYSQL_DRIVER, "org.h2.Driver");
config.setString(MySQLConfKey.MYSQL_URL,
"jdbc:h2:" + testDir.getCanonicalPath() + "/mysqlbackend;MODE=MySQL");
config.setString(MySQLConfKey.MYSQL_USER, "root");
config.setString(MySQLConfKey.MYSQL_PASSWORD, "123456");
backend = new MySQLIdentityBackend(config);
backend.initialize();
}
@AfterAll
public static void tearDown() throws KrbException {
if (backend != null) {
backend.stop();
}
if (dbFile.exists() && !dbFile.delete()) {
System.err.println("Failed to delete the test database file.");
}
}
}
| 634 |
0 | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/test/java/org/apache/kerby/kerberos/kerb/identity/backend/MySQLBackendKdcTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kerb.identity.backend;
import org.apache.kerby.kerberos.kdc.identitybackend.MySQLConfKey;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.server.KdcConfigKey;
import org.apache.kerby.kerberos.kerb.server.KdcTestBase;
import org.apache.kerby.kerberos.kerb.type.ticket.SgtTicket;
import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.File;
import static org.assertj.core.api.Assertions.assertThat;
public class MySQLBackendKdcTest extends KdcTestBase {
private static File testDir = new File(System.getProperty("test.dir", "target"));
private static File dbFile = new File(testDir, "mysqlbackend.mv.db");
@AfterEach
public void tearDown() {
if (dbFile.exists() && !dbFile.delete()) {
System.err.println("Failed to delete the test database file.");
}
}
@Override
protected void prepareKdc() throws KrbException {
BackendConfig backendConfig = getKdcServer().getBackendConfig();
backendConfig.setString(KdcConfigKey.KDC_IDENTITY_BACKEND,
"org.apache.kerby.kerberos.kdc.identitybackend.MySQLIdentityBackend");
backendConfig.setString(MySQLConfKey.MYSQL_DRIVER, "org.h2.Driver");
backendConfig.setString(MySQLConfKey.MYSQL_URL,
"jdbc:h2:" + testDir.getAbsolutePath() + "/mysqlbackend;MODE=MySQL");
backendConfig.setString(MySQLConfKey.MYSQL_USER, "root");
backendConfig.setString(MySQLConfKey.MYSQL_PASSWORD, "123456");
super.prepareKdc();
}
@Test
public void testKdc() {
TgtTicket tgt;
SgtTicket tkt;
try {
tgt = getKrbClient().requestTgt(getClientPrincipal(), getClientPassword());
assertThat(tgt).isNotNull();
tkt = getKrbClient().requestSgt(tgt, getServerPrincipal());
assertThat(tkt).isNotNull();
} catch (Exception e) {
Assertions.fail("Exception occurred with good password. "
+ e.toString());
}
}
}
| 635 |
0 | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/MySQLConfKey.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import org.apache.kerby.config.ConfigKey;
/**
* Define all the MySQL backend related configuration items with default values.
*/
public enum MySQLConfKey implements ConfigKey {
MYSQL_DRIVER("org.drizzle.jdbc.DrizzleDriver"),
MYSQL_URL("jdbc:mysql:thin://127.0.0.1:3306/mysqlbackend"),
MYSQL_USER("root"),
MYSQL_PASSWORD("passwd");
private Object defaultValue;
MySQLConfKey() {
this.defaultValue = null;
}
MySQLConfKey(Object defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public String getPropertyKey() {
return name().toLowerCase();
}
@Override
public Object getDefaultValue() {
return this.defaultValue;
}
}
| 636 |
0 | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/main/java/org/apache/kerby/kerberos/kdc | Create_ds/directory-kerby/kerby-backend/mysql-backend/src/main/java/org/apache/kerby/kerberos/kdc/identitybackend/MySQLIdentityBackend.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.kerby.kerberos.kdc.identitybackend;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.kerby.config.Config;
import org.apache.kerby.kerberos.kerb.KrbException;
import org.apache.kerby.kerberos.kerb.identity.backend.AbstractIdentityBackend;
import org.apache.kerby.kerberos.kerb.request.KrbIdentity;
import org.apache.kerby.kerberos.kerb.type.KerberosTime;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey;
import org.apache.kerby.kerberos.kerb.type.base.EncryptionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import javax.sql.rowset.serial.SerialBlob;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
/**
* A MySQL based backend implementation.
*/
public class MySQLIdentityBackend extends AbstractIdentityBackend {
private String keyInfoTable;
private String identityTable;
private static DruidDataSource dataSource = null;
private static final Logger LOG = LoggerFactory.getLogger(MySQLIdentityBackend.class);
/**
* Constructing an instance using specified config that contains anything
* to be used to initialize an MySQL Backend.
*
* @param config used to config the backend
*/
public MySQLIdentityBackend(final Config config) {
setConfig(config);
}
public MySQLIdentityBackend() {
}
/**
* Create data base connection pool.
* @throws SQLException e
*/
private void initializeDataSource(
String driver, String url, String user, String password) throws SQLException {
dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setInitialSize(10);
dataSource.setMinIdle(3);
dataSource.setMaxActive(80);
dataSource.setMaxWait(6000);
dataSource.setTestWhileIdle(true);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(180);
dataSource.setLogAbandoned(true);
dataSource.setMinEvictableIdleTimeMillis(300000);
dataSource.setTimeBetweenEvictionRunsMillis(90000);
dataSource.setPoolPreparedStatements(true);
dataSource.setMaxOpenPreparedStatements(20);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(30);
dataSource.setAsyncInit(true);
dataSource.setFilters("stat");
}
/**
* {@inheritDoc}
*/
@Override
protected void doInitialize() throws KrbException {
LOG.info("Initializing the MySQL identity backend.");
// Initialize data base connection pool
if (MySQLIdentityBackend.dataSource == null) {
String driver = getConfig().getString(MySQLConfKey.MYSQL_DRIVER, true);
String user = getConfig().getString(MySQLConfKey.MYSQL_USER, true);
String password = getConfig().getString(MySQLConfKey.MYSQL_PASSWORD, true);
String urlString = getConfig().getString(MySQLConfKey.MYSQL_URL, true);
if (urlString == null || urlString.isEmpty()) {
urlString = getBackendConfig().getString(MySQLConfKey.MYSQL_URL, true);
}
try {
initializeDataSource(driver, urlString, user, password);
} catch (SQLException e) {
LOG.error("Failed to initialize data source. " + e.toString());
throw new KrbException("Failed to initialize data source.", e);
}
}
Connection connection = null;
ResultSet resCheckTable = null;
PreparedStatement preInitialize = null;
PreparedStatement preKdcRealm = null;
ResultSet resKdcRealm = null;
PreparedStatement preIdentity = null;
PreparedStatement preKey = null;
try {
connection = dataSource.getConnection();
resCheckTable = connection.getMetaData().getTables(null, null, "kdc_config", null);
if (resCheckTable.next()) {
// Set initialized for kdc config table if HAS enabled
String stmInitialize = "UPDATE `kdc_config` SET initialized = true WHERE id = 1";
preInitialize = connection.prepareStatement(stmInitialize);
preInitialize.executeUpdate();
// Get identity table name according to realm of kdc
String stmKdcRealm = "SELECT realm FROM `kdc_config`";
preKdcRealm = connection.prepareStatement(stmKdcRealm);
resKdcRealm = preKdcRealm.executeQuery();
if (resKdcRealm.next()) {
String realm = resKdcRealm.getString("realm").toLowerCase();
identityTable = "`" + realm + "_identity" + "`";
keyInfoTable = "`" + realm + "_key" + "`";
} else {
throw new KrbException("Failed to get kdc config.");
}
} else {
identityTable = "`" + "kerby_identity" + "`";
keyInfoTable = "`" + "kerby_key" + "`";
}
// Create identity table
String stmIdentity = "CREATE TABLE IF NOT EXISTS " + identityTable
+ " (principal varchar(255) NOT NULL, key_version INTEGER "
+ "DEFAULT 1, kdc_flags INTEGER DEFAULT 0, disabled bool "
+ "DEFAULT NULL, locked bool DEFAULT NULL, created_time "
+ "BIGINT DEFAULT 0, expire_time BIGINT DEFAULT 0, "
+ "PRIMARY KEY (principal) ) ENGINE=INNODB "
+ "DEFAULT CHARSET=utf8;";
preIdentity = connection.prepareStatement(stmIdentity);
preIdentity.executeUpdate();
// Create key table
String stmKey = "CREATE TABLE IF NOT EXISTS " + keyInfoTable
+ " (key_id INTEGER NOT NULL AUTO_INCREMENT, key_type "
+ "VARCHAR(255) DEFAULT NULL, kvno INTEGER DEFAULT -1, "
+ "key_value BLOB DEFAULT NULL, principal VARCHAR(255) NOT NULL,"
+ "PRIMARY KEY (key_id), INDEX (principal), FOREIGN KEY "
+ "(principal) REFERENCES " + identityTable + "(principal) "
+ ") ENGINE=INNODB DEFAULT CHARSET=utf8;";
preKey = connection.prepareStatement(stmKey);
preKey.executeUpdate();
} catch (SQLException e) {
LOG.error("Error occurred while initialize MySQL backend.", e);
throw new KrbException("Failed to create table in database. ", e);
} finally {
DbUtils.closeQuietly(resCheckTable);
DbUtils.closeQuietly(preInitialize);
DbUtils.closeQuietly(preKdcRealm);
DbUtils.closeQuietly(resKdcRealm);
DbUtils.closeQuietly(preIdentity);
DbUtils.closeQuietly(preKey);
DbUtils.closeQuietly(connection);
}
}
/**
* {@inheritDoc}
*/
@Override
protected void doStop() throws KrbException {
if (dataSource == null) {
return;
}
dataSource.close();
if (dataSource.isClosed()) {
LOG.info("Succeeded in closing connection with MySQL.");
} else {
throw new KrbException("Failed to close connection with MySQL.");
}
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doAddIdentity(KrbIdentity identity) throws KrbException {
String principalName = identity.getPrincipalName();
int keyVersion = identity.getKeyVersion();
int kdcFlags = identity.getKdcFlags();
boolean disabled = identity.isDisabled();
boolean locked = identity.isLocked();
long createdTime = identity.getCreatedTime().getTime();
long expireTime = identity.getExpireTime().getTime();
Map<EncryptionType, EncryptionKey> keys = identity.getKeys();
Connection connection = null;
KrbIdentity duplicateIdentity = doGetIdentity(principalName);
if (duplicateIdentity != null) {
LOG.warn("The identity maybe duplicate.");
return duplicateIdentity;
} else {
try {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
// Insert identity to identity table
String stmIdentity = "INSERT INTO " + identityTable
+ " (principal, key_version, kdc_flags, disabled, locked,"
+ " created_time, expire_time) VALUES(?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement preIdentity = connection.prepareStatement(stmIdentity)) {
preIdentity.setString(1, principalName);
preIdentity.setInt(2, keyVersion);
preIdentity.setInt(3, kdcFlags);
preIdentity.setBoolean(4, disabled);
preIdentity.setBoolean(5, locked);
preIdentity.setLong(6, createdTime);
preIdentity.setLong(7, expireTime);
preIdentity.executeUpdate();
}
// Insert keys to key table
for (Map.Entry<EncryptionType, EncryptionKey> entry : keys.entrySet()) {
String stmKey = "INSERT INTO " + keyInfoTable
+ " (key_type, kvno, key_value, principal) VALUES(?, ?, ?, ?)";
try (PreparedStatement preKey = connection.prepareStatement(stmKey)) {
preKey.setString(1, entry.getKey().getName());
preKey.setInt(2, entry.getValue().getKvno());
preKey.setBlob(3, new SerialBlob(entry.getValue().getKeyData()));
preKey.setString(4, principalName);
preKey.executeUpdate();
}
}
connection.commit();
return identity;
} catch (SQLException e) {
try {
LOG.info("Transaction is being rolled back.");
if (connection != null) {
connection.rollback();
}
} catch (SQLException ex) {
throw new KrbException("Transaction roll back failed. ", ex);
}
LOG.error("Error occurred while adding identity.");
throw new KrbException("Failed to add identity. ", e);
} finally {
DbUtils.closeQuietly(connection);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doGetIdentity(final String principalName) throws KrbException {
KrbIdentity krbIdentity = null;
Connection connection = null;
PreparedStatement preIdentity = null;
ResultSet resIdentity = null;
try {
connection = dataSource.getConnection();
// Get identity from identity and key table
String stmIdentity = String.format("SELECT * FROM %s a left join %s b on "
+ "a.principal = b.principal where a.principal = ?", identityTable, keyInfoTable);
preIdentity = connection.prepareStatement(stmIdentity);
preIdentity.setString(1, principalName);
resIdentity = preIdentity.executeQuery();
List<EncryptionKey> keys = new ArrayList<>();
if (resIdentity.isBeforeFirst()) {
while (resIdentity.next()) {
if (krbIdentity == null) {
krbIdentity = new KrbIdentity(principalName);
krbIdentity.setKeyVersion(resIdentity.getInt("key_version"));
krbIdentity.setKdcFlags(resIdentity.getInt("kdc_flags"));
krbIdentity.setDisabled(resIdentity.getBoolean("disabled"));
krbIdentity.setLocked(resIdentity.getBoolean("locked"));
krbIdentity.setCreatedTime(new KerberosTime(resIdentity.getLong("created_time")));
krbIdentity.setExpireTime(new KerberosTime(resIdentity.getLong("expire_time")));
}
// Get key info
int kvno = resIdentity.getInt("kvno");
String keyType = resIdentity.getString("key_type");
EncryptionType eType = EncryptionType.fromName(keyType);
byte[] keyValue = resIdentity.getBytes("key_value");
EncryptionKey key = new EncryptionKey(eType, keyValue, kvno);
keys.add(key);
}
if (krbIdentity != null && keys.size() > 0) {
krbIdentity.addKeys(keys);
}
return krbIdentity;
} else {
return null;
}
} catch (SQLException e) {
LOG.error("Error occurred while getting identity. " + e.toString());
throw new KrbException("Failed to get identity. ", e);
} finally {
DbUtils.closeQuietly(preIdentity);
DbUtils.closeQuietly(resIdentity);
DbUtils.closeQuietly(connection);
}
}
/**
* {@inheritDoc}
*/
@Override
protected KrbIdentity doUpdateIdentity(KrbIdentity identity) throws KrbException {
String principalName = identity.getPrincipalName();
try {
// Delete old identity
doDeleteIdentity(principalName);
// Insert new identity
doAddIdentity(identity);
} catch (KrbException e) {
LOG.error("Error occurred while updating identity: " + principalName);
throw new KrbException("Failed to update identity. ", e);
}
return getIdentity(principalName);
}
/**
* {@inheritDoc}
*/
@Override
protected void doDeleteIdentity(String principalName) throws KrbException {
Connection connection = null;
PreparedStatement preKey = null;
PreparedStatement preIdentity = null;
try {
connection = dataSource.getConnection();
connection.setAutoCommit(false);
// Delete keys from key table
String stmKey = "DELETE FROM " + keyInfoTable + " WHERE principal = ?";
preKey = connection.prepareStatement(stmKey);
preKey.setString(1, principalName);
preKey.executeUpdate();
// Delete identity from identity table
String stmIdentity = "DELETE FROM " + identityTable + " WHERE principal = ? ";
preIdentity = connection.prepareStatement(stmIdentity);
preIdentity.setString(1, principalName);
preIdentity.executeUpdate();
connection.commit();
} catch (SQLException e) {
try {
LOG.warn("Transaction is being rolled back.");
if (connection != null) {
connection.rollback();
}
} catch (SQLException ex) {
throw new KrbException("Transaction roll back failed. ", ex);
}
LOG.error("Error occurred while deleting identity.");
throw new KrbException("Failed to delete identity. ", e);
} finally {
DbUtils.closeQuietly(preIdentity);
DbUtils.closeQuietly(preKey);
DbUtils.closeQuietly(connection);
}
}
/**
* {@inheritDoc}
*/
@Override
protected Iterable<String> doGetIdentities() throws KrbException {
List<String> identityNames = new ArrayList<>();
Connection connection = null;
PreparedStatement preSmt = null;
ResultSet result = null;
try {
connection = dataSource.getConnection();
String statement = "SELECT * FROM " + identityTable;
preSmt = connection.prepareStatement(statement);
result = preSmt.executeQuery();
while (result.next()) {
identityNames.add(result.getString("principal"));
}
result.close();
preSmt.close();
} catch (SQLException e) {
LOG.error("Error occurred while getting identities.", e);
throw new KrbException("Failed to get identities. ", e);
} finally {
DbUtils.closeQuietly(preSmt);
DbUtils.closeQuietly(result);
DbUtils.closeQuietly(connection);
}
return identityNames;
}
}
| 637 |
0 | Create_ds/cordova-plugin-compat/src | Create_ds/cordova-plugin-compat/src/android/PermissionHelper.java | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import android.content.pm.PackageManager;
/**
* This class provides reflective methods for permission requesting and checking so that plugins
* written for cordova-android 5.0.0+ can still compile with earlier cordova-android versions.
*/
public class PermissionHelper {
private static final String LOG_TAG = "CordovaPermissionHelper";
/**
* Requests a "dangerous" permission for the application at runtime. This is a helper method
* alternative to cordovaInterface.requestPermission() that does not require the project to be
* built with cordova-android 5.0.0+
*
* @param plugin The plugin the permission is being requested for
* @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()
* along with the result of the permission request
* @param permission The permission to be requested
*/
public static void requestPermission(CordovaPlugin plugin, int requestCode, String permission) {
PermissionHelper.requestPermissions(plugin, requestCode, new String[] {permission});
}
/**
* Requests "dangerous" permissions for the application at runtime. This is a helper method
* alternative to cordovaInterface.requestPermissions() that does not require the project to be
* built with cordova-android 5.0.0+
*
* @param plugin The plugin the permissions are being requested for
* @param requestCode A requestCode to be passed to the plugin's onRequestPermissionResult()
* along with the result of the permissions request
* @param permissions The permissions to be requested
*/
public static void requestPermissions(CordovaPlugin plugin, int requestCode, String[] permissions) {
try {
Method requestPermission = CordovaInterface.class.getDeclaredMethod(
"requestPermissions", CordovaPlugin.class, int.class, String[].class);
// If there is no exception, then this is cordova-android 5.0.0+
requestPermission.invoke(plugin.cordova, plugin, requestCode, permissions);
} catch (NoSuchMethodException noSuchMethodException) {
// cordova-android version is less than 5.0.0, so permission is implicitly granted
LOG.d(LOG_TAG, "No need to request permissions " + Arrays.toString(permissions));
// Notify the plugin that all were granted by using more reflection
deliverPermissionResult(plugin, requestCode, permissions);
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when requesting permissions " + Arrays.toString(permissions), illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method does not throw any exceptions, so this should never be caught
LOG.e(LOG_TAG, "invocationTargetException when requesting permissions " + Arrays.toString(permissions), invocationTargetException);
}
}
/**
* Checks at runtime to see if the application has been granted a permission. This is a helper
* method alternative to cordovaInterface.hasPermission() that does not require the project to
* be built with cordova-android 5.0.0+
*
* @param plugin The plugin the permission is being checked against
* @param permission The permission to be checked
*
* @return True if the permission has already been granted and false otherwise
*/
public static boolean hasPermission(CordovaPlugin plugin, String permission) {
try {
Method hasPermission = CordovaInterface.class.getDeclaredMethod("hasPermission", String.class);
// If there is no exception, then this is cordova-android 5.0.0+
return (Boolean) hasPermission.invoke(plugin.cordova, permission);
} catch (NoSuchMethodException noSuchMethodException) {
// cordova-android version is less than 5.0.0, so permission is implicitly granted
LOG.d(LOG_TAG, "No need to check for permission " + permission);
return true;
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when checking permission " + permission, illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method does not throw any exceptions, so this should never be caught
LOG.e(LOG_TAG, "invocationTargetException when checking permission " + permission, invocationTargetException);
}
return false;
}
private static void deliverPermissionResult(CordovaPlugin plugin, int requestCode, String[] permissions) {
// Generate the request results
int[] requestResults = new int[permissions.length];
Arrays.fill(requestResults, PackageManager.PERMISSION_GRANTED);
try {
Method onRequestPermissionResult = CordovaPlugin.class.getDeclaredMethod(
"onRequestPermissionResult", int.class, String[].class, int[].class);
onRequestPermissionResult.invoke(plugin, requestCode, permissions, requestResults);
} catch (NoSuchMethodException noSuchMethodException) {
// Should never be caught since the plugin must be written for cordova-android 5.0.0+ if it
// made it to this point
LOG.e(LOG_TAG, "NoSuchMethodException when delivering permissions results", noSuchMethodException);
} catch (IllegalAccessException illegalAccessException) {
// Should never be caught; this is a public method
LOG.e(LOG_TAG, "IllegalAccessException when delivering permissions results", illegalAccessException);
} catch(InvocationTargetException invocationTargetException) {
// This method may throw a JSONException. We are just duplicating cordova-android's
// exception handling behavior here; all it does is log the exception in CordovaActivity,
// print the stacktrace, and ignore it
LOG.e(LOG_TAG, "InvocationTargetException when delivering permissions results", invocationTargetException);
}
}
}
| 638 |
0 | Create_ds/cordova-plugin-compat/src | Create_ds/cordova-plugin-compat/src/android/BuildHelper.java | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
/*
* This is a utility class that allows us to get the BuildConfig variable, which is required
* for the use of different providers. This is not guaranteed to work, and it's better for this
* to be set in the build step in config.xml
*
*/
import android.app.Activity;
import android.content.Context;
import java.lang.reflect.Field;
public class BuildHelper {
private static String TAG="BuildHelper";
/*
* This needs to be implemented if you wish to use the Camera Plugin or other plugins
* that read the Build Configuration.
*
* Thanks to Phil@Medtronic and Graham Borland for finding the answer and posting it to
* StackOverflow. This is annoying as hell! However, this method does not work with
* ProGuard, and you should use the config.xml to define the application_id
*
*/
public static Object getBuildConfigValue(Context ctx, String key)
{
try
{
Class<?> clazz = Class.forName(ctx.getPackageName() + ".BuildConfig");
Field field = clazz.getField(key);
return field.get(null);
} catch (ClassNotFoundException e) {
LOG.d(TAG, "Unable to get the BuildConfig, is this built with ANT?");
e.printStackTrace();
} catch (NoSuchFieldException e) {
LOG.d(TAG, key + " is not a valid field. Check your build.gradle");
} catch (IllegalAccessException e) {
LOG.d(TAG, "Illegal Access Exception: Let's print a stack trace.");
e.printStackTrace();
}
return null;
}
}
| 639 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/androidTest/java/sample/here/paypal/com | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/androidTest/java/sample/here/paypal/com/heresdksampleapp/ApplicationTest.java | package sample.here.paypal.com.heresdksampleapp;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 640 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/ToolbarActivity.java | package com.paypal.heresdk.sampleapp.ui;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.view.MenuItem;
import com.paypal.heresdk.sampleapp.R;
public abstract class ToolbarActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
setupToolbar();
}
public abstract int getLayoutResId();
private void setupToolbar(){
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == android.R.id.home){
onBackPressed();
return true;
}
return false;
}
}
| 641 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/ReaderConnectionActivity.java | package com.paypal.heresdk.sampleapp.ui;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.text.LoginFilter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.heresdk.sampleapp.login.LoginActivity;
import com.paypal.paypalretailsdk.DeviceManager;
import com.paypal.paypalretailsdk.PaymentDevice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
public class ReaderConnectionActivity extends ToolbarActivity implements View.OnClickListener
{
private static final String LOG_TAG = ReaderConnectionActivity.class.getSimpleName();
public static final String INTENT_STRING_EMV_READER = "EMV_READER";
public static final String INTENT_STRING_AUDIO_JACK_READER = "AUDIO_JACK_READER";
private StepView findConnectStep;
private StepView connectLastStep;
private StepView autoConnectStep;
@Override
public int getLayoutResId()
{
return R.layout.reader_connection_activity;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
findConnectStep = (StepView)findViewById(R.id.find_connect_step);
findConnectStep.setOnButtonClickListener(this);
connectLastStep = (StepView)findViewById(R.id.connect_last_step);
connectLastStep.setOnButtonClickListener(this);
autoConnectStep = (StepView)findViewById(R.id.auto_connect_step);
autoConnectStep.setOnButtonClickListener(this);
}
public void onFindAndConnectClicked()
{
RetailSDK.getDeviceManager().searchAndConnect(new DeviceManager.ConnectionCallback()
{
@Override
public void connection(final RetailSDKException error, final PaymentDevice cardReader)
{
ReaderConnectionActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (error == null)
{
//Toast.makeText(getApplicationContext(), "Connected to card reader" + cardReader.getId(), Toast.LENGTH_SHORT).show();
onReaderConnected(cardReader);
}
else
{
Log.e(LOG_TAG, "Connection to a reader failed with error: " + error);
Toast.makeText(getApplicationContext(), "Card reader connection error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void onConnectToLastClicked()
{
RetailSDK.getDeviceManager().connectToLastActiveReader(new DeviceManager.ConnectionCallback()
{
@Override
public void connection(final RetailSDKException error, final PaymentDevice cardReader)
{
ReaderConnectionActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (error == null && cardReader != null)
{
//Toast.makeText(getApplicationContext(), "Connected to last active device " + cardReader.getId(), Toast.LENGTH_SHORT).show();
onReaderConnected(cardReader);
}
else if (error != null)
{
Toast.makeText(getApplicationContext(), "Connection to a reader failed with error: " + error, Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Connection to a reader failed with error: " + error);
}
else
{
Toast.makeText(getApplicationContext(), "Could not find the last card reader to connect to", Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "Could not find the last card reader to connect to");
}
}
});
}
});
}
private void onReaderConnected(PaymentDevice cardReader)
{
Log.d(LOG_TAG, "Connected to device " + cardReader.getId());
final TextView readerIdTxt = (TextView) findViewById(R.id.textReaderId);
readerIdTxt.setText(getString(R.string.connected) + " " + cardReader.getId());
final LinearLayout runTxnButtonContainer = (LinearLayout) findViewById(R.id.run_txn_btn_container);
runTxnButtonContainer.setVisibility(View.VISIBLE);
}
public void onRunTransactionClicked(View view)
{
Intent transactionIntent = new Intent(ReaderConnectionActivity.this, ChargeActivity.class);
transactionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(transactionIntent);
}
public void onAutoConnectClicked() {
autoConnectStep.showProgressBar();
String lastKnowReader = RetailSDK.getDeviceManager().getLastActiveBluetoothReader();
RetailSDK.getDeviceManager().scanAndAutoConnectToBluetoothReader(lastKnowReader, new DeviceManager.ConnectionCallback() {
@Override
public void connection(final RetailSDKException error, final PaymentDevice cardReader) {
ReaderConnectionActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
autoConnectStep.hideProgressBarShowButton();
if (error == null && cardReader != null) {
//Toast.makeText(getApplicationContext(), "Connected to last active device " + cardReader.getId(), Toast.LENGTH_SHORT).show();
onReaderConnected(cardReader);
} else if (error != null) {
Toast.makeText(getApplicationContext(), "Connection to a reader failed with error: " + error, Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Connection to a reader failed with error: " + error);
} else {
Toast.makeText(getApplicationContext(), "Could not find the last card reader to connect to", Toast.LENGTH_SHORT).show();
Log.d(LOG_TAG, "Could not find the last card reader to connect to");
}
}
});
}
});
}
@Override
public void onClick(View v)
{
if (v == findConnectStep.getButton()){
onFindAndConnectClicked();
}else if(v == connectLastStep.getButton()){
onConnectToLastClicked();
}else if(v == autoConnectStep.getButton()){
onAutoConnectClicked();
}
}
}
| 642 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/VaultActivity.java | package com.paypal.heresdk.sampleapp.ui;
import java.math.BigDecimal;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
/**
* Created by muozdemir on 11/1/18.
*/
public class VaultActivity extends ToolbarActivity
{
private static final String LOG_TAG = VaultActivity.class.getSimpleName();
public static final String INTENT_VAULT_ID = "VAULT_ID";
StepView goBack;
String vaultId;
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==android.R.id.home){
goBackToChargeActivity();
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
Intent intent = getIntent();
if (intent.hasExtra(INTENT_VAULT_ID))
{
vaultId = (String) intent.getSerializableExtra(INTENT_VAULT_ID);
Log.d(LOG_TAG, "onCreate vaultId:" + vaultId);
final TextView vaultIdTxt = (TextView) findViewById(R.id.vault_id);
vaultIdTxt.setText("Your vault of " + vaultId +" was successful");
}
goBack = (StepView) findViewById(R.id.go_back_step);
goBack.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
goBackToChargeActivity();
}
});
}
@Override
public int getLayoutResId()
{
return R.layout.vault_activity;
}
public void goBackToChargeActivity()
{
Log.d(LOG_TAG, "goToChargeActivity");
Intent intent = new Intent(VaultActivity.this, ChargeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
| 643 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/PaymentOptionsActivity.java | package com.paypal.heresdk.sampleapp.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Switch;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultType;
public class PaymentOptionsActivity extends ToolbarActivity
{
final private String logComponent = "PaymentOptionsActivity";
Switch authCaptureSwitch;
Switch promptAppSwitch;
Switch promptReaderSwitch;
Switch amountTippingSwitch;
Switch enableQuickChipSwitch;
Switch readerTipSwitch;
EditText tagTxt;
CheckBox chipBox;
CheckBox contactlessBox;
CheckBox magneticSwipeBox;
CheckBox manualCardBox;
CheckBox secureManualBox;
LinearLayout ll_customerId;
EditText customerId;
RadioGroup radioGroupVault;
TransactionBeginOptionsVaultType vaultType;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_options_dialog);
authCaptureSwitch = (Switch) findViewById(R.id.auth_capture_switch);
promptReaderSwitch = (Switch) findViewById(R.id.show_prompt_card_reader_switch);
promptAppSwitch = (Switch) findViewById(R.id.show_prompt_app_switch);
readerTipSwitch = (Switch) findViewById(R.id.tipping_reader_switch);
amountTippingSwitch = (Switch) findViewById(R.id.amount_tipping_switch);
enableQuickChipSwitch = (Switch) findViewById(R.id.enable_quick_chip_switch);
radioGroupVault = (RadioGroup) findViewById(R.id.vaultRadioGroup);
vaultType = TransactionBeginOptionsVaultType.PayOnly;
radioGroupVault.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
// find which radio button is selected
if(checkedId == R.id.payOnlyButton) {
vaultType = TransactionBeginOptionsVaultType.PayOnly;
} else if(checkedId == R.id.vaultOnlyButton) {
vaultType = TransactionBeginOptionsVaultType.VaultOnly;
} else {
vaultType = TransactionBeginOptionsVaultType.PayAndVault;
}
}
});
tagTxt = (EditText) findViewById(R.id.tag);
magneticSwipeBox = (CheckBox) findViewById(R.id.magnetic_swipe);
chipBox = (CheckBox) findViewById(R.id.chip);
contactlessBox = (CheckBox) findViewById(R.id.contactless);
secureManualBox = (CheckBox) findViewById(R.id.secure_manual);
manualCardBox = (CheckBox) findViewById(R.id.manual_card);
ll_customerId = (LinearLayout) findViewById(R.id.ll_customer_id);
customerId = (EditText) findViewById(R.id.customer_id);
Bundle options = getIntent().getExtras();
if (options!=null)
{
authCaptureSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_AUTH_CAPTURE));
// vaultSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_VAULT_ONLY));
promptReaderSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_CARD_READER_PROMPT));
promptAppSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_APP_PROMPT));
readerTipSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_TIP_ON_READER));
amountTippingSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_AMOUNT_TIP));
enableQuickChipSwitch.setChecked(options.getBoolean(ChargeActivity.OPTION_QUICK_CHIP_ENABLED));
chipBox.setChecked(options.getBoolean(ChargeActivity.OPTION_CHIP));
magneticSwipeBox.setChecked(options.getBoolean(ChargeActivity.OPTION_MAGNETIC_SWIPE));
contactlessBox.setChecked(options.getBoolean(ChargeActivity.OPTION_CONTACTLESS));
secureManualBox.setChecked(options.getBoolean(ChargeActivity.OPTION_SECURE_MANUAL));
manualCardBox.setChecked(options.getBoolean(ChargeActivity.OPTION_MANUAL_CARD));
customerId.setText(options.getString(ChargeActivity.OPTION_CUSTOMER_ID));
tagTxt.setText(options.getString(ChargeActivity.OPTION_TAG));
}
}
@Override
protected void onPause()
{
super.onPause();
}
public void onDoneClicked(View view){
Intent data = new Intent();
data.putExtras(getOptionsBundle());
setResult(RESULT_OK,data);
finish();
}
@Override
public int getLayoutResId()
{
return R.layout.activity_payment_options;
}
private Bundle getOptionsBundle()
{
Bundle bundle = new Bundle();
bundle.putBoolean(ChargeActivity.OPTION_AUTH_CAPTURE,authCaptureSwitch.isChecked());
bundle.putInt(ChargeActivity.OPTION_VAULT_TYPE, vaultType.getValue());
bundle.putBoolean(ChargeActivity.OPTION_CARD_READER_PROMPT,promptReaderSwitch.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_APP_PROMPT,promptAppSwitch.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_TIP_ON_READER,readerTipSwitch.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_AMOUNT_TIP,amountTippingSwitch.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_QUICK_CHIP_ENABLED, enableQuickChipSwitch.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_MAGNETIC_SWIPE,magneticSwipeBox.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_CHIP,chipBox.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_CONTACTLESS,contactlessBox.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_MANUAL_CARD,manualCardBox.isChecked());
bundle.putBoolean(ChargeActivity.OPTION_SECURE_MANUAL,secureManualBox.isChecked());
bundle.putString(ChargeActivity.OPTION_CUSTOMER_ID,customerId.getText().toString());
bundle.putString(ChargeActivity.OPTION_TAG,tagTxt.getText().toString());
return bundle;
}
}
| 644 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/MainActivity.java | package com.paypal.heresdk.sampleapp.ui;
/**
* Created by muozdemir on 12/5/17.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.paypal.heresdk.sampleapp.login.LoginActivity;
import com.paypal.heresdk.sampleapp.R;
public class MainActivity extends Activity
{
private static final String LOG_TAG = MainActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
}
public void onStartClicked(View view)
{
Log.d(LOG_TAG, "goToLoginActivity");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
} | 645 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/EditTextPreference.java | package com.paypal.heresdk.sampleapp.ui;
import android.content.Context;
import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.widget.EditText;
import com.paypal.heresdk.sampleapp.R;
/* Custom preference to show editText in preferenceFragment.
Android's default EditTextPreference{@link android.support.v7.preference.EditTextPreference},
shows the EditText in a Dialog box */
public class EditTextPreference extends Preference
{
private EditText tagEditText;
private String text;
public EditTextPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
setLayoutResource(R.layout.edit_text_preference);
}
public EditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setLayoutResource(R.layout.edit_text_preference);
}
@Override
public void onBindViewHolder(PreferenceViewHolder holder)
{
super.onBindViewHolder(holder);
tagEditText = (EditText) holder.itemView;
tagEditText.setText(text);
}
public String getText(){
return tagEditText.getText().toString();
}
public void setText(String text){
this.text = text;
if(tagEditText!=null){
tagEditText.setText(text);
}
}
}
| 646 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/CaptureActivity.java | package com.paypal.heresdk.sampleapp.ui;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.InvoicePayment;
import com.paypal.paypalretailsdk.InvoiceStatus;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailInvoicePayment;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
/**
* Created by muozdemir on 1/9/18.
*/
public class CaptureActivity extends ToolbarActivity
{
private static final String LOG_TAG = CaptureActivity.class.getSimpleName();
public static final String INTENT_AUTH_TOTAL_AMOUNT = "TOTAL_AMOUNT";
public static final String INTENT_CAPTURE_TOTAL_AMOUNT = "CAPTURE_AMOUNT";
public static final String INTENT_AUTH_ID = "AUTH_ID";
public static final String INTENT_INVOICE_ID = "INVOICE_ID";
public static RetailInvoice invoiceForRefundCaptured = null;
private ProgressDialog mProgressDialog = null;
BigDecimal authAmount;
BigDecimal captureAmount;
String authId;
String invoiceId;
String captureId;
EditText amountEditText;
@Override
public int getLayoutResId()
{
return R.layout.capture_activity;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
setContentView(R.layout.capture_activity);
Intent intent = getIntent();
authAmount = new BigDecimal(0.0);
amountEditText = (EditText)findViewById(R.id.amount);
amountEditText.setHint(getString(R.string.authorization_amount) + " (" + NumberFormat.getCurrencyInstance().getCurrency().getSymbol() + ")");
if (intent.hasExtra(INTENT_AUTH_TOTAL_AMOUNT))
{
authAmount = (BigDecimal) intent.getSerializableExtra(INTENT_AUTH_TOTAL_AMOUNT);
authId = (String) intent.getSerializableExtra(INTENT_AUTH_ID);
invoiceId = (String) intent.getSerializableExtra(INTENT_INVOICE_ID);
Log.d(LOG_TAG, "onCreate amount:" + authAmount);
}
}
public void onCaptureClicked(View view)
{
showProcessingProgressbar();
EditText amountEditText = (EditText) findViewById(R.id.amount);
String amountText = amountEditText.getText().toString();
captureAmount = BigDecimal.ZERO;
if (null != amountText && amountText.length() > 0) {
amountText = String.format("%.2f", Double.parseDouble(amountText));
captureAmount = new BigDecimal(amountText);
if (captureAmount.compareTo(BigDecimal.ZERO) == 0)
{
showInvalidAmountAlertDialog();
return;
}
}
else
{
showInvalidAmountAlertDialog();
return;
}
Log.d(LOG_TAG, "onCaptureClicked capture amount:" + captureAmount);
BigDecimal gratuity = BigDecimal.ZERO;
if (captureAmount.compareTo(authAmount) > 0)
{
gratuity = captureAmount.subtract(authAmount);
}
Log.d(LOG_TAG, "onCaptureClicked gratuity amount:" + gratuity);
RetailSDK.getTransactionManager().captureAuthorization(authId, invoiceId, captureAmount, gratuity, "USD", new TransactionManager.CaptureAuthorizedTransactionCallback()
{
@Override
public void captureAuthorizedTransaction(final RetailSDKException error, final String captureId)
{
CaptureActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
cancelProgressbar();
if (error != null)
{
if (error.getDeveloperMessage() == null || error.getDeveloperMessage().isEmpty())
{
Log.d(LOG_TAG, "void capture error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "void capture error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
else
{
Log.d(LOG_TAG, "void capture error: " + error.getDeveloperMessage());
Toast.makeText(getApplicationContext(), "void capture error: " + error.getDeveloperMessage(), Toast.LENGTH_SHORT).show();
}
}
else
{
CaptureActivity.this.captureId = captureId;
Log.d(LOG_TAG, captureId + " captured.");
Toast.makeText(getApplicationContext(), captureId + " captured ", Toast.LENGTH_SHORT).show();
goToRefundActivity();
}
}
});
}
});
}
public void goToRefundActivity(){
Log.d(LOG_TAG, "goToRefundActivity");
//Get the refund data
invoiceForRefundCaptured = new RetailInvoice(null);
invoiceForRefundCaptured.setStatus(InvoiceStatus.PAID);
RetailInvoicePayment invoicePayment = new RetailInvoicePayment();
invoicePayment.setTransactionID(captureId);
List<InvoicePayment> list = new ArrayList<>();
list.add(invoicePayment);
invoiceForRefundCaptured.setPayments(list);
RefundActivity.invoiceForRefundCaptured = invoiceForRefundCaptured;
Intent refundIntent = new Intent(CaptureActivity.this, RefundActivity.class);
Log.d(LOG_TAG, "goToRefundActivity total: " + captureAmount);
refundIntent.putExtra(INTENT_CAPTURE_TOTAL_AMOUNT, captureAmount);
refundIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(refundIntent);
}
public void goBackToChargeActivity()
{
Log.d(LOG_TAG, "goToChargeActivity");
Intent intent = new Intent(CaptureActivity.this, ChargeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void showInvalidAmountAlertDialog(){
Log.d(LOG_TAG, "showInvalidAmountAlertDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.this);
builder.setTitle(R.string.error_title);
builder.setMessage(R.string.error_invalid_amount);
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(LOG_TAG, "takePayment invalid amount alert dialog onClick");
dialog.dismiss();
}
});
builder.create().show();
}
private void showProcessingProgressbar()
{
mProgressDialog = new ProgressDialog(CaptureActivity.this);
mProgressDialog.setMessage(getString(R.string.capturing_msg));
mProgressDialog.show();
}
private void cancelProgressbar()
{
if (null != mProgressDialog && mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
}
| 647 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/ChargeActivity.java | package com.paypal.heresdk.sampleapp.ui;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.DeviceUpdate;
import com.paypal.paypalretailsdk.FormFactor;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.OfflinePaymentInfo;
import com.paypal.paypalretailsdk.OfflinePaymentStatus;
import com.paypal.paypalretailsdk.OfflineTransactionRecord;
import com.paypal.paypalretailsdk.PaymentDevice;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionBeginOptions;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultProvider;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultType;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
import com.paypal.paypalretailsdk.VaultRecord;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class ChargeActivity extends ToolbarActivity implements View.OnClickListener
{
private static final String LOG_TAG = ChargeActivity.class.getSimpleName();
public static final String INTENT_TRANX_TOTAL_AMOUNT = "TOTAL_AMOUNT";
public static final String INTENT_AUTH_ID = "AUTH_ID";
public static final String INTENT_INVOICE_ID = "INVOICE_ID";
public static final String INTENT_VAULT_ID = "VAULT_ID";
private static final int REQUEST_OPTIONS_ACTIVITY = 1;
TransactionContext currentTransaction;
RetailInvoice currentInvoice;
Invoice invoiceForRefund;
private EditText amountEditText;
private StepView createInvoiceStep;
private StepView createTxnStep;
private StepView acceptTxnStep;
private LinearLayout paymentOptionsStep;
private TextView step3Text;
private TextView paymentOptionsText;
private ImageView paymentOptionsArrow;
private LinearLayout offlineModeContainer;
private TextView enabledText;
private SharedPreferences sharedPrefs;
// payment option constants
public static final String OPTION_AUTH_CAPTURE = "authCapture";
public static final String OPTION_VAULT_TYPE = "vaultType";
public static final String OPTION_CARD_READER_PROMPT = "cardReader";
public static final String OPTION_APP_PROMPT= "appPrompt";
public static final String OPTION_TIP_ON_READER = "tipReader";
public static final String OPTION_AMOUNT_TIP = "amountTip";
public static final String OPTION_QUICK_CHIP_ENABLED = "quickChipEnabled";
public static final String OPTION_MAGNETIC_SWIPE = "magneticSwipe";
public static final String OPTION_CHIP = "chip";
public static final String OPTION_CONTACTLESS = "contactless";
public static final String OPTION_MANUAL_CARD= "manualCard";
public static final String OPTION_SECURE_MANUAL= "secureManual";
public static final String OPTION_CUSTOMER_ID= "customoerId";
public static final String OPTION_TAG= "tag";
// payment option booleans
private boolean isAuthCaptureEnabled = false;
private TransactionBeginOptionsVaultType vaultType = TransactionBeginOptionsVaultType.PayOnly;
private boolean isCardReaderPromptEnabled = true;
private boolean isAppPromptEnabled = true;
private boolean isTippingOnReaderEnabled = false;
private boolean isAmountBasedTippingEnabled = false;
private boolean isQuickChipEnabled = false;
private boolean isMagneticSwipeEnabled = true;
private boolean isChipEnabled = true;
private boolean isContactlessEnabled = true;
private boolean isManualCardEnabled = true;
private boolean isSecureManualEnabled = true;
private String customerId = "";
private String tagString = "";
private String mVaultId = "";
@Override
public int getLayoutResId()
{
return R.layout.transaction_activity;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
amountEditText = (EditText)findViewById(R.id.amount);
TextView paymentAmountText = (TextView) findViewById(R.id.payment_amount_text);
paymentAmountText.setText(getString(R.string.payment_amount) + " (" + NumberFormat.getCurrencyInstance().getCurrency().getSymbol() + ")");
createInvoiceStep = (StepView)findViewById(R.id.create_invoice_step);
createInvoiceStep.setOnButtonClickListener(this);
createTxnStep = (StepView)findViewById(R.id.create_txn_step);
createTxnStep.setOnButtonClickListener(this);
acceptTxnStep = (StepView)findViewById(R.id.accept_txn_step);
acceptTxnStep.setOnButtonClickListener(this);
paymentOptionsStep = (LinearLayout) findViewById(R.id.payment_options_container);
paymentOptionsStep.setOnClickListener(this);
paymentOptionsText = (TextView) findViewById(R.id.payment_options_text);
// step3Text = (TextView) findViewById(R.id.step3_text);
paymentOptionsArrow = (ImageView) findViewById(R.id.payment_options_arrow);
// disablePaymentOptionsStep();
offlineModeContainer = (LinearLayout) findViewById(R.id.offline_mode_container);
offlineModeContainer.setOnClickListener(this);
sharedPrefs = getSharedPreferences(OfflinePayActivity.PREF_NAME, Context.MODE_PRIVATE);
enabledText = (TextView) findViewById(R.id.offline_mode_status_text);
amountEditText.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if (actionId == EditorInfo.IME_ACTION_DONE){
if (TextUtils.isEmpty(amountEditText.getText().toString()))
{
Toast.makeText(ChargeActivity.this, "Amount cannot be empty", Toast.LENGTH_SHORT).show();
return true;
}else
{
createInvoiceStep.setStepEnabled();
createTxnStep.setStepDisabled();
// disablePaymentOptionsStep();
paymentOptionsStep.setOnClickListener(null);
acceptTxnStep.setStepDisabled();
return false;
}
}
return false;
}
});
}
@Override
protected void onResume()
{
super.onResume();
if(sharedPrefs.getBoolean(OfflinePayActivity.OFFLINE_MODE,false))
{
enabledText.setText("ENABLED");
enabledText.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
if (RetailSDK.getTransactionManager().getOfflinePaymentEligibility()){
RetailSDK.getTransactionManager().startOfflinePayment(new TransactionManager.OfflinePaymentStatusCallback() {
@Override
public void offlinePaymentStatus(RetailSDKException error, OfflinePaymentInfo offlinePaymentInfo) {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getDeveloperMessage(), Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Merchant not whitelisted for offline payments", Toast.LENGTH_LONG).show();
}
}else{
enabledText.setText("DISABLED");
enabledText.setTextColor(getResources().getColor(android.R.color.holo_red_light));
RetailSDK.getTransactionManager().stopOfflinePayment(new TransactionManager.OfflinePaymentStatusCallback()
{
@Override
public void offlinePaymentStatus(RetailSDKException error, OfflinePaymentInfo offlinePaymentInfo)
{
if (error != null) {
Toast.makeText(getApplicationContext(), error.getDeveloperMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
public void enablePaymentOptionsStep(){
paymentOptionsArrow.setAlpha(1f);
paymentOptionsText.setTextColor(getResources().getColor(R.color.sdk_black));
// step3Text.setTextColor(getResources().getColor(R.color.sdk_black));
paymentOptionsStep.setOnClickListener(this);
}
public void disablePaymentOptionsStep(){
paymentOptionsArrow.setAlpha(0.5f);
paymentOptionsText.setTextColor(getResources().getColor(R.color.sdk_gray));
// step3Text.setTextColor(getResources().getColor(R.color.sdk_gray));
paymentOptionsStep.setOnClickListener(null);
}
public void onCreateInvoiceClicked()
{
Log.d(LOG_TAG, "onCreateInvoiceClicked");
if (vaultType == TransactionBeginOptionsVaultType.VaultOnly)
{
return;
}
amountEditText = (EditText) findViewById(R.id.amount);
String amountText = amountEditText.getText().toString();
BigDecimal amount = BigDecimal.ZERO;
if (null != amountText && amountText.length() > 0) {
amountText = String.format("%.2f", Double.parseDouble(amountText));
amount = new BigDecimal(amountText);
if (amount.compareTo(BigDecimal.ZERO) == 0)
{
showInvalidAmountAlertDialog();
return;
}
}
else
{
showInvalidAmountAlertDialog();
return;
}
Log.d(LOG_TAG, "onCreateInvoiceClicked amount:" + amount);
currentInvoice = new RetailInvoice(RetailSDK.getMerchant().getCurrency());
BigDecimal quantity = new BigDecimal(1);
currentInvoice.addItem("Item", quantity, amount, 1, null);
// BigDecimal gratuityAmt = new BigDecimal(gratuityField.getText().toString());
// if(gratuityAmt.intValue() > 0){
// invoice.setGratuityAmount(gratuityAmt);
// }
}
public void onCreateTransactionClicked()
{
Log.d(LOG_TAG, "onCreateTransactionClicked");
if (vaultType == TransactionBeginOptionsVaultType.VaultOnly) {
RetailSDK.getTransactionManager().createVaultTransaction(new TransactionManager.TransactionCallback()
{
@Override
public void transaction(RetailSDKException e, TransactionContext context)
{
if (e != null) {
final String errorTxt = e.toString();
ChargeActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "create transaction error: " + errorTxt, Toast.LENGTH_SHORT).show();
}
});
}else{
currentTransaction = context;
}
}
});
}
else {
RetailSDK.getTransactionManager().createTransaction(currentInvoice, new TransactionManager.TransactionCallback()
{
@Override
public void transaction(RetailSDKException e, final TransactionContext context)
{
if (e != null) {
final String errorTxt = e.toString();
ChargeActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "create transaction error: " + errorTxt, Toast.LENGTH_SHORT).show();
}
});
}else{
currentTransaction = context;
}
}
});
}
}
public void onAcceptTransactionClicked()
{
Log.d(LOG_TAG, "onAcceptTransactionClicked");
PaymentDevice activeDevice = RetailSDK.getDeviceManager().getActiveReader();
DeviceUpdate deviceUpdate = activeDevice.getPendingUpdate();
if (deviceUpdate != null && deviceUpdate.getIsRequired() && !deviceUpdate.getWasInstalled())
{
deviceUpdate.offer(new DeviceUpdate.CompletedCallback()
{
@Override
public void completed(RetailSDKException e, Boolean aBoolean)
{
Log.d(LOG_TAG, "device update completed");
ChargeActivity.this.beginPayment();
}
});
}
else {
beginPayment();
}
}
private void beginPayment()
{
currentTransaction.setCompletedHandler(new TransactionContext.TransactionCompletedCallback() {
@Override
public void transactionCompleted(RetailSDKException error, TransactionRecord record) {
ChargeActivity.this.transactionCompleted(error, record);
}
});
currentTransaction.setVaultCompletedHandler(new TransactionContext.VaultCompletedCallback()
{
@Override
public void vaultCompleted(RetailSDKException error, VaultRecord record)
{
ChargeActivity.this.vaultCompleted(error, record);
}
});
currentTransaction.setOfflineTransactionAdditionHandler(new TransactionContext.OfflineTransactionAddedCallback() {
@Override
public void offlineTransactionAdded(RetailSDKException error, OfflineTransactionRecord offlineTransactionRecord)
{
ChargeActivity.this.offlineTransactionAdded(error, offlineTransactionRecord);
}
});
TransactionBeginOptions options = new TransactionBeginOptions();
options.setShowPromptInCardReader(isCardReaderPromptEnabled);
options.setShowPromptInApp(isAppPromptEnabled);
options.setIsAuthCapture(isAuthCaptureEnabled);
options.setAmountBasedTipping(isAmountBasedTippingEnabled);
options.setQuickChipEnabled(isQuickChipEnabled);
options.setTippingOnReaderEnabled(isTippingOnReaderEnabled);
options.setTag(tagString);
options.setPreferredFormFactors(getPreferredFormFactors());
if (vaultType == TransactionBeginOptionsVaultType.VaultOnly)
{
options.setVaultCustomerId(customerId);
options.setVaultType(TransactionBeginOptionsVaultType.VaultOnly);
options.setVaultProvider(TransactionBeginOptionsVaultProvider.Braintree);
} else if (vaultType == TransactionBeginOptionsVaultType.PayAndVault) {
options.setVaultCustomerId(customerId);
options.setVaultType(TransactionBeginOptionsVaultType.PayAndVault);
options.setVaultProvider(TransactionBeginOptionsVaultProvider.Braintree);
}
else
{
options.setVaultType(TransactionBeginOptionsVaultType.PayOnly);
// we want to send customerId even for pay only txs.
// BT merchants can make payments and add customer id with it.
if (!customerId.isEmpty()) {
options.setVaultCustomerId(customerId);
}
}
currentTransaction.beginPayment(options);
}
void transactionCompleted(RetailSDKException error, final TransactionRecord record) {
if (error != null) {
final String errorTxt = error.toString();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "transaction error: " + errorTxt, Toast.LENGTH_SHORT).show();
// refundButton.setEnabled(false);
finish();
startActivity(getIntent());
}
});
} else {
invoiceForRefund = currentTransaction.getInvoice();
final String recordTxt = record.getTransactionNumber();
this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (isAuthCaptureEnabled) {
goToAuthCaptureActivity(record);
}
else
{
goToRefundActivity();
}
Toast.makeText(getApplicationContext(), String.format("Completed Transaction %s", recordTxt), Toast.LENGTH_SHORT).show();
}
});
}
}
void vaultCompleted(RetailSDKException error, final VaultRecord record) {
if (error != null)
{
final String errorTxt = error.toString();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "vault error: " + errorTxt, Toast.LENGTH_SHORT).show();
//refundButton.setEnabled(false);
}
});
}
else
{
invoiceForRefund = currentTransaction.getInvoice();
final String recordTxt = record.getVaultId();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (vaultType == TransactionBeginOptionsVaultType.VaultOnly)
{
goToVaultActivity(record);
}
else // payAndVault
{
mVaultId = record.getVaultId();
}
Toast.makeText(getApplicationContext(), String.format("Completed Vault %s", recordTxt), Toast.LENGTH_SHORT).show();
}
});
}
}
void offlineTransactionAdded(RetailSDKException error, final OfflineTransactionRecord record) {
if (error != null)
{
final String errorTxt = error.toString();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "offline error: " + errorTxt, Toast.LENGTH_SHORT).show();
//refundButton.setEnabled(false);
}
});
}
else
{
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "offline success: " + record.getId(), Toast.LENGTH_SHORT).show();
//refundButton.setEnabled(false);
}
});
goToOfflinePayCompleteActivity();
}
}
private void goToOfflinePayCompleteActivity()
{
Intent intent = new Intent(ChargeActivity.this,OfflinePaySuccessActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void goToAuthCaptureActivity(TransactionRecord record){
Log.d(LOG_TAG, "goToAuthCaptureActivity");
AuthCaptureActivity.invoiceForRefund = invoiceForRefund;
Intent intent = new Intent(ChargeActivity.this, AuthCaptureActivity.class);
String authId = record.getTransactionNumber();
String invoiceId = record.getInvoiceId();
BigDecimal amount = currentInvoice.getTotal();
Log.d(LOG_TAG, "goToAuthCaptureActivity total: " + amount);
intent.putExtra(INTENT_TRANX_TOTAL_AMOUNT, amount);
intent.putExtra(INTENT_AUTH_ID, authId);
intent.putExtra(INTENT_INVOICE_ID, invoiceId);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void goToVaultActivity(VaultRecord record){
Log.d(LOG_TAG, "goToVaultActivity");
Intent intent = new Intent(ChargeActivity.this, VaultActivity.class);
String vaultId = record.getVaultId();
Log.d(LOG_TAG, "goToAuthCaptureActivity vaultId: " + vaultId);
intent.putExtra(INTENT_VAULT_ID, vaultId);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void goToRefundActivity(){
Log.d(LOG_TAG, "goToRefundActivity");
RefundActivity.invoiceForRefund = invoiceForRefund;
Intent refundIntent = new Intent(ChargeActivity.this, RefundActivity.class);
BigDecimal amount = currentInvoice.getTotal();
Log.d(LOG_TAG, "goToRefundActivity total: " + amount);
refundIntent.putExtra(INTENT_TRANX_TOTAL_AMOUNT, amount);
if (vaultType == TransactionBeginOptionsVaultType.PayAndVault) {
refundIntent.putExtra(INTENT_VAULT_ID, mVaultId);
}
refundIntent.putExtra(INTENT_VAULT_ID, mVaultId);
refundIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(refundIntent);
}
private void showInvalidAmountAlertDialog(){
Log.d(LOG_TAG, "showInvalidAmountAlertDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(ChargeActivity.this);
builder.setTitle(R.string.error_title);
builder.setMessage(R.string.error_invalid_amount);
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(LOG_TAG, "takePayment invalid amount alert dialog onClick");
dialog.dismiss();
}
});
builder.create().show();
}
private void showTransactionAlreadyCreatedDialog(){
Log.d(LOG_TAG, "showTransactionAlreadyCreatedDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(ChargeActivity.this);
builder.setTitle(R.string.dialog_transaction_created_title);
builder.setMessage(R.string.dialog_transaction_created_message);
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(LOG_TAG, "show Transaction Already Created Dialog onClick");
dialog.dismiss();
}
});
builder.create().show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == REQUEST_OPTIONS_ACTIVITY)
{
Bundle optionsBundle = data.getExtras();
isAuthCaptureEnabled = optionsBundle.getBoolean(OPTION_AUTH_CAPTURE);
vaultType = TransactionBeginOptionsVaultType.fromInt(optionsBundle.getInt(OPTION_VAULT_TYPE));
isAppPromptEnabled = optionsBundle.getBoolean(OPTION_APP_PROMPT);
isTippingOnReaderEnabled = optionsBundle.getBoolean(OPTION_TIP_ON_READER);
isAmountBasedTippingEnabled = optionsBundle.getBoolean(OPTION_AMOUNT_TIP);
isQuickChipEnabled = optionsBundle.getBoolean(OPTION_QUICK_CHIP_ENABLED);
isMagneticSwipeEnabled = optionsBundle.getBoolean(OPTION_MAGNETIC_SWIPE);
isChipEnabled = optionsBundle.getBoolean(OPTION_CHIP);
isContactlessEnabled = optionsBundle.getBoolean(OPTION_CONTACTLESS);
isManualCardEnabled = optionsBundle.getBoolean(OPTION_MANUAL_CARD);
isSecureManualEnabled = optionsBundle.getBoolean(OPTION_SECURE_MANUAL);
customerId = optionsBundle.getString(OPTION_CUSTOMER_ID);
tagString = optionsBundle.getString(OPTION_TAG);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View v)
{
if (v == createInvoiceStep.getButton())
{
onCreateInvoiceClicked();
createInvoiceStep.setStepCompleted();
createTxnStep.setStepEnabled();
}
else if(v == createTxnStep.getButton())
{
onCreateTransactionClicked();
createTxnStep.setStepCompleted();
// Don't enable payment options step if offline mode is selected
if(!sharedPrefs.getBoolean(OfflinePayActivity.OFFLINE_MODE,false))
{
// enablePaymentOptionsStep();
acceptTxnStep.setStepEnabled();
} else {
acceptTxnStep.setStepEnabled();
}
}
else if(v == acceptTxnStep.getButton())
{
onAcceptTransactionClicked();
}else if(v == paymentOptionsStep){
Intent optionsActivity = new Intent(this,PaymentOptionsActivity.class);
optionsActivity.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
optionsActivity.putExtras(getOptionsBundle());
startActivityForResult(optionsActivity,REQUEST_OPTIONS_ACTIVITY);
}else if(v == offlineModeContainer){
if (currentTransaction != null) {
showTransactionAlreadyCreatedDialog();
} else {
Intent offlineActivity = new Intent(this, OfflinePayActivity.class);
offlineActivity.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(offlineActivity);
}
}
}
public List<FormFactor> getPreferredFormFactors()
{
List<FormFactor> formFactors = new ArrayList<>();
if (isMagneticSwipeEnabled)
{
formFactors.add(FormFactor.MagneticCardSwipe);
}
if (isChipEnabled)
{
formFactors.add(FormFactor.Chip);
}
if (isContactlessEnabled)
{
formFactors.add(FormFactor.EmvCertifiedContactless);
}
if (isSecureManualEnabled)
{
formFactors.add(FormFactor.SecureManualEntry);
}
if (isManualCardEnabled)
{
formFactors.add(FormFactor.ManualCardEntry);
}
if (formFactors.size() == 0)
{
formFactors.add(FormFactor.None);
}
return formFactors;
}
private Bundle getOptionsBundle()
{
Bundle bundle = new Bundle();
bundle.putBoolean(OPTION_AUTH_CAPTURE,isAuthCaptureEnabled);
bundle.putInt(OPTION_VAULT_TYPE,vaultType.getValue());
bundle.putBoolean(OPTION_CARD_READER_PROMPT,isCardReaderPromptEnabled);
bundle.putBoolean(OPTION_APP_PROMPT,isAppPromptEnabled);
bundle.putBoolean(OPTION_TIP_ON_READER,isTippingOnReaderEnabled);
bundle.putBoolean(OPTION_AMOUNT_TIP,isAmountBasedTippingEnabled);
bundle.putBoolean(OPTION_QUICK_CHIP_ENABLED, isQuickChipEnabled);
bundle.putBoolean(OPTION_MAGNETIC_SWIPE,isMagneticSwipeEnabled);
bundle.putBoolean(OPTION_CHIP,isChipEnabled);
bundle.putBoolean(OPTION_CONTACTLESS,isContactlessEnabled);
bundle.putBoolean(OPTION_MANUAL_CARD,isManualCardEnabled);
bundle.putBoolean(OPTION_SECURE_MANUAL,isSecureManualEnabled);
bundle.putString(OPTION_CUSTOMER_ID,customerId);
bundle.putString(OPTION_TAG,tagString);
return bundle;
}
}
| 648 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/AuthCaptureActivity.java | package com.paypal.heresdk.sampleapp.ui;
import java.math.BigDecimal;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
/**
* Created by muozdemir on 1/8/18.
*/
public class AuthCaptureActivity extends ToolbarActivity implements View.OnClickListener
{
private static final String LOG_TAG = AuthCaptureActivity.class.getSimpleName();
public static final String INTENT_AUTH_TOTAL_AMOUNT = "TOTAL_AMOUNT";
public static final String INTENT_AUTH_ID = "AUTH_ID";
public static final String INTENT_INVOICE_ID = "INVOICE_ID";
public static Invoice invoiceForRefund = null;
BigDecimal authAmount;
String authId;
String invoiceId;
private StepView voidAuthStep;
private StepView captureAuthStep;
@Override
public int getLayoutResId()
{
return R.layout.authorization_activity;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
voidAuthStep = (StepView)findViewById(R.id.void_auth_step);
captureAuthStep = (StepView)findViewById(R.id.capture_auth_step);
voidAuthStep.setOnButtonClickListener(this);
captureAuthStep.setOnButtonClickListener(this);
Intent intent = getIntent();
authAmount = new BigDecimal(0.0);
if (intent.hasExtra(INTENT_AUTH_TOTAL_AMOUNT))
{
authAmount = (BigDecimal) intent.getSerializableExtra(INTENT_AUTH_TOTAL_AMOUNT);
authId = (String) intent.getSerializableExtra(INTENT_AUTH_ID);
invoiceId = (String) intent.getSerializableExtra(INTENT_INVOICE_ID);
Log.d(LOG_TAG, "onCreate amount:" + authAmount);
final TextView txtAmount = (TextView) findViewById(R.id.amount);
txtAmount.setText("Your authorization of " + currencyFormat(authAmount) + " was successful");
}
}
public static String currencyFormat(BigDecimal n)
{
return NumberFormat.getCurrencyInstance().format(n);
}
public void onVoidAuthClicked()
{
voidAuthStep.showProgressBar();
RetailSDK.getTransactionManager().voidAuthorization(authId, new TransactionManager.VoidAuthorizationCallback()
{
@Override
public void voidAuthorization(final RetailSDKException error)
{
AuthCaptureActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
if (error != null)
{
if (error.getDeveloperMessage() == null || error.getDeveloperMessage().isEmpty())
{
Toast.makeText(getApplicationContext(), "void Authorization error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "void Authorization error: " + error.getDeveloperMessage(), Toast.LENGTH_SHORT).show();
}
}
else
{
captureAuthStep.setStepDisabled();
voidAuthStep.hideProgressBarShowTick();
Toast.makeText(getApplicationContext(), authId + " voided ", Toast.LENGTH_SHORT).show();
goToChargeActivity();
}
}
});
}
});
}
public void onCaptureAuthClicked()
{
Log.d(LOG_TAG, "goToCaptureActivity");
// CaptureActivity.invoiceForRefund = invoiceForRefund;
Intent intent = new Intent(AuthCaptureActivity.this, CaptureActivity.class);
intent.putExtra(INTENT_AUTH_TOTAL_AMOUNT, authAmount);
intent.putExtra(INTENT_AUTH_ID, authId);
intent.putExtra(INTENT_INVOICE_ID, invoiceId);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void goToChargeActivity()
{
Log.d(LOG_TAG, "goToChargeActivity");
Intent intent = new Intent(AuthCaptureActivity.this, ChargeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public void onClick(View v)
{
if (v == voidAuthStep.getButton()){
onVoidAuthClicked();
}else if(v == captureAuthStep.getButton()){
onCaptureAuthClicked();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==android.R.id.home){
goToChargeActivity();
}
return true;
}
}
| 649 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/OfflinePaySuccessActivity.java | package com.paypal.heresdk.sampleapp.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import com.paypal.heresdk.sampleapp.R;
public class OfflinePaySuccessActivity extends ToolbarActivity
{
@Override
public int getLayoutResId()
{
return R.layout.activity_offline_pay_success;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void onNewSaleClicked(View view){
goToChargeActivity();
}
public void goToChargeActivity(){
Intent intent = new Intent(OfflinePaySuccessActivity.this, ChargeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == android.R.id.home){
goToChargeActivity();
}
return true;
}
}
| 650 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/OfflinePayActivity.java | package com.paypal.heresdk.sampleapp.ui;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.OfflinePaymentInfo;
import com.paypal.paypalretailsdk.OfflinePaymentStatus;
import com.paypal.paypalretailsdk.OfflineTransactionState;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionManager;
public class OfflinePayActivity extends ToolbarActivity implements View.OnClickListener
{
public static final String PREF_NAME = "SampleAppPrefs";
public static final String OFFLINE_MODE ="offlineMode";
public static final String OFFLINE_INIT ="offlineInit";
private static final String REPLAY_IN_PROGRESS = "replayInProgress";
private static final String LOG_TAG = OfflinePayActivity.class.getSimpleName();
private Switch offlineModeSwitch;
private TextView statusText;
private StepView offlineStatusStep;
private StepView replayStep;
private StepView stopReplayStep;
private SharedPreferences sharedPrefs;
private boolean activityVisible = true;
@Override
public int getLayoutResId()
{
return R.layout.activity_offline_pay;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefs = getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE);
statusText = (TextView)findViewById(R.id.status_text);
offlineModeSwitch = (Switch)findViewById(R.id.offline_mode_switch);
offlineStatusStep = (StepView) findViewById(R.id.offline_status);
offlineStatusStep.setOnButtonClickListener(this);
replayStep = (StepView) findViewById(R.id.replay_offline);
replayStep.setOnButtonClickListener(this);
stopReplayStep = (StepView) findViewById(R.id.stop_replay);
stopReplayStep.setOnButtonClickListener(this);
getOfflineStatus();
replayStep.setStepEnabled();
offlineModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
sharedPrefs.edit().putBoolean(OFFLINE_MODE,isChecked).apply();
if (isChecked){
// Before we start offline Payment, we want to check if the merchant is eligible
// to take offline Payments. Then we call the startOfflinePayment() API.
// This API will have a callback which will return an error if there was one and a list
// of offline transactions.
if (RetailSDK.getTransactionManager().getOfflinePaymentEligibility()){
RetailSDK.getTransactionManager().startOfflinePayment(new TransactionManager.OfflinePaymentStatusCallback() {
@Override
public void offlinePaymentStatus(RetailSDKException error, OfflinePaymentInfo offlinePaymentInfo) {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getDeveloperMessage(), Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Merchant not whitelisted for offline payments", Toast.LENGTH_LONG).show();
}
}else{
RetailSDK.getTransactionManager().stopOfflinePayment(new TransactionManager.OfflinePaymentStatusCallback()
{
@Override
public void offlinePaymentStatus(RetailSDKException error, OfflinePaymentInfo offlinePaymentInfo)
{
if (error != null) {
Toast.makeText(getApplicationContext(), error.getDeveloperMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
}
});
intiViewState();
}
private void intiViewState()
{
if (sharedPrefs.getBoolean(OFFLINE_MODE,false)){
offlineModeSwitch.setChecked(true);
replayStep.setStepEnabled();
stopReplayStep.setStepDisabled();
}else{
offlineModeSwitch.setChecked(false);
if (sharedPrefs.getBoolean(REPLAY_IN_PROGRESS,false)){
replayStep.showProgressBar();
stopReplayStep.setStepEnabled();
offlineModeSwitch.setEnabled(false);
}else{
replayStep.setStepEnabled();
stopReplayStep.setStepDisabled();
}
}
}
private void showSwitchingToOnlineDialog(String title, String message, final Boolean setChecked){
Log.d(LOG_TAG, "showSwitchingToOnlineDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(OfflinePayActivity.this);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(LOG_TAG, "replaying while in offline mode alert dialog onClick");
offlineModeSwitch.setChecked(setChecked);
dialog.dismiss();
}
});
builder.create().show();
}
private void showReplayCompleteDialog(String title, String message){
Log.d(LOG_TAG, "showReplayCompleteDialog");
AlertDialog.Builder builder = new AlertDialog.Builder(OfflinePayActivity.this);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(LOG_TAG, "show replay completed onClick");
dialog.dismiss();
}
});
builder.create().show();
}
private void replayOfflineTxns(){
if (sharedPrefs.getBoolean(OFFLINE_INIT, false))
{
showSwitchingToOnlineDialog(getString(R.string.replay_dialog_offline_init_title), getString(R.string.replay_dialog_offline_init_message), true);
return;
} else if (sharedPrefs.getBoolean(OFFLINE_MODE, false)) {
showSwitchingToOnlineDialog(getString(R.string.replay_dialog_offline_mode_title), getString(R.string.replay_dialog_offline_mode_message), false);
}
replayStep.showProgressBar();
stopReplayStep.setStepEnabled();
offlineModeSwitch.setEnabled(false);
sharedPrefs.edit().putBoolean(REPLAY_IN_PROGRESS,true).apply();
RetailSDK.getTransactionManager().startReplayOfflineTxns(new TransactionManager.OfflinePaymentStatusCallback()
{
@Override
public void offlinePaymentStatus(RetailSDKException e, OfflinePaymentInfo offlinePaymentInfo)
{
sharedPrefs.edit().putBoolean(REPLAY_IN_PROGRESS,false).apply();
if(activityVisible){
final String toPrint = getStringToPrint(offlinePaymentInfo.getStatusList());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
showReplayCompleteDialog("Offline Replay Completed", toPrint);
statusText.setText(toPrint);
stopReplayStep.setStepDisabled();
offlineModeSwitch.setEnabled(true);
replayStep.hideProgressBarShowButton();
}
});
}
}
});
}
private void stopReplay()
{
sharedPrefs.edit().putBoolean(REPLAY_IN_PROGRESS,false).apply();
RetailSDK.getTransactionManager().stopReplayOfflineTxns(new TransactionManager.OfflinePaymentStatusCallback() {
@Override
public void offlinePaymentStatus(RetailSDKException error, OfflinePaymentInfo offlinePaymentInfo) {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getDeveloperMessage(), Toast.LENGTH_LONG).show();
}
}
});
stopReplayStep.setStepDisabled();
offlineModeSwitch.setEnabled(true);
replayStep.hideProgressBarShowButton();
}
private void getOfflineStatus()
{
RetailSDK.getTransactionManager().getOfflinePaymentStatus(new TransactionManager.OfflinePaymentStatusCallback()
{
@Override
public void offlinePaymentStatus(RetailSDKException e, OfflinePaymentInfo offlinePaymentInfo)
{
final String toPrint = getStringToPrint(offlinePaymentInfo.getStatusList());
runOnUiThread(new Runnable()
{
@Override
public void run()
{
statusText.setText(toPrint);
}
});
}
});
}
private String getStringToPrint(List<OfflinePaymentStatus> list)
{
String toPrint = "No pending offline transactions";
int activeTransactionsCount = 0;
int completedTransactionsCount = 0;
int declinedTransactionsCount = 0;
int deletedTransactionsCount = 0;
int failedTransactionsCount = 0;
if(list!=null && list.size()>0){
toPrint = "";
for (OfflinePaymentStatus status:list){
OfflineTransactionState state = status.getState();
switch (state){
case Active:
activeTransactionsCount += 1;
break;
case Completed:
completedTransactionsCount += 1;
break;
case Declined:
declinedTransactionsCount += 1;
break;
case Deleted:
deletedTransactionsCount += 1;
break;
case Failed:
failedTransactionsCount += 1;
break;
}
}
toPrint += "Active : " + activeTransactionsCount + "\n"
+ "Completed : " + completedTransactionsCount + "\n"
+ "Declined : " + declinedTransactionsCount + "\n"
+ "Deleted : " + deletedTransactionsCount + "\n"
+ "Failed : " + failedTransactionsCount;
}
return toPrint;
}
@Override
protected void onPause()
{
super.onPause();
activityVisible = false;
}
@Override
public void onClick(View v)
{
if (v == offlineStatusStep.getButton()){
getOfflineStatus();
}else if(v == replayStep.getButton()){
replayOfflineTxns();
}else if(v == stopReplayStep.getButton()){
stopReplay();
}
}
}
| 651 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/PaymentOptionsFragment.java | package com.paypal.heresdk.sampleapp.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;
import android.util.Log;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.RetailSDK;
public class PaymentOptionsFragment extends PreferenceFragmentCompat
{
final String logComponent = "PaymentOptionsFragment";
SwitchPreferenceCompat authCapturePreference;
SwitchPreferenceCompat vaultPreference;
SwitchPreferenceCompat promptAppPreference;
SwitchPreferenceCompat promptReaderPreference;
SwitchPreferenceCompat amountTippingPreference;
SwitchPreferenceCompat enableQuickChipPreference;
SwitchPreferenceCompat readerTipPreference;
SwitchPreferenceCompat chipPreference;
SwitchPreferenceCompat contactlessPreference;
SwitchPreferenceCompat magneticSwipePreference;
SwitchPreferenceCompat manualCardPreference;
SwitchPreferenceCompat secureManualPreference;
EditTextPreference tag;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
{
setPreferencesFromResource(R.xml.preferences,rootKey);
authCapturePreference = (SwitchPreferenceCompat) findPreference(getString(R.string.auth_capture));
vaultPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.vault_only));
promptAppPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.show_prompt_in_app));
promptReaderPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.show_prompt_in_card_reader));
amountTippingPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.amount_based_tipping));
enableQuickChipPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.enable_quick_chip));
readerTipPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.tipping_on_reader));
chipPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.chip));
contactlessPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.contactless));
magneticSwipePreference = (SwitchPreferenceCompat) findPreference(getString(R.string.magnetic_swipe));
manualCardPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.manual_card));
secureManualPreference = (SwitchPreferenceCompat) findPreference(getString(R.string.secure_manual));
tag = (EditTextPreference)findPreference(getString(R.string.edit_text_pref));
}
// getters
public boolean getAuthCapturePreference()
{
return authCapturePreference.isChecked();
}
public boolean getVaultPreference()
{
return vaultPreference.isChecked();
}
public boolean getPromptAppPreference()
{
return promptAppPreference.isChecked();
}
public boolean getPromptReaderPreference()
{
return promptReaderPreference.isChecked();
}
public boolean getAmountTippingPreference()
{
return amountTippingPreference.isChecked();
}
public boolean getQuickChipEnabledPreference()
{
return enableQuickChipPreference.isChecked();
}
public boolean getTipOnReaderPreference()
{
return readerTipPreference.isChecked();
}
public boolean getChipPreference()
{
return chipPreference.isChecked();
}
public boolean getContactlessPreference()
{
return contactlessPreference.isChecked();
}
public boolean getMagneticSwipePreference()
{
return magneticSwipePreference.isChecked();
}
public boolean getManualCardPreference()
{
return manualCardPreference.isChecked();
}
public boolean getSecureManualPreference()
{
return secureManualPreference.isChecked();
}
public String getTagString()
{
return tag.getText();
}
// setters
public void setAuthCapturePreference(boolean isChecked)
{
authCapturePreference.setChecked(isChecked);
}
public void setVaultPreference(boolean isChecked)
{
vaultPreference.setChecked(isChecked);
}
public void setPromptAppPreference(boolean isChecked)
{
promptAppPreference.setChecked(isChecked);
}
public void setPromptReaderPreference(boolean isChecked)
{
promptReaderPreference.setChecked(isChecked);
}
public void setAmountTippingPreference(boolean isChecked)
{
amountTippingPreference.setChecked(isChecked);
}
public void setQuickChipEnabledPreference(boolean isChecked){
enableQuickChipPreference.setChecked(isChecked);
}
public void setReaderTipPreference(boolean isChecked)
{
readerTipPreference.setChecked(isChecked);
}
public void setChipPreference(boolean isChecked)
{
chipPreference.setChecked(isChecked);
}
public void setContactlessPreference(boolean isChecked)
{
contactlessPreference.setChecked(isChecked);
}
public void setMagneticSwipePreference(boolean isChecked)
{
magneticSwipePreference.setChecked(isChecked);
}
public void setManualCardPreference(boolean isChecked)
{
manualCardPreference.setChecked(isChecked);
}
public void setSecureManualPreference(boolean isChecked)
{
secureManualPreference.setChecked(isChecked);
}
public void setTag(String tagText)
{
if(tag!=null)
{
tag.setText(tagText);
}
}
}
| 652 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/RefundActivity.java | package com.paypal.heresdk.sampleapp.ui;
import java.math.BigDecimal;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
/**
* Created by muozdemir on 12/19/17.
*/
public class RefundActivity extends ToolbarActivity
{
private static final String LOG_TAG = RefundActivity.class.getSimpleName();
public static final String INTENT_TRANX_TOTAL_AMOUNT = "TOTAL_AMOUNT";
public static final String INTENT_CAPTURE_TOTAL_AMOUNT = "CAPTURE_AMOUNT";
public static final String INTENT_VAULT_ID = "VAULT_ID";
public static Invoice invoiceForRefund = null;
public static RetailInvoice invoiceForRefundCaptured = null;
TransactionContext currentTransaction;
BigDecimal currentAmount;
boolean isCaptured = false;
private StepView issueRefundStep;
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId()==android.R.id.home){
goBackToChargeActivity();
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
setContentView(R.layout.refund_activity);
Intent intent = getIntent();
currentAmount = new BigDecimal(0.0);
if (intent.hasExtra(INTENT_TRANX_TOTAL_AMOUNT))
{
isCaptured = false;
currentAmount = (BigDecimal) intent.getSerializableExtra(INTENT_TRANX_TOTAL_AMOUNT);
Log.d(LOG_TAG, "onCreate amount:" + currentAmount);
final TextView txtAmount = (TextView) findViewById(R.id.amount);
if (intent.hasExtra(INTENT_VAULT_ID)) {
String vaultId = (String) intent.getSerializableExtra(INTENT_VAULT_ID);
txtAmount.setText("Your payment of " + currencyFormat(currentAmount) +" was successful with Vault " + vaultId);
} else {
txtAmount.setText("Your payment of " + currencyFormat(currentAmount) +" was successful");
}
}
else if (intent.hasExtra(INTENT_CAPTURE_TOTAL_AMOUNT))
{
isCaptured = true;
currentAmount = (BigDecimal) intent.getSerializableExtra(INTENT_CAPTURE_TOTAL_AMOUNT);
Log.d(LOG_TAG, "onCreate captur amount:" + currentAmount);
final TextView txtAmount = (TextView) findViewById(R.id.amount);
txtAmount.setText("Your payment of " + currencyFormat(currentAmount) +" was successfully captured.");
}
issueRefundStep = (StepView) findViewById(R.id.refund_step);
issueRefundStep.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onProvideRefundClicked();
}
});
}
@Override
public int getLayoutResId()
{
return R.layout.refund_activity;
}
public static String currencyFormat(BigDecimal n)
{
return NumberFormat.getCurrencyInstance().format(n);
}
public void onSkipRefundClicked(View view)
{
goBackToChargeActivity();
}
public void onProvideRefundClicked()
{
RetailSDK.setCurrentApplicationActivity(this);
if (isCaptured)
{
RetailSDK.getTransactionManager().createTransaction(invoiceForRefundCaptured, new TransactionManager.TransactionCallback()
{
@Override
public void transaction(RetailSDKException error, TransactionContext transactionContext)
{
transactionContext.setCompletedHandler(new TransactionContext.TransactionCompletedCallback()
{
@Override
public void transactionCompleted(RetailSDKException error, TransactionRecord record)
{
Log.d(LOG_TAG, "createTx for captured -> transactionCompleted");
RefundActivity.this.refundCompleted(error, record);
}
});
transactionContext.beginRefund(true, currentAmount);
}
});
return;
}
currentTransaction = RetailSDK.createTransaction(invoiceForRefund);
currentTransaction.setCompletedHandler(new TransactionContext.TransactionCompletedCallback()
{
@Override
public void transactionCompleted(RetailSDKException error, TransactionRecord record)
{
RefundActivity.this.refundCompleted(error, record);
}
});
currentTransaction.beginRefund(true, currentAmount);
}
private void refundCompleted(RetailSDKException error, TransactionRecord record)
{
if (error != null)
{
final String errorTxt = error.toString();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "refund error: " + errorTxt, Toast.LENGTH_SHORT).show();
}
});
}
else
{
final String txnNumber = record.getTransactionNumber();
this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), String.format("Completed refund for Transaction %s", txnNumber), Toast.LENGTH_SHORT).show();
RefundActivity.this.goBackToChargeActivity();
}
});
}
}
public void goBackToChargeActivity()
{
Log.d(LOG_TAG, "goToChargeActivity");
Intent intent = new Intent(RefundActivity.this, ChargeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
| 653 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/ui/StepView.java | package com.paypal.heresdk.sampleapp.ui;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.paypal.heresdk.sampleapp.R;
public class StepView extends LinearLayout
{
private ImageView tick;
private ImageView cross;
private Button button;
private TextView titleTextView;
private TextView codeTextView;
private Context context;
private LinearLayout container;
private ProgressBar progress;
public StepView(Context context)
{
super(context);
this.context = context;
}
public StepView(Context context, AttributeSet attrs){
super(context,attrs);
this.context = context;
TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.step_view_styleable);
String title = attrArray.getString(R.styleable.step_view_styleable_title_text);
String code = attrArray.getString(R.styleable.step_view_styleable_code_text);
String buttonText = attrArray.getString(R.styleable.step_view_styleable_button_text);
boolean enabled = attrArray.getBoolean(R.styleable.step_view_styleable_enabled,true);
title = title == null ? "" : title;
code = code == null ? "" : code;
buttonText = buttonText == null ? "" : buttonText;
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container = (LinearLayout) layoutInflater.inflate(R.layout.step_view_layout,this,true);
titleTextView = (TextView)container.findViewById(R.id.title);
codeTextView = (TextView)container.findViewById(R.id.code_text);
button = (Button)container.findViewById(R.id.button);
tick = (ImageView)container.findViewById(R.id.done_tick);
cross = (ImageView) container.findViewById(R.id.done_cross);
progress = (ProgressBar)container.findViewById(R.id.progress);
titleTextView.setText(title);
codeTextView.setText(code);
button.setText(buttonText);
if (enabled){
setStepEnabled();
}else{
setStepDisabled();
}
attrArray.recycle();
}
public void setStepDisabled(){
button.setVisibility(GONE);
tick.setVisibility(GONE);
titleTextView.setTextColor(getResources().getColor(R.color.sdk_gray));
codeTextView.setTextColor(getResources().getColor(R.color.sdk_gray));
}
public void setStepEnabled(){
button.setVisibility(VISIBLE);
tick.setVisibility(GONE);
titleTextView.setTextColor(getResources().getColor(R.color.sdk_black));
codeTextView.setTextColor(getResources().getColor(R.color.sdk_black));
}
public void setStepCompleted(){
button.setVisibility(GONE);
tick.setVisibility(VISIBLE);
tick.setImageResource(R.drawable.small_blue_tick);
titleTextView.setTextColor(getResources().getColor(R.color.sdk_black));
codeTextView.setTextColor(getResources().getColor(R.color.sdk_black));
}
public void setStepCrossed()
{
button.setVisibility(GONE);
tick.setVisibility(GONE);
cross.setVisibility(VISIBLE);
cross.setImageResource(R.drawable.cancel_x);
titleTextView.setTextColor(getResources().getColor(R.color.sdk_black));
codeTextView.setTextColor(getResources().getColor(R.color.sdk_black));
}
public Button getButton(){
return button;
}
public void setOnButtonClickListener(OnClickListener clickListener){
button.setOnClickListener(clickListener);
}
public void setOnStepClickListener(OnClickListener clickListener){
container.setOnClickListener(clickListener);
}
public void showProgressBar()
{
button.setVisibility(GONE);
tick.setVisibility(GONE);
progress.setVisibility(VISIBLE);
}
public void hideProgressBarShowButton(){
progress.setVisibility(GONE);
tick.setVisibility(GONE);
button.setVisibility(VISIBLE);
}
public void hideProgressBarShowTick(){
progress.setVisibility(GONE);
button.setVisibility(GONE);
tick.setVisibility(VISIBLE);
}
}
| 654 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/transactionSelection/TransactionSelection.java | package com.paypal.heresdk.sampleapp.activities.transactionSelection;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.heresdk.sampleapp.activities.vaultAndPayTransaction.VaultAndPayTransaction;
import com.paypal.heresdk.sampleapp.activities.vaultTransaction.VaultTransaction;
import com.paypal.heresdk.sampleapp.ui.ChargeActivity;
public class TransactionSelection extends AppCompatActivity
{
private RecyclerView _transactionSelectionRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction_selection);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
_transactionSelectionRecyclerView = findViewById(R.id.transaction_selection_recycler_view);
_transactionSelectionRecyclerView.setHasFixedSize(true);
_transactionSelectionRecyclerView.setLayoutManager(new LinearLayoutManager(this));
_transactionSelectionRecyclerView.setAdapter(
new TransactionSelectionAdapter(
new String[]{
this.getString(R.string.transaction_selection_vault_and_pay),
this.getString(R.string.transaction_selection_vault),
this.getString(R.string.transaction_selection_pay),
this.getString(R.string.transaction_selection_offline),
this.getString(R.string.transaction_selection_auth),
this.getString(R.string.transaction_selection_auth_capture),
}
)
);
}
static class TransactionSelectionAdapter extends RecyclerView.Adapter<TransactionSelectionAdapter.TransactionSelectionViewHolder>
{
private String[] _transactionTypes;
static class TransactionSelectionViewHolder extends RecyclerView.ViewHolder
{
LinearLayout _linearLayout;
TransactionSelectionViewHolder(LinearLayout linearLayout)
{
super(linearLayout);
_linearLayout = linearLayout;
}
}
TransactionSelectionAdapter(String[] transactionTypes)
{
_transactionTypes = transactionTypes;
}
@NonNull
@Override
public TransactionSelectionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
// TextView textView = parent.findViewById(R.id.transaction_selection_text_view);
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.content_transaction_selection, parent, false);
return new TransactionSelectionViewHolder(linearLayout);
}
@Override
public void onBindViewHolder(@NonNull TransactionSelectionViewHolder holder, int position)
{
TextView textView = holder._linearLayout.findViewById(R.id.transaction_selection_text_view);
textView.setText(_transactionTypes[position]);
holder._linearLayout.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
transitionToActivity(view);
}
void transitionToActivity(@NonNull View _view)
{
String transactionType = ((TextView) _view.findViewById(R.id.transaction_selection_text_view)).getText().toString();
_view.getContext().startActivity(getIntent(transactionType, _view.getContext()));
}
@NonNull
Intent getIntent(@NonNull String transactionType, @NonNull Context context)
{
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_auth_capture)))
{
return new Intent(context, ChargeActivity.class);
}
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_auth)))
{
return new Intent(context, ChargeActivity.class);
}
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_offline)))
{
return new Intent(context, ChargeActivity.class);
}
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_pay)))
{
return new Intent(context, ChargeActivity.class);
}
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_vault)))
{
return new Intent(context, VaultTransaction.class);
}
if (transactionType.equalsIgnoreCase(context.getString(R.string.transaction_selection_vault_and_pay)))
{
return new Intent(context, VaultAndPayTransaction.class);
}
return new Intent(context, ChargeActivity.class);
}
});
}
@Override
public int getItemCount()
{
return _transactionTypes.length;
}
}
}
| 655 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultTransaction/VaultTransactionViewModel.java | package com.paypal.heresdk.sampleapp.activities.vaultTransaction;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.MutableLiveData;
import android.os.Handler;
import android.os.Looper;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionBeginOptions;
import com.paypal.paypalretailsdk.TransactionBeginOptionsPaymentTypes;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultProvider;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultType;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.VaultRecord;
public class VaultTransactionViewModel extends ViewModel
{
private VaultTransactionModel _vaultTransactionModel;
private final String LOG_TAG = "VaultTransactionVM";
private final String BRAINTREE_CUSTOMER_ID = "4085815786";
private MutableLiveData<VaultRecord> _vaultRecordLiveData;
private MutableLiveData<RetailSDKException> _retailSDKExceptionMutableLiveData;
public MutableLiveData<RetailSDKException> getRetailSDKExceptionMutableLiveData()
{
if (_retailSDKExceptionMutableLiveData == null)
{
_retailSDKExceptionMutableLiveData = new MutableLiveData<>();
}
return _retailSDKExceptionMutableLiveData;
}
public MutableLiveData<VaultRecord> getVaultRecordLiveData()
{
if (_vaultRecordLiveData == null)
{
_vaultRecordLiveData = new MutableLiveData<>();
}
return _vaultRecordLiveData;
}
public VaultTransactionViewModel()
{
_vaultTransactionModel = new VaultTransactionModel();
}
String getBraintreeLoginUrl()
{
return _vaultTransactionModel.getBraintreeLoginURL();
}
boolean isBraintreeReturnUrlValid(String returnUrl)
{
return _vaultTransactionModel.isBraintreeReturnUrlValid(returnUrl);
}
void beginPayment()
{
_vaultTransactionModel.createTransaction(
new TransactionManager.TransactionCallback()
{
@Override
public void transaction(RetailSDKException error, TransactionContext transactionContext)
{
if (error != null)
{
_retailSDKExceptionMutableLiveData.setValue(error);
}
else
{
transactionContext.setVaultCompletedHandler(new TransactionContext.VaultCompletedCallback()
{
@Override
public void vaultCompleted(final RetailSDKException error, final VaultRecord vaultRecord)
{
if (error != null)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_retailSDKExceptionMutableLiveData.setValue(error);
}
});
}
else
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_vaultRecordLiveData.setValue(vaultRecord);
}
});
}
}
});
TransactionBeginOptions transactionBeginOptions = new TransactionBeginOptions();
transactionBeginOptions.setPaymentType(TransactionBeginOptionsPaymentTypes.card);
transactionBeginOptions.setVaultProvider(TransactionBeginOptionsVaultProvider.Braintree);
transactionBeginOptions.setVaultType(TransactionBeginOptionsVaultType.VaultOnly);
transactionBeginOptions.setVaultCustomerId(BRAINTREE_CUSTOMER_ID);
transactionContext.beginPayment(transactionBeginOptions);
}
}
}
);
}
@Override
protected void onCleared()
{
super.onCleared();
}
}
| 656 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultTransaction/VaultTransaction.java | package com.paypal.heresdk.sampleapp.activities.vaultTransaction;
import java.util.Objects;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.annotation.Nullable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.heresdk.sampleapp.ui.StepView;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.VaultRecord;
public class VaultTransaction extends AppCompatActivity
{
private String LOG_TAG = VaultTransaction.class.getSimpleName();
private VaultTransactionViewModel _vaultTransactionViewModel;
StepView _vaultStep;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vault_transaction);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
_vaultTransactionViewModel = ViewModelProviders.of(VaultTransaction.this).get(VaultTransactionViewModel.class);
_vaultStep = findViewById(R.id.begin_vault_step);
_vaultStep.setStepEnabled();
}
@Override
protected void onStart()
{
super.onStart();
_vaultStep.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
_vaultTransactionViewModel.getVaultRecordLiveData().observe(VaultTransaction.this, new Observer<VaultRecord>()
{
@Override
public void onChanged(@Nullable VaultRecord vaultRecord)
{
if (vaultRecord != null)
{
_vaultStep.setStepCompleted();
}
}
});
_vaultTransactionViewModel.getRetailSDKExceptionMutableLiveData().observe(VaultTransaction.this, new Observer<RetailSDKException>()
{
@Override
public void onChanged(@Nullable RetailSDKException error)
{
if (error != null)
{
_vaultStep.setStepCrossed();
}
}
});
_vaultTransactionViewModel.beginPayment();
}
});
}
}
| 657 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultTransaction/VaultTransactionModel.java | package com.paypal.heresdk.sampleapp.activities.vaultTransaction;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.TransactionManager;
class VaultTransactionModel
{
String getBraintreeLoginURL()
{
return RetailSDK.getBraintreeManager().getBtLoginUrl();
}
boolean isBraintreeReturnUrlValid(String returnUrl)
{
return RetailSDK.getBraintreeManager().isBtReturnUrlValid(returnUrl);
}
void createTransaction(TransactionManager.TransactionCallback transactionCallback)
{
RetailSDK.getTransactionManager().createVaultTransaction(transactionCallback);
}
}
| 658 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultAndPayTransaction/VaultAndPayTransactionModel.java | package com.paypal.heresdk.sampleapp.activities.vaultAndPayTransaction;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.TransactionManager;
class VaultAndPayTransactionModel
{
String getBraintreeLoginURL()
{
return RetailSDK.getBraintreeManager().getBtLoginUrl();
}
boolean isBraintreeReturnUrlValid(String redirectUrl)
{
return RetailSDK.getBraintreeManager().isBtReturnUrlValid(redirectUrl);
}
RetailInvoice createInvoice()
{
return new RetailInvoice(RetailSDK.getMerchant().getCurrency());
}
void createTransaction(RetailInvoice invoice, TransactionManager.TransactionCallback transactionCallback)
{
RetailSDK.getTransactionManager().createTransaction(invoice, transactionCallback);
}
}
| 659 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultAndPayTransaction/VaultAndPayTransactionViewModel.java | package com.paypal.heresdk.sampleapp.activities.vaultAndPayTransaction;
import java.math.BigDecimal;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.MutableLiveData;
import android.os.Handler;
import android.os.Looper;
import com.paypal.paypalretailsdk.Invoice;
import com.paypal.paypalretailsdk.InvoiceItem;
import com.paypal.paypalretailsdk.RetailInvoice;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionBeginOptions;
import com.paypal.paypalretailsdk.TransactionBeginOptionsPaymentTypes;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultProvider;
import com.paypal.paypalretailsdk.TransactionBeginOptionsVaultType;
import com.paypal.paypalretailsdk.TransactionContext;
import com.paypal.paypalretailsdk.TransactionManager;
import com.paypal.paypalretailsdk.TransactionRecord;
import com.paypal.paypalretailsdk.VaultRecord;
public class VaultAndPayTransactionViewModel extends ViewModel
{
private VaultAndPayTransactionModel _vaultAndPayTransactionModel;
private RetailInvoice _invoice;
private final String LOG_TAG = "VaultNPayTransactionVM";
private final String BRAINTREE_CUSTOMER_ID = "4085815786";
private MutableLiveData<TransactionRecord> _transactionRecordLiveData;
private MutableLiveData<VaultRecord> _vaultRecordLiveData;
private MutableLiveData<RetailSDKException> _retailSDKExceptionMutableLiveData;
public MutableLiveData<RetailSDKException> getRetailSDKExceptionMutableLiveData()
{
if (_retailSDKExceptionMutableLiveData == null)
{
_retailSDKExceptionMutableLiveData = new MutableLiveData<>();
}
return _retailSDKExceptionMutableLiveData;
}
public MutableLiveData<TransactionRecord> getTransactionRecordLiveData()
{
if (_transactionRecordLiveData == null)
{
_transactionRecordLiveData = new MutableLiveData<>();
}
return _transactionRecordLiveData;
}
public MutableLiveData<VaultRecord> getVaultRecordLiveData()
{
if (_vaultRecordLiveData == null)
{
_vaultRecordLiveData = new MutableLiveData<>();
}
return _vaultRecordLiveData;
}
public VaultAndPayTransactionViewModel()
{
_vaultAndPayTransactionModel = new VaultAndPayTransactionModel();
}
String getBraintreeLoginUrl()
{
return _vaultAndPayTransactionModel.getBraintreeLoginURL();
}
boolean isBraintreeReturnUrlValid(String returnUrl)
{
return _vaultAndPayTransactionModel.isBraintreeReturnUrlValid(returnUrl);
}
boolean createInvoice()
{
this._invoice = _vaultAndPayTransactionModel.createInvoice();
return this._invoice != null;
}
boolean addInvoiceItem(String itemName, String quantity, String unitPrice, String itemId, String detailId)
{
if (this._invoice != null)
{
InvoiceItem _invoiceItem = this._invoice.addItem(
itemName,
new BigDecimal(quantity),
new BigDecimal(unitPrice),
Integer.valueOf(itemId),
detailId
);
return _invoiceItem != null;
}
return false;
}
void beginPayment()
{
_vaultAndPayTransactionModel.createTransaction(
VaultAndPayTransactionViewModel.this._invoice,
new TransactionManager.TransactionCallback()
{
@Override
public void transaction(RetailSDKException error, TransactionContext transactionContext)
{
if (error != null)
{
_retailSDKExceptionMutableLiveData.setValue(error);
}
else
{
transactionContext.setVaultCompletedHandler(new TransactionContext.VaultCompletedCallback()
{
@Override
public void vaultCompleted(final RetailSDKException error, final VaultRecord vaultRecord)
{
if (error != null)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_retailSDKExceptionMutableLiveData.setValue(error);
}
});
}
else
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_vaultRecordLiveData.setValue(vaultRecord);
}
});
}
}
});
transactionContext.setCompletedHandler(new TransactionContext.TransactionCompletedCallback()
{
@Override
public void transactionCompleted(final RetailSDKException error, final TransactionRecord transactionRecord)
{
if (error != null)
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_retailSDKExceptionMutableLiveData.setValue(error);
}
});
}
else
{
new Handler(Looper.getMainLooper()).post(new Runnable()
{
@Override
public void run()
{
_transactionRecordLiveData.setValue(transactionRecord);
}
});
}
}
});
TransactionBeginOptions transactionBeginOptions = new TransactionBeginOptions();
transactionBeginOptions.setPaymentType(TransactionBeginOptionsPaymentTypes.card);
transactionBeginOptions.setVaultProvider(TransactionBeginOptionsVaultProvider.Braintree);
transactionBeginOptions.setVaultType(TransactionBeginOptionsVaultType.PayAndVault);
transactionBeginOptions.setVaultCustomerId(BRAINTREE_CUSTOMER_ID);
transactionContext.beginPayment(transactionBeginOptions);
}
}
}
);
}
@Override
protected void onCleared()
{
super.onCleared();
}
}
| 660 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/activities/vaultAndPayTransaction/VaultAndPayTransaction.java | package com.paypal.heresdk.sampleapp.activities.vaultAndPayTransaction;
import java.util.Objects;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.annotation.Nullable;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.heresdk.sampleapp.ui.StepView;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.TransactionRecord;
import com.paypal.paypalretailsdk.VaultRecord;
public class VaultAndPayTransaction extends AppCompatActivity
{
private String LOG_TAG = VaultAndPayTransaction.class.getSimpleName();
private VaultAndPayTransactionViewModel _vaultAndPayTransactionViewModel;
StepView _createInvoiceStep, _addInvoiceItemStep, _vaultAndPayStep;
EditText _amount;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vault_and_pay_transaction);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
_vaultAndPayTransactionViewModel = ViewModelProviders.of(VaultAndPayTransaction.this).get(VaultAndPayTransactionViewModel.class);
_createInvoiceStep = findViewById(R.id.create_invoice_step);
_addInvoiceItemStep = findViewById(R.id.add_invoice_item_step);
_vaultAndPayStep = findViewById(R.id.begin_vault_and_pay_step);
_amount = findViewById(R.id.amount);
_amount.setFocusable(false);
_createInvoiceStep.setStepEnabled();
}
@Override
protected void onStart()
{
super.onStart();
_createInvoiceStep.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if (_vaultAndPayTransactionViewModel.createInvoice())
{
_addInvoiceItemStep.setStepEnabled();
_createInvoiceStep.setStepCompleted();
_amount.setFocusableInTouchMode(true);
}
}
});
_addInvoiceItemStep.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
if (_vaultAndPayTransactionViewModel.addInvoiceItem("Item", "1", _amount.getText().toString(), "101", ""))
{
_vaultAndPayStep.setStepEnabled();
}
}
});
_vaultAndPayStep.setOnButtonClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
_vaultAndPayTransactionViewModel.getTransactionRecordLiveData().observe(VaultAndPayTransaction.this, new Observer<TransactionRecord>()
{
@Override
public void onChanged(@Nullable TransactionRecord transactionRecord)
{
if (transactionRecord != null)
{
_vaultAndPayStep.setStepCompleted();
}
}
});
_vaultAndPayTransactionViewModel.getVaultRecordLiveData().observe(VaultAndPayTransaction.this, new Observer<VaultRecord>()
{
@Override
public void onChanged(@Nullable VaultRecord vaultRecord)
{
if (vaultRecord != null)
{
_vaultAndPayStep.setStepCompleted();
}
}
});
_vaultAndPayTransactionViewModel.getRetailSDKExceptionMutableLiveData().observe(VaultAndPayTransaction.this, new Observer<RetailSDKException>()
{
@Override
public void onChanged(@Nullable RetailSDKException error)
{
if (error != null)
{
_vaultAndPayStep.setStepCrossed();
}
}
});
_vaultAndPayTransactionViewModel.beginPayment();
}
});
}
}
| 661 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/login/LocalPreferences.java | package com.paypal.heresdk.sampleapp.login;
import android.content.Context;
import android.content.SharedPreferences;
public class LocalPreferences {
private static final String LOG_TAG = LocalPreferences.class.getSimpleName();
private static String SHARED_PREFS_SANDBOX_MID_TIER_TOKEN = "SHARED_PREFS_SANDBOX_MID_TIER_TOKEN";
private static String SHARED_PREFS_LIVE_MID_TIER_TOKEN = "SHARED_PREFS_LIVE_MID_TIER_TOKEN";
private static String SHARED_PREFS_LIVE_MID_TIER_ACCESS_TOKEN = "SHARED_PREFS_LIVE_MID_TIER_ACCESS_TOKEN";
private static String SHARED_PREFS_LIVE_MID_TIER_REFRESH_URL = "SHARED_PREFS_LIVE_MID_TIER_REFRESH_URL";
private static String SHARED_PREFS_LIVE_MID_TIER_ENV = "SHARED_PREFS_LIVE_MID_TIER_ENV";
private static String SHARED_PREFS_SANDBOX_MID_TIER_ACCESS_TOKEN = "SHARED_PREFS_SANDBOX_MID_TIER_ACCESS_TOKEN";
private static String SHARED_PREFS_SANDBOX_MID_TIER_REFRESH_URL = "SHARED_PREFS_SANDBOX_MID_TIER_REFRESH_URL";
private static String SHARED_PREFS_SANDBOX_MID_TIER_ENV = "SHARED_PREFS_SANDBOX_MID_TIER_ENV";
private static String SHARED_PREFS_NAME = "MyTokens";
public static void storeSandboxMidTierToken(Context context, String token){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREFS_SANDBOX_MID_TIER_TOKEN,token);
editor.commit();
}
public static void storeSandboxMidTierCredentials(Context context, String access_token, String refresh_url, String env){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREFS_SANDBOX_MID_TIER_ACCESS_TOKEN,access_token);
editor.putString(SHARED_PREFS_SANDBOX_MID_TIER_REFRESH_URL,refresh_url);
editor.putString(SHARED_PREFS_SANDBOX_MID_TIER_ENV,env);
editor.commit();
}
public static void storeLiveMidTierToken(Context context, String token){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREFS_LIVE_MID_TIER_TOKEN,token);
editor.commit();
}
public static void storeLiveMidTierCredentials(Context context, String access_token, String refresh_url, String env){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SHARED_PREFS_LIVE_MID_TIER_ACCESS_TOKEN,access_token);
editor.putString(SHARED_PREFS_LIVE_MID_TIER_REFRESH_URL,refresh_url);
editor.putString(SHARED_PREFS_LIVE_MID_TIER_ENV,env);
editor.commit();
}
public static String getSandboxMidtierToken(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
String token = preferences.getString(SHARED_PREFS_SANDBOX_MID_TIER_TOKEN, null);
return token;
}
public static String getLiveMidtierToken(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
String token = preferences.getString(SHARED_PREFS_LIVE_MID_TIER_TOKEN, null);
return token;
}
public static String getLiveMidtierAccessToken(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_LIVE_MID_TIER_ACCESS_TOKEN, null);
}
public static String getLiveMidtierRefreshUrl(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_LIVE_MID_TIER_REFRESH_URL, null);
}
public static String getLiveMidtierEnv(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_LIVE_MID_TIER_ENV, null);
}
public static String getSandboxMidtierAccessToken(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_SANDBOX_MID_TIER_ACCESS_TOKEN, null);
}
public static String getSandboxMidtierRefreshUrl(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_SANDBOX_MID_TIER_REFRESH_URL, null);
}
public static String getSandboxMidtierEnv(Context context){
SharedPreferences preferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
return preferences.getString(SHARED_PREFS_SANDBOX_MID_TIER_ENV, null);
}
}
| 662 |
0 | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp | Create_ds/paypal-here-sdk-android-distribution/SampleApp/src/main/java/com/paypal/heresdk/sampleapp/login/LoginActivity.java | package com.paypal.heresdk.sampleapp.login;
import java.net.URI;
import java.util.List;
import java.util.Set;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.paypal.heresdk.sampleapp.R;
import com.paypal.heresdk.sampleapp.ui.ReaderConnectionActivity;
import com.paypal.heresdk.sampleapp.ui.StepView;
import com.paypal.heresdk.sampleapp.ui.ToolbarActivity;
import com.paypal.paypalretailsdk.AppInfo;
import com.paypal.paypalretailsdk.Merchant;
import com.paypal.paypalretailsdk.NetworkRequest;
import com.paypal.paypalretailsdk.NetworkResponse;
import com.paypal.paypalretailsdk.RetailSDK;
import com.paypal.paypalretailsdk.RetailSDKException;
import com.paypal.paypalretailsdk.SdkCredential;
import static com.paypal.heresdk.sampleapp.ui.OfflinePayActivity.OFFLINE_MODE;
import static com.paypal.heresdk.sampleapp.ui.OfflinePayActivity.OFFLINE_INIT;
import static com.paypal.heresdk.sampleapp.ui.OfflinePayActivity.PREF_NAME;
public class LoginActivity extends ToolbarActivity implements View.OnClickListener
{
private static final String LOG_TAG = LoginActivity.class.getSimpleName();
public static final String PREFS_NAME = "SDKSampleAppPreferences";
public static final String PREF_TOKEN_KEY_NAME = "lastToken";
// private static final String MID_TIER_URL_FOR_LIVE = "http://pph-retail-sdk-sample.herokuapp.com/toPayPal/live";
private static final String MID_TIER_URL_FOR_LIVE = "http://pph-retail-sdk-sample.herokuapp.com/toPayPal/live?returnTokenOnQueryString=true";
// private static final String MID_TIER_URL_FOR_SANDBOX = "http://pph-retail-sdk-sample.herokuapp.com/toPayPal/sandbox";
private static final String MID_TIER_URL_FOR_SANDBOX = "http://pph-retail-sdk-sample.herokuapp.com/toPayPal/sandbox?returnTokenOnQueryString=true";
private static final String SW_REPOSITORY = "production"; // "production-stage"
public static final String INTENT_URL_WEBVIEW = "URL_FOR_WEBVIEW";
public static final String INTENT_ISLIVE_WEBVIEW = "ISLIVE_FOR_WEBVIEW";
private ProgressDialog mProgressDialog = null;
private RadioGroup radioGroup1;
private StepView step1;
private StepView step2;
private Boolean offlineClicked;
private Button connectButton;
// abstract method from ToolbarActivity
@Override
public int getLayoutResId()
{
return R.layout.login_activity;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "onCreate");
radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
connectButton = (Button) findViewById(R.id.connect_reader_button);
step1 = (StepView)findViewById(R.id.step1);
step1.setOnButtonClickListener(this);
step2 = (StepView)findViewById(R.id.step2);
step2.setOnButtonClickListener(this);
offlineClicked = false;
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
Log.d(LOG_TAG, "onConfigurationChanged");
}
public void onInitMerchantClicked()
{
RadioButton sandboxButton = (RadioButton) findViewById(R.id.radioSandbox);
RadioButton liveButton = (RadioButton) findViewById(R.id.radioLive);
RadioButton offlineButton = (RadioButton) findViewById(R.id.radioOffline);
if (sandboxButton.isChecked())
{
/*If User selected Sandbox environment then we need to check if we already have sandbox token form mid tier server or not.
* If we don't have the token then we need to start web view, else we can use the token and set it to sdk.
*/
//String token = LocalPreferences.getSandboxMidtierToken(LoginActivity.this);
String accessToken = LocalPreferences.getSandboxMidtierAccessToken(LoginActivity.this);
String refreshUrl = LocalPreferences.getSandboxMidtierRefreshUrl(LoginActivity.this);
String env = LocalPreferences.getSandboxMidtierEnv(LoginActivity.this);
if (null == accessToken || null == refreshUrl || null == env)
{
startWebView(MID_TIER_URL_FOR_SANDBOX, true, false);
}
else
{
Log.d(LOG_TAG, "onLoginButtonClicked looks like we have sandbox access token: " + accessToken);
//initializeMerchant(token, SW_REPOSITORY);
SdkCredential credential = new SdkCredential(env, accessToken);
credential.setTokenRefreshCredentials(refreshUrl);
Log.d(LOG_TAG, "onLoginButtonClicked looks like we have live token. Starting payment options activity");
initializeMerchant(credential);
}
}
else if (offlineButton.isChecked())
{
initializeMerchantOffline();
}
else
{
/* If User selected Live environment then we need to check if we already have live token form mid tier server or not.
* If we don't have the token then we need to start web view, else we can use the token and set it to sdk.
*/
//String token = LocalPreferences.getLiveMidtierToken(LoginActivity.this);
String accessToken = LocalPreferences.getLiveMidtierAccessToken(LoginActivity.this);
String refreshUrl = LocalPreferences.getLiveMidtierRefreshUrl(LoginActivity.this);
String env = LocalPreferences.getLiveMidtierEnv(LoginActivity.this);
if (null == accessToken || null == refreshUrl || null == env)
{
startWebView(MID_TIER_URL_FOR_LIVE, false, true);
//hardCodingInitMerchant();
}
else
{
Log.d(LOG_TAG, "onLoginButtonClicked looks like we have live access token: " + accessToken);
SdkCredential credential = new SdkCredential(env, accessToken);
credential.setTokenRefreshCredentials(refreshUrl);
Log.d(LOG_TAG, "onLoginButtonClicked looks like we have live token. Starting payment options activity");
initializeMerchant(credential);
}
}
}
private void hardCodingInitMerchant()//use this method when using stage rather than live
{
Log.d(LOG_TAG, "hard-coding for initializeMerchant()");
// hard coding the initializeMerchant
String access_token = "A103.LYafNu2QoAUgEDGshkgLaN9M2xSeTnhTfrFns2HNYdceSa6GO3LhScOMQzdX3TI8.ZeE98NKhHF72Wu-4QNLQ4Rlct8i";
String env = "stage2d0020";
Log.d(LOG_TAG, "shouldOverrideURLLoading: access_token: " + access_token);
Log.d(LOG_TAG, "shouldOverrideURLLoading: env: " + env);
SdkCredential credential = new SdkCredential(env, access_token);
// credential.setTokenRefreshCredentials(refresh_url);
initializeMerchant(credential);
}
public void onLogoutClicked(View view)
{
RetailSDK.logout();
// Need to remove tokens from local preferences
LocalPreferences.storeSandboxMidTierCredentials(LoginActivity.this, null, null, null);
LocalPreferences.storeLiveMidTierCredentials(LoginActivity.this, null, null, null);
Toast.makeText(getApplicationContext(), "Logged out! Please initialize Merchant.", Toast.LENGTH_SHORT).show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
public void onConnectCardReaderClicked(View view)
{
Intent readerConnectionIntent = new Intent(LoginActivity.this, ReaderConnectionActivity.class);
readerConnectionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(readerConnectionIntent);
}
private void startWebView(String url, final boolean isSandBox, final boolean isLive)
{
Log.d(LOG_TAG, "startWebView url: " + url + " isSandbox: " + isSandBox + " isLive: " + isLive);
final WebView webView = (WebView) findViewById(R.id.id_webView);
webView.setVisibility(View.VISIBLE);
webView.getSettings().setJavaScriptEnabled(true);
webView.requestFocus(View.FOCUS_DOWN);
webView.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
Log.d(LOG_TAG, "shouldOverrideURLLoading: url: " + url);
//String returnStringCheckParam = "retailsdksampleapp://oauth?sdk_token=";
String returnStringCheckParam = "retailsdksampleapp://oauth?access_token=";
// List<NameValuePair> parameters = URLEncodedUtils.parse(new URI(url));
Uri uri = Uri.parse(url);
Set<String> paramNames = uri.getQueryParameterNames();
for (String key: paramNames) {
String value = uri.getQueryParameter(key);
Log.d(LOG_TAG, "shouldOverrideURLLoading: name: " + key + " value: " + value);
}
if (null != url && url.startsWith(returnStringCheckParam))
{
if (paramNames.contains("access_token") && paramNames.contains("refresh_url") && paramNames.contains("env"))
{
String access_token = uri.getQueryParameter("access_token");
String refresh_url = uri.getQueryParameter("refresh_url");
String env = uri.getQueryParameter("env");
Log.d(LOG_TAG, "shouldOverrideURLLoading: access_token: " + access_token);
Log.d(LOG_TAG, "shouldOverrideURLLoading: refresh_url: " + refresh_url);
Log.d(LOG_TAG, "shouldOverrideURLLoading: env: " + env);
SdkCredential credential = new SdkCredential(env, access_token);
credential.setTokenRefreshCredentials(refresh_url);
//String compositeToken = url.substring(returnStringCheckParam.length());
//Log.d(LOG_TAG, "shouldOverrideURLLoading compositeToken: " + compositeToken);
if (isSandBox)
{
//LocalPreferences.storeSandboxMidTierToken(LoginActivity.this, compositeToken);
//startPaymentOptionsActivity(compositeToken, PayPalHereSDK.Sandbox);
//initializeMerchant(compositeToken, SW_REPOSITORY);
LocalPreferences.storeSandboxMidTierCredentials(LoginActivity.this, access_token, refresh_url, env);
initializeMerchant(credential);
}
else if (isLive)
{
LocalPreferences.storeLiveMidTierCredentials(LoginActivity.this, access_token, refresh_url, env);
//LocalPreferences.storeLiveMidTierToken(LoginActivity.this, compositeToken);
// startPaymentOptionsActivity(compositeToken, PayPalHereSDK.Live);
initializeMerchant(credential);
}
webView.setVisibility(View.GONE);
return true;
}
}
return false;
}
});
webView.loadUrl(url);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("result");
Log.d(LOG_TAG, "onActivityResult result: " + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
Log.d(LOG_TAG, "onActivityResult RESULT_CANCELED! ");
//Write your code if there's no result
}
}
}
private void initializeMerchant(final String token, String repository)
{
Log.d(LOG_TAG, "initializeMerchant token: " + token);
Log.d(LOG_TAG, "initializeMerchant serverName: " + repository);
try
{
showProcessingProgressbar();
RetailSDK.initializeMerchant(token, repository, new RetailSDK.MerchantInitializedCallback()
{
@Override
public void merchantInitialized(RetailSDKException error, Merchant merchant)
{
saveToken(token);
SharedPreferences pref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(OFFLINE_MODE, false);
editor.putBoolean(OFFLINE_INIT, false);
editor.apply();
editor.commit();
LoginActivity.this.merchantReady(error, merchant);
}
});
}
catch (Exception x)
{
try
{
Log.e(LOG_TAG, "exception: " + x.toString());
//statusText.setText(x.toString());
}
catch (Exception ignore)
{
ignore.printStackTrace();
}
x.printStackTrace();
}
}
private void initializeMerchant(final SdkCredential credential)
{
try
{
showProcessingProgressbar();
RetailSDK.initializeMerchant(credential, new RetailSDK.MerchantInitializedCallback()
{
@Override
public void merchantInitialized(RetailSDKException error, Merchant merchant)
{
SharedPreferences pref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(OFFLINE_MODE, false);
editor.putBoolean(OFFLINE_INIT, false);
editor.apply();
editor.commit();
LoginActivity.this.merchantReady(error, merchant);
}
});
}
catch (Exception x)
{
try
{
Log.e(LOG_TAG, "exception: " + x.toString());
//statusText.setText(x.toString());
}
catch (Exception ignore)
{
ignore.printStackTrace();
}
x.printStackTrace();
}
}
private void initializeMerchantOffline()
{
try {
showProcessingProgressbar();
RetailSDK.initializeMerchantOffline(new RetailSDK.MerchantInitializedCallback()
{
@Override
public void merchantInitialized(RetailSDKException error, Merchant merchant)
{
offlineClicked = true;
if (error == null) {
SharedPreferences pref = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(OFFLINE_MODE, true);
editor.putBoolean(OFFLINE_INIT, true);
editor.apply();
editor.commit();
}
LoginActivity.this.merchantReady(error, merchant);
}
});
}
catch (Exception x)
{
Log.e(LOG_TAG, "Exception: " + x.toString());
x.printStackTrace();
}
}
void merchantReady(final RetailSDKException error, final Merchant merchant)
{
if (error == null)
{
LoginActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Add the BN code for Partner tracking. To obtain this value, contact
// your PayPal account representative. Please do not change this value when
// using this sample app for testing.
merchant.setReferrerCode("PPHSDK_SampleApp_Android");
Log.d(LOG_TAG, "merchantReady without any error");
cancelProgressbar();
step2.setStepCompleted();
final TextView txtMerchantEmail = (TextView) findViewById(R.id.merchant_email);
if (offlineClicked) {
txtMerchantEmail.setText("Offline Merchant loaded");
}
else
{
txtMerchantEmail.setText(merchant.getEmailAddress());
}
final RelativeLayout logoutContainer = (RelativeLayout) findViewById(R.id.logout);
logoutContainer.setVisibility(View.VISIBLE);
connectButton.setVisibility(View.VISIBLE);
}
});
}
else
{
LoginActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
Log.d(LOG_TAG, "RetailSDK initialize on Error:" + error.toString());
cancelProgressbar();
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setTitle(R.string.error_title);
if (offlineClicked) {
builder.setMessage(error.getMessage());
} else
{
builder.setMessage(R.string.error_initialize_msg);
}
builder.setCancelable(false);
builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Log.d(LOG_TAG, "RetailSDK Initialize error AlertDialog onClick");
dialog.dismiss();
finish();
}
});
builder.show();
}
});
}
}
private void saveToken(String token)
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_TOKEN_KEY_NAME, token);
editor.commit();
}
private void showProcessingProgressbar()
{
step2.showProgressBar();
}
private void cancelProgressbar()
{
step2.hideProgressBarShowTick();
}
@Override
public void onClick(View v)
{
if (v == step1.getButton()){
initSDK();
}else if(v == step2.getButton()){
onInitMerchantClicked();
}
}
public void initSDK()
{
try
{
AppInfo info = new AppInfo("SampleApp", "1.0", "01");
RetailSDK.initialize(getApplicationContext(), new RetailSDK.AppState()
{
@Override
public Activity getCurrentActivity()
{
return LoginActivity.this;
}
@Override
public boolean getIsTabletMode()
{
return false;
}
}, info);
/**
* Add this observer to handle insecure network errors from the sdk
*/
RetailSDK.addUntrustedNetworkObserver(new RetailSDK.UntrusterNetworkObserver() {
@Override
public void untrustedNetwork(RetailSDKException error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Insecure network. Please join a secure network and open the app again")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
catch (RetailSDKException e)
{
e.printStackTrace();
}
step1.setStepCompleted();
step2.setStepEnabled();
}
}
| 663 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/util/TcpTransport.java | /**
gxfdgvdfg * Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.util;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.SocketFactory;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.transport.tcp.TcpBufferedInputStream;
import org.apache.activemq.transport.tcp.TcpBufferedOutputStream;
import org.apache.activemq.util.ServiceStopper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class TcpTransport implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(TcpTransport.class);
protected final URI remoteLocation;
protected final OpenWireFormat wireFormat;
protected int connectionTimeout = 30000;
protected int socketBufferSize = 64 * 1024;
protected int ioBufferSize = 8 * 1024;
protected Socket socket;
protected DataOutputStream dataOut;
protected DataInputStream dataIn;
protected int minmumWireFormatVersion;
protected SocketFactory socketFactory;
protected final AtomicReference<CountDownLatch> stoppedLatch = new AtomicReference<CountDownLatch>();
protected volatile int receiveCounter;
private Thread runnerThread;
private AtomicBoolean started = new AtomicBoolean(false);
private AtomicBoolean stopping = new AtomicBoolean(false);
private AtomicBoolean stopped = new AtomicBoolean(false);
private TransportListener transportListener;
/**
* Connect to a remote Node - e.g. a Broker
*
* @param wireFormat
* @param socketFactory
* @param remoteLocation
* @param localLocation
* - e.g. local InetAddress and local port
* @throws IOException
* @throws UnknownHostException
*/
public TcpTransport(OpenWireFormat wireFormat, URI remoteLocation) throws UnknownHostException, IOException {
this.wireFormat = wireFormat;
this.socketFactory = SocketFactory.getDefault();
try {
this.socket = socketFactory.createSocket();
} catch (SocketException e) {
this.socket = null;
}
this.remoteLocation = remoteLocation;
}
/**
* A one way asynchronous send
*/
public void oneway(Object command) throws IOException {
checkStarted();
wireFormat.marshal(command, dataOut);
dataOut.flush();
}
/**
* reads packets from a Socket
*/
public void run() {
LOG.trace("TCP consumer thread for {} starting", this);
this.runnerThread = Thread.currentThread();
try {
while (!isStopped()) {
doRun();
}
} catch (IOException e) {
stoppedLatch.get().countDown();
onException(e);
} catch (Throwable e) {
stoppedLatch.get().countDown();
IOException ioe = new IOException("Unexpected error occured: " + e);
ioe.initCause(e);
onException(ioe);
} finally {
stoppedLatch.get().countDown();
}
}
protected void doRun() throws IOException {
try {
Object command = readCommand();
doConsume(command);
} catch (SocketTimeoutException e) {
} catch (InterruptedIOException e) {
}
}
protected Object readCommand() throws IOException {
return wireFormat.unmarshal(dataIn);
}
/**
* Configures the socket for use
*
* @param sock
* the socket
* @throws SocketException
* , IllegalArgumentException if setting the options on the socket
* failed.
*/
protected void initialiseSocket(Socket sock) throws SocketException, IllegalArgumentException {
try {
sock.setReceiveBufferSize(socketBufferSize);
sock.setSendBufferSize(socketBufferSize);
} catch (SocketException se) {
LOG.warn("Cannot set socket buffer size = {}", socketBufferSize);
LOG.debug("Cannot set socket buffer size. Reason: {}. This exception is ignored.",
se.getMessage(), se);
}
}
public void start() throws Exception {
if (started.compareAndSet(false, true)) {
boolean success = false;
stopped.set(false);
try {
doStart();
success = true;
} finally {
started.set(success);
}
}
}
public void stop() throws Exception {
if (stopped.compareAndSet(false, true)) {
stopping.set(true);
ServiceStopper stopper = new ServiceStopper();
try {
doStop(stopper);
} catch (Exception e) {
stopper.onException(this, e);
}
stopped.set(true);
started.set(false);
stopping.set(false);
stopper.throwFirstException();
}
CountDownLatch countDownLatch = stoppedLatch.get();
if (countDownLatch != null && Thread.currentThread() != this.runnerThread) {
countDownLatch.await(1, TimeUnit.SECONDS);
}
}
protected void doStart() throws Exception {
connect();
stoppedLatch.set(new CountDownLatch(1));
runnerThread = new Thread(null, this, "OpenWire Test Transport: " + toString());
runnerThread.setDaemon(false);
runnerThread.start();
}
protected void connect() throws Exception {
if (socket == null && socketFactory == null) {
throw new IllegalStateException("Cannot connect if the socket or socketFactory have not been set");
}
InetSocketAddress remoteAddress = null;
if (remoteLocation != null) {
remoteAddress = new InetSocketAddress(remoteLocation.getHost(), remoteLocation.getPort());
}
socket = socketFactory.createSocket(remoteAddress.getAddress(), remoteAddress.getPort());
initialiseSocket(socket);
initializeStreams();
}
protected void doStop(ServiceStopper stopper) throws Exception {
LOG.debug("Stopping transport {}", this);
if (socket != null) {
LOG.trace("Closing socket {}", socket);
try {
socket.close();
LOG.debug("Closed socket {}", socket);
} catch (IOException e) {
LOG.debug("Caught exception closing socket {}. This exception will be ignored.", socket, e);
}
}
}
protected void initializeStreams() throws Exception {
TcpBufferedInputStream buffIn = new TcpBufferedInputStream(socket.getInputStream(), ioBufferSize) {
@Override
public int read() throws IOException {
receiveCounter++;
return super.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
receiveCounter++;
return super.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
receiveCounter++;
return super.skip(n);
}
@Override
protected void fill() throws IOException {
receiveCounter++;
super.fill();
}
};
this.dataIn = new DataInputStream(buffIn);
TcpBufferedOutputStream outputStream = new TcpBufferedOutputStream(socket.getOutputStream(), ioBufferSize);
this.dataOut = new DataOutputStream(outputStream);
}
protected void closeStreams() throws IOException {
if (dataOut != null) {
dataOut.close();
}
if (dataIn != null) {
dataIn.close();
}
}
/**
* Process the inbound command
*/
public void doConsume(Object command) {
if (command != null) {
if (transportListener != null) {
transportListener.onCommand(command);
} else {
LOG.error("No transportListener available to process inbound command: {}", command);
}
}
}
/**
* Passes any IO exceptions into the transport listener
*/
public void onException(IOException e) {
if (transportListener != null) {
try {
transportListener.onException(e);
} catch (RuntimeException e2) {
// Handle any unexpected runtime exceptions by debug logging them.
LOG.debug("Unexpected runtime exception: " + e2, e2);
}
}
}
public String getRemoteAddress() {
if (socket != null) {
SocketAddress address = socket.getRemoteSocketAddress();
if (address instanceof InetSocketAddress) {
return "tcp://" + ((InetSocketAddress) address).getAddress().getHostAddress() + ":" + ((InetSocketAddress) address).getPort();
} else {
return "" + socket.getRemoteSocketAddress();
}
}
return null;
}
public int getReceiveCounter() {
return receiveCounter;
}
public OpenWireFormat getWireFormat() {
return wireFormat;
}
/**
* @return true if this service has been started
*/
public boolean isStarted() {
return started.get();
}
/**
* @return true if this service is in the process of closing
*/
public boolean isStopping() {
return stopping.get();
}
/**
* @return true if this service is closed
*/
public boolean isStopped() {
return stopped.get();
}
/**
* Returns the current transport listener
*/
public TransportListener getTransportListener() {
return transportListener;
}
/**
* Registers an inbound command listener
*
* @param commandListener
*/
public void setTransportListener(TransportListener commandListener) {
this.transportListener = commandListener;
}
public int getMinmumWireFormatVersion() {
return minmumWireFormatVersion;
}
public void setMinmumWireFormatVersion(int minmumWireFormatVersion) {
this.minmumWireFormatVersion = minmumWireFormatVersion;
}
public int getSocketBufferSize() {
return socketBufferSize;
}
/**
* Sets the buffer size to use on the socket
*/
public void setSocketBufferSize(int socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
/**
* Sets the timeout used to connect to the socket
*/
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
/**
* @return the ioBufferSize
*/
public int getIoBufferSize() {
return this.ioBufferSize;
}
/**
* @param ioBufferSize
* the ioBufferSize to set
*/
public void setIoBufferSize(int ioBufferSize) {
this.ioBufferSize = ioBufferSize;
}
/**
* @return pretty print of 'this'
*/
@Override
public String toString() {
return "" + (socket.isConnected() ? "tcp://" + socket.getInetAddress() + ":" + socket.getPort() + "@" + socket.getLocalPort() : remoteLocation);
}
protected void checkStarted() throws IOException {
if (!isStarted()) {
throw new IOException("The transport is not running.");
}
}
}
| 664 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/util/TransportListener.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.util;
import java.io.IOException;
/**
* An asynchronous listener of commands
*/
public interface TransportListener {
/**
* called to process a command
*
* @param command
*/
void onCommand(Object command);
/**
* An unrecoverable exception has occurred on the transport
*
* @param error
*/
void onException(IOException error);
/**
* The transport has suffered an interruption from which it hopes to recover
*
*/
void transportInterupted();
/**
* The transport has resumed after an interruption
*
*/
void transportResumed();
}
| 665 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/util/Wait.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.util;
import java.util.concurrent.TimeUnit;
public class Wait {
public static final long MAX_WAIT_MILLIS = 30 * 1000;
public static final int SLEEP_MILLIS = 1000;
public interface Condition {
boolean isSatisified() throws Exception;
}
public static boolean waitFor(Condition condition) throws Exception {
return waitFor(condition, MAX_WAIT_MILLIS);
}
public static boolean waitFor(final Condition condition, final long duration) throws Exception {
return waitFor(condition, duration, SLEEP_MILLIS);
}
public static boolean waitFor(final Condition condition, final long duration, final int sleepMillis) throws Exception {
final long expiry = System.currentTimeMillis() + duration;
boolean conditionSatisified = condition.isSatisified();
while (!conditionSatisified && System.currentTimeMillis() < expiry) {
TimeUnit.MILLISECONDS.sleep(sleepMillis);
conditionSatisified = condition.isSatisified();
}
return conditionSatisified;
}
}
| 666 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/OpenWireInteropTests.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.openwire.commands.ConnectionInfo;
import org.apache.activemq.openwire.commands.ConsumerInfo;
import org.apache.activemq.openwire.commands.Message;
import org.apache.activemq.openwire.commands.OpenWireQueue;
import org.apache.activemq.openwire.commands.OpenWireTextMessage;
import org.apache.activemq.openwire.commands.OpenWireTopic;
import org.apache.activemq.openwire.commands.ProducerInfo;
import org.apache.activemq.openwire.util.Wait;
import org.apache.activemq.openwire.utils.OpenWireConnection;
import org.apache.activemq.openwire.utils.OpenWireConsumer;
import org.apache.activemq.openwire.utils.OpenWireProducer;
import org.apache.activemq.openwire.utils.OpenWireSession;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(Parameterized.class)
public abstract class OpenWireInteropTests extends OpenWireInteropTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(OpenWireInteropTests.class);
protected OpenWireConnection connectionId;
protected boolean tightEncodingEnabled;
public OpenWireInteropTests(boolean tightEncodingEnabled) {
this.tightEncodingEnabled = tightEncodingEnabled;
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] { { Boolean.FALSE }, { Boolean.TRUE } });
}
@Override
protected boolean isTightEncodingEnabled() {
return tightEncodingEnabled;
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
connectionId = new OpenWireConnection();
}
@Test(timeout = 60000)
public void testCanConnect() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertEquals(getOpenWireVersion(), getRemoteWireFormatInfo().getVersion());
if (isTightEncodingEnabled()) {
LOG.info("Should be using tight encoding: are we? {}", wireFormat.isTightEncodingEnabled());
assertTrue(wireFormat.isTightEncodingEnabled());
} else {
LOG.info("Should not be using tight encoding: are we? {}", wireFormat.isTightEncodingEnabled());
assertFalse(wireFormat.isTightEncodingEnabled());
}
}
@Test(timeout = 60000)
public void testCreateConnection() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
}
@Test(timeout = 60000)
public void testCreateSession() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connectionId.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
}
@Test(timeout = 60000)
public void testCreateProducer() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connectionId.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireProducer producerId = sessionId.createOpenWireProducer();
ProducerInfo info = producerId.createProducerInfo(new OpenWireTopic(name.getMethodName() + "-Topic"));
info.setDispatchAsync(false);
assertTrue(request(info, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getTopicProducers().length);
assertTrue(request(producerId.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getTopicProducers().length);
}
@Test(timeout = 60000)
public void testCreateConsumer() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connectionId.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireConsumer consumerId = sessionId.createOpenWireConsumer();
ConsumerInfo info = consumerId.createConsumerInfo(new OpenWireTopic(name.getMethodName() + "-Topic"));
info.setDispatchAsync(false);
assertTrue(request(info, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getTopicSubscribers().length);
assertTrue(request(consumerId.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getTopicSubscribers().length);
}
@Test(timeout = 60000)
public void testSendMessageToQueue() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connectionId.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireProducer producerId = sessionId.createOpenWireProducer();
OpenWireQueue queue = new OpenWireQueue(name.getMethodName() + "-Queue");
ProducerInfo info = producerId.createProducerInfo(queue);
info.setDispatchAsync(false);
assertTrue(request(info, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueProducers().length);
OpenWireTextMessage message = new OpenWireTextMessage();
message.setText("test");
message.setTimestamp(System.currentTimeMillis());
message.setMessageId(producerId.getNextMessageId());
message.setProducerId(producerId.getProducerId());
message.setDestination(queue);
message.onSend();
assertTrue(request(message, 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(queue.getPhysicalName()).getQueueSize());
assertTrue(request(producerId.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getQueueProducers().length);
}
@Test(timeout = 60000)
public void testConsumeMessageFromQueue() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
assertTrue(request(createConnectionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connectionId.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireProducer producerId = sessionId.createOpenWireProducer();
OpenWireQueue queue = new OpenWireQueue(name.getMethodName() + "-Queue");
ProducerInfo producerInfo = producerId.createProducerInfo(queue);
producerInfo.setDispatchAsync(false);
assertTrue(request(producerInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueProducers().length);
OpenWireTextMessage message = new OpenWireTextMessage();
message.setText("test");
message.setTimestamp(System.currentTimeMillis());
message.setMessageId(producerId.getNextMessageId());
message.setProducerId(producerId.getProducerId());
message.setDestination(queue);
message.onSend();
assertTrue(request(message, 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(queue.getPhysicalName()).getQueueSize());
OpenWireConsumer consumerId = sessionId.createOpenWireConsumer();
ConsumerInfo consumerInfo = consumerId.createConsumerInfo(queue);
consumerInfo.setDispatchAsync(false);
consumerInfo.setPrefetchSize(1);
assertTrue(request(consumerInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueSubscribers().length);
assertTrue("Should have received a message", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
return messages.size() == 1;
}
}));
Message incoming = messages.poll();
assertTrue(incoming instanceof OpenWireTextMessage);
OpenWireTextMessage received = (OpenWireTextMessage) incoming;
assertEquals("test", received.getText());
assertTrue(request(consumerId.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getQueueSubscribers().length);
}
protected ConnectionInfo createConnectionInfo() {
ConnectionInfo info = new ConnectionInfo(connectionId.getConnectionId());
info.setManageable(false);
info.setFaultTolerant(false);
info.setClientId(name.getMethodName());
return info;
}
}
| 667 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/WireFormatInfoMarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import org.apache.activemq.openwire.buffer.Buffer;
import org.apache.activemq.openwire.commands.WireFormatInfo;
import org.apache.activemq.util.ByteSequence;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test that the WireFormatInfo marshals and un-marshals correctly.
*/
public abstract class WireFormatInfoMarshaledSizeTest {
private static final Logger LOG = LoggerFactory.getLogger(WireFormatInfoMarshaledSizeTest.class);
private OpenWireFormat wireFormat;
public int getExpectedMarshaledSize() {
return 244;
}
public abstract int getVersion();
@Before
public void setUp() throws Exception {
OpenWireFormatFactory factory = new OpenWireFormatFactory();
factory.setVersion(getVersion());
wireFormat = factory.createWireFormat();
}
@Test
public void testMarshalledSize1() throws Exception {
WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
Buffer result = wireFormat.marshal(info);
assertNotNull(result);
LOG.info("Size of marshalled object: {}", result.getLength());
assertEquals(getExpectedMarshaledSize(), result.getLength());
ByteArrayInputStream bytesIn = new ByteArrayInputStream(result.toByteArray());
DataInputStream input = new DataInputStream(bytesIn);
int size = input.readInt();
assertEquals(getExpectedMarshaledSize() - 4, size);
}
@Test
public void testMarshalledSize2() throws Exception {
WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(bytesOut);
wireFormat.marshal(info, dataOut);
dataOut.close();
ByteSequence result = new ByteSequence(bytesOut.toByteArray());
LOG.info("Size of marshalled object: {}", result.getLength());
assertEquals(getExpectedMarshaledSize(), result.getLength());
ByteArrayInputStream bytesIn = new ByteArrayInputStream(result.data);
DataInputStream input = new DataInputStream(bytesIn);
int size = input.readInt();
assertEquals(getExpectedMarshaledSize() - 4, size);
}
@Test
public void testMarshalThenUnmarshal1() throws Exception {
final WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
LOG.info("Original: {}", info);
Buffer marshaledForm = wireFormat.marshal(info);
assertNotNull(marshaledForm);
Object result = wireFormat.unmarshal(marshaledForm);
assertNotNull(result);
assertTrue(result instanceof WireFormatInfo);
WireFormatInfo duplicate = (WireFormatInfo) result;
LOG.info("Duplicated: {}", duplicate);
assertEquals(info.getVersion(), duplicate.getVersion());
assertEquals(info.getCacheSize(), duplicate.getCacheSize());
assertEquals(info.getMaxFrameSize(), duplicate.getMaxFrameSize());
assertEquals(info.getMaxInactivityDuration(), duplicate.getMaxInactivityDuration());
assertEquals(info.getMaxInactivityDurationInitalDelay(), duplicate.getMaxInactivityDurationInitalDelay());
assertEquals(info.isCacheEnabled(), duplicate.isCacheEnabled());
assertEquals(info.isSizePrefixDisabled(), duplicate.isSizePrefixDisabled());
assertEquals(info.isTcpNoDelayEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isStackTraceEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isTightEncodingEnabled(), duplicate.isTightEncodingEnabled());
}
@Test
public void testMarshalThenUnmarshal2() throws Exception {
final WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
LOG.info("Original: {}", info);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(bytesOut);
wireFormat.marshal(info, dataOut);
dataOut.close();
ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytesOut.toByteArray());
DataInputStream dataIn = new DataInputStream(bytesIn);
Object result = wireFormat.unmarshal(dataIn);
assertNotNull(result);
assertTrue(result instanceof WireFormatInfo);
WireFormatInfo duplicate = (WireFormatInfo) result;
LOG.info("Duplicated: {}", duplicate);
assertEquals(info.getVersion(), duplicate.getVersion());
assertEquals(info.getCacheSize(), duplicate.getCacheSize());
assertEquals(info.getMaxFrameSize(), duplicate.getMaxFrameSize());
assertEquals(info.getMaxInactivityDuration(), duplicate.getMaxInactivityDuration());
assertEquals(info.getMaxInactivityDurationInitalDelay(), duplicate.getMaxInactivityDurationInitalDelay());
assertEquals(info.isCacheEnabled(), duplicate.isCacheEnabled());
assertEquals(info.isSizePrefixDisabled(), duplicate.isSizePrefixDisabled());
assertEquals(info.isTcpNoDelayEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isStackTraceEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isTightEncodingEnabled(), duplicate.isTightEncodingEnabled());
}
@Test
public void testMarshalThenUnmarshal3() throws Exception {
final WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
LOG.info("Original: {}", info);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(bytesOut);
wireFormat.marshal(info, dataOut);
dataOut.close();
Buffer marshaledForm = new Buffer(bytesOut.toByteArray());
Object result = wireFormat.unmarshal(marshaledForm);
assertNotNull(result);
assertTrue(result instanceof WireFormatInfo);
WireFormatInfo duplicate = (WireFormatInfo) result;
LOG.info("Duplicated: {}", duplicate);
assertEquals(info.getVersion(), duplicate.getVersion());
assertEquals(info.getCacheSize(), duplicate.getCacheSize());
assertEquals(info.getMaxFrameSize(), duplicate.getMaxFrameSize());
assertEquals(info.getMaxInactivityDuration(), duplicate.getMaxInactivityDuration());
assertEquals(info.getMaxInactivityDurationInitalDelay(), duplicate.getMaxInactivityDurationInitalDelay());
assertEquals(info.isCacheEnabled(), duplicate.isCacheEnabled());
assertEquals(info.isSizePrefixDisabled(), duplicate.isSizePrefixDisabled());
assertEquals(info.isTcpNoDelayEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isStackTraceEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isTightEncodingEnabled(), duplicate.isTightEncodingEnabled());
}
@Test
public void testMarshalThenUnmarshal4() throws Exception {
final WireFormatInfo info = wireFormat.getPreferedWireFormatInfo();
LOG.info("Original: {}", info);
Buffer marshaledForm = wireFormat.marshal(info);
assertNotNull(marshaledForm);
ByteArrayInputStream bytesIn = new ByteArrayInputStream(marshaledForm.data);
DataInputStream dataIn = new DataInputStream(bytesIn);
Object result = wireFormat.unmarshal(dataIn);
assertNotNull(result);
assertTrue(result instanceof WireFormatInfo);
WireFormatInfo duplicate = (WireFormatInfo) result;
LOG.info("Duplicated: {}", duplicate);
assertEquals(info.getVersion(), duplicate.getVersion());
assertEquals(info.getCacheSize(), duplicate.getCacheSize());
assertEquals(info.getMaxFrameSize(), duplicate.getMaxFrameSize());
assertEquals(info.getMaxInactivityDuration(), duplicate.getMaxInactivityDuration());
assertEquals(info.getMaxInactivityDurationInitalDelay(), duplicate.getMaxInactivityDurationInitalDelay());
assertEquals(info.isCacheEnabled(), duplicate.isCacheEnabled());
assertEquals(info.isSizePrefixDisabled(), duplicate.isSizePrefixDisabled());
assertEquals(info.isTcpNoDelayEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isStackTraceEnabled(), duplicate.isTcpNoDelayEnabled());
assertEquals(info.isTightEncodingEnabled(), duplicate.isTightEncodingEnabled());
}
}
| 668 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/OpenWireInteropTestSupport.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec;
import java.io.IOException;
import java.net.URI;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.jms.JMSException;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.codec.OpenWireFormatFactory;
import org.apache.activemq.openwire.commands.BrokerInfo;
import org.apache.activemq.openwire.commands.Command;
import org.apache.activemq.openwire.commands.KeepAliveInfo;
import org.apache.activemq.openwire.commands.Message;
import org.apache.activemq.openwire.commands.MessageDispatch;
import org.apache.activemq.openwire.commands.Response;
import org.apache.activemq.openwire.commands.ShutdownInfo;
import org.apache.activemq.openwire.commands.WireFormatInfo;
import org.apache.activemq.openwire.util.TcpTransport;
import org.apache.activemq.openwire.util.TransportListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Base class used in testing the interoperability between the OpenWire
* commands and Marshalers in this library and those in ActiveMQ.
*/
public abstract class OpenWireInteropTestSupport implements TransportListener {
private static final Logger LOG = LoggerFactory.getLogger(OpenWireInteropTestSupport.class);
@Rule public TestName name = new TestName();
protected BrokerService brokerService;
private TcpTransport transport;
protected URI connectionURI;
private OpenWireFormatFactory factory;
protected OpenWireFormat wireFormat;
private CountDownLatch connected;
private WireFormatInfo remoteWireformatInfo;
private BrokerInfo remoteInfo;
private Exception failureCause;
private final AtomicInteger requestIdGenerator = new AtomicInteger(1);
private final Map<Integer, CountDownLatch> requestMap =
new ConcurrentHashMap<Integer, CountDownLatch>();
protected Command latest;
protected final Queue<Message> messages = new LinkedList<Message>();
@Before
public void setUp() throws Exception {
brokerService = createBroker();
brokerService.start();
brokerService.waitUntilStarted();
factory = new OpenWireFormatFactory();
factory.setVersion(getOpenWireVersion());
factory.setCacheEnabled(false);
factory.setTightEncodingEnabled(isTightEncodingEnabled());
wireFormat = factory.createWireFormat();
}
@After
public void tearDown() throws Exception {
disconnect();
if (brokerService != null) {
brokerService.stop();
brokerService.waitUntilStopped();
}
}
protected abstract int getOpenWireVersion();
protected abstract boolean isTightEncodingEnabled();
protected void connect() throws Exception {
connected = new CountDownLatch(1);
transport = new TcpTransport(wireFormat, connectionURI);
transport.setTransportListener(this);
transport.start();
transport.oneway(wireFormat.getPreferedWireFormatInfo());
}
protected void disconnect() throws Exception {
if (transport != null && transport.isStarted()) {
ShutdownInfo done = new ShutdownInfo();
transport.oneway(done);
Thread.sleep(50);
transport.stop();
}
}
protected boolean request(Command command, long timeout, TimeUnit units) throws Exception {
command.setCommandId(requestIdGenerator.getAndIncrement());
command.setResponseRequired(true);
CountDownLatch complete = new CountDownLatch(1);
requestMap.put(new Integer(command.getCommandId()), complete);
transport.oneway(command);
return complete.await(timeout, units);
}
protected boolean awaitConnected(long time, TimeUnit unit) throws InterruptedException {
return connected.await(time, unit);
}
protected BrokerService createBroker() throws Exception {
BrokerService brokerService = new BrokerService();
brokerService.setPersistent(false);
brokerService.setAdvisorySupport(false);
brokerService.setDeleteAllMessagesOnStartup(true);
brokerService.setUseJmx(true);
TransportConnector connector = brokerService.addConnector("tcp://0.0.0.0:0?transport.trace=true&trace=true");
connectionURI = connector.getPublishableConnectURI();
LOG.debug("Using openwire port: {}", connectionURI);
return brokerService;
}
@Override
public void onCommand(Object command) {
try {
if (command instanceof WireFormatInfo) {
handleWireFormatInfo((WireFormatInfo) command);
} else if (command instanceof KeepAliveInfo) {
handleKeepAliveInfo((KeepAliveInfo) command);
} else if (command instanceof BrokerInfo) {
handleBrokerInfo((BrokerInfo) command);
} else if (command instanceof Response) {
Response response = (Response) command;
this.latest = response;
LOG.info("Received response for request: {}, response = {}", response.getCorrelationId(), latest);
CountDownLatch done = requestMap.get(response.getCorrelationId());
if (done != null) {
done.countDown();
}
} else if (command instanceof MessageDispatch) {
LOG.info("Received new MessageDispatch: {}", command);
MessageDispatch dispatch = (MessageDispatch) command;
messages.add(dispatch.getMessage());
} else {
LOG.info("Received unknown command: {}", command);
}
} catch (Exception e) {
failureCause = e;
}
}
@Override
public void onException(IOException error) {
failureCause = error;
}
@Override
public void transportInterupted() {
}
@Override
public void transportResumed() {
}
public WireFormatInfo getRemoteWireFormatInfo() {
return this.remoteWireformatInfo;
}
public BrokerInfo getRemoteBrokerInfo() {
return this.remoteInfo;
}
public Command getLastCommandReceived() {
return this.latest;
}
public boolean isFailed() {
return this.failureCause != null;
}
protected void handleWireFormatInfo(WireFormatInfo info) throws Exception {
LOG.info("Received remote WireFormatInfo: {}", info);
this.remoteWireformatInfo = info;
if (LOG.isDebugEnabled()) {
LOG.debug(this + " before negotiation: " + wireFormat);
}
if (!info.isValid()) {
onException(new IOException("Remote wire format magic is invalid"));
} else if (info.getVersion() < getOpenWireVersion()) {
onException(new IOException("Remote wire format (" + info.getVersion() +
") is lower the minimum version required (" + getOpenWireVersion() + ")"));
}
wireFormat.renegotiateWireFormat(info);
if (LOG.isDebugEnabled()) {
LOG.debug(this + " after negotiation: " + wireFormat);
}
connected.countDown();
}
protected void handleKeepAliveInfo(KeepAliveInfo info) throws Exception {
LOG.info("Received remote KeepAliveInfo: {}", info);
if (info.isResponseRequired()) {
KeepAliveInfo response = new KeepAliveInfo();
transport.oneway(response);
}
}
protected void handleBrokerInfo(BrokerInfo info) throws Exception {
LOG.info("Received remote BrokerInfo: {}", info);
this.remoteInfo = info;
}
protected QueueViewMBean getProxyToQueue(String name) throws MalformedObjectNameException, JMSException {
ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName="+name);
QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext()
.newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
return proxy;
}
protected QueueViewMBean getProxyToTopic(String name) throws MalformedObjectNameException, JMSException {
ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Topic,destinationName="+name);
QueueViewMBean proxy = (QueueViewMBean) brokerService.getManagementContext()
.newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
return proxy;
}
}
| 669 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/MessageCompressionTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import javax.jms.BytesMessage;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.openwire.commands.ConnectionInfo;
import org.apache.activemq.openwire.commands.ConsumerInfo;
import org.apache.activemq.openwire.commands.Message;
import org.apache.activemq.openwire.commands.MessageAck;
import org.apache.activemq.openwire.commands.OpenWireBytesMessage;
import org.apache.activemq.openwire.commands.OpenWireQueue;
import org.apache.activemq.openwire.commands.OpenWireTextMessage;
import org.apache.activemq.openwire.commands.ProducerInfo;
import org.apache.activemq.openwire.util.Wait;
import org.apache.activemq.openwire.utils.OpenWireConnection;
import org.apache.activemq.openwire.utils.OpenWireConsumer;
import org.apache.activemq.openwire.utils.OpenWireProducer;
import org.apache.activemq.openwire.utils.OpenWireSession;
import org.junit.Test;
public class MessageCompressionTest extends OpenWireInteropTestSupport {
// The following text should compress well
private static final String TEXT = "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. "
+ "The quick red fox jumped over the lazy brown dog. " + "The quick red fox jumped over the lazy brown dog. ";
public OpenWireQueue getOpenWireQueue() {
return new OpenWireQueue(name.getMethodName());
}
public Queue getActiveMQQueue() {
return new ActiveMQQueue(name.getMethodName());
}
@Test
public void testTextMessageCompressionActiveMQ() throws Exception {
sendAMQTextMessage(TEXT);
ActiveMQTextMessage message = receiveAMQTextMessage();
int compressedSize = message.getContent().getLength();
sendAMQTextMessage(TEXT, false);
message = receiveAMQTextMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testOpenWireTextMessageCompression() throws Exception {
sendOpenWireTextMessage(TEXT);
OpenWireTextMessage message = receiveOpenWireTextMessage();
int compressedSize = message.getContent().getLength();
sendOpenWireTextMessage(TEXT, false);
message = receiveOpenWireTextMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testTextMessageCompressionActiveMQtoOpenWire() throws Exception {
sendAMQTextMessage(TEXT);
OpenWireTextMessage message = receiveOpenWireTextMessage();
int compressedSize = message.getContent().getLength();
sendAMQTextMessage(TEXT, false);
message = receiveOpenWireTextMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testTextMessageCompressionOpenWireToActiveMQ() throws Exception {
sendOpenWireTextMessage(TEXT);
ActiveMQTextMessage message = receiveAMQTextMessage();
int compressedSize = message.getContent().getLength();
sendOpenWireTextMessage(TEXT, false);
message = receiveAMQTextMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testBytesMessageCompressionActiveMQ() throws Exception {
sendAMQBytesMessage(TEXT);
ActiveMQBytesMessage message = receiveAMQBytesMessage();
int compressedSize = message.getContent().getLength();
byte[] bytes = new byte[TEXT.getBytes("UTF8").length];
message.readBytes(bytes);
assertTrue(message.readBytes(new byte[255]) == -1);
String rcvString = new String(bytes, "UTF8");
assertEquals(TEXT, rcvString);
assertTrue(message.isCompressed());
sendAMQBytesMessage(TEXT, false);
message = receiveAMQBytesMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testBytesMessageCompressionOpenWire() throws Exception {
sendOpenWireBytesMessage(TEXT);
OpenWireBytesMessage message = receiveOpenWireBytesMessage();
int compressedSize = message.getContent().getLength();
byte[] bytes = message.getBodyBytes();
String rcvString = new String(bytes, "UTF8");
assertEquals(TEXT, rcvString);
assertTrue(message.isCompressed());
sendOpenWireBytesMessage(TEXT, false);
message = receiveOpenWireBytesMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testBytesMessageCompressionActiveMQtoOpenWire() throws Exception {
sendAMQBytesMessage(TEXT);
OpenWireBytesMessage message = receiveOpenWireBytesMessage();
int compressedSize = message.getContent().getLength();
byte[] bytes = message.getBodyBytes();
String rcvString = new String(bytes, "UTF8");
assertEquals(TEXT, rcvString);
assertTrue(message.isCompressed());
sendAMQBytesMessage(TEXT, false);
message = receiveOpenWireBytesMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
@Test
public void testBytesMessageCompressionOpenWiretoActiveMQ() throws Exception {
sendAMQBytesMessage(TEXT);
OpenWireBytesMessage message = receiveOpenWireBytesMessage();
int compressedSize = message.getContent().getLength();
byte[] bytes = message.getBodyBytes();
String rcvString = new String(bytes, "UTF8");
assertEquals(TEXT, rcvString);
assertTrue(message.isCompressed());
sendAMQBytesMessage(TEXT, false);
message = receiveOpenWireBytesMessage();
int unCompressedSize = message.getContent().getLength();
assertTrue("expected: compressed Size '" + compressedSize + "' < unCompressedSize '" + unCompressedSize + "'",
compressedSize < unCompressedSize);
}
//---------- Sends and Receives Message Via ActiveMQ Objects -------------//
private void sendAMQTextMessage(String message) throws Exception {
sendAMQTextMessage(TEXT, true);
}
private void sendAMQTextMessage(String message, boolean useCompression) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
factory.setUseCompression(useCompression);
ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(getActiveMQQueue());
producer.send(session.createTextMessage(message));
connection.close();
}
private ActiveMQTextMessage receiveAMQTextMessage() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(getActiveMQQueue());
ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive();
connection.close();
return rc;
}
private void sendAMQBytesMessage(String message) throws Exception {
sendAMQBytesMessage(TEXT, true);
}
private void sendAMQBytesMessage(String message, boolean useCompression) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
factory.setUseCompression(useCompression);
ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(getActiveMQQueue());
BytesMessage bytesMessage = session.createBytesMessage();
bytesMessage.writeBytes(message.getBytes("UTF8"));
producer.send(bytesMessage);
connection.close();
}
private ActiveMQBytesMessage receiveAMQBytesMessage() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(getActiveMQQueue());
ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive();
connection.close();
return rc;
}
//---------- Send and Receive OpenWire Messages --------------------------//
private void sendOpenWireTextMessage(String payload) throws Exception {
sendOpenWireTextMessage(payload, true);
}
private void sendOpenWireTextMessage(String payload, boolean useCompression) throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
OpenWireConnection connection = new OpenWireConnection();
ConnectionInfo connectionInfo = connection.createConnectionInfo();
connectionInfo.setClientId(name.getMethodName());
assertTrue(request(connectionInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connection.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireProducer producerId = sessionId.createOpenWireProducer();
ProducerInfo info = producerId.createProducerInfo(getOpenWireQueue());
info.setDispatchAsync(false);
assertTrue(request(info, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueProducers().length);
OpenWireTextMessage message = new OpenWireTextMessage();
message.setUseCompression(useCompression);
message.setText(payload);
message.setTimestamp(System.currentTimeMillis());
message.setMessageId(producerId.getNextMessageId());
message.setProducerId(producerId.getProducerId());
message.setDestination(getOpenWireQueue());
message.onSend();
assertTrue(request(message, 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
assertTrue(request(connection.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getCurrentConnectionsCount());
disconnect();
}
private void sendOpenWireBytesMessage(String payload) throws Exception {
sendOpenWireBytesMessage(payload, true);
}
private void sendOpenWireBytesMessage(String payload, boolean useCompression) throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
OpenWireConnection connection = new OpenWireConnection();
ConnectionInfo connectionInfo = connection.createConnectionInfo();
connectionInfo.setClientId(name.getMethodName());
assertTrue(request(connectionInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connection.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
OpenWireProducer producerId = sessionId.createOpenWireProducer();
ProducerInfo info = producerId.createProducerInfo(getOpenWireQueue());
info.setDispatchAsync(false);
assertTrue(request(info, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueProducers().length);
OpenWireBytesMessage message = new OpenWireBytesMessage();
message.setUseCompression(useCompression);
message.setBodyBytes(payload.getBytes("UTF8"));
message.setTimestamp(System.currentTimeMillis());
message.setMessageId(producerId.getNextMessageId());
message.setProducerId(producerId.getProducerId());
message.setDestination(getOpenWireQueue());
message.onSend();
assertTrue(request(message, 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
assertTrue(request(connection.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getCurrentConnectionsCount());
disconnect();
}
public OpenWireTextMessage receiveOpenWireTextMessage() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
OpenWireConnection connection = new OpenWireConnection();
ConnectionInfo connectionInfo = connection.createConnectionInfo();
connectionInfo.setClientId(name.getMethodName());
assertTrue(request(connectionInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connection.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
OpenWireConsumer consumerId = sessionId.createOpenWireConsumer();
ConsumerInfo consumerInfo = consumerId.createConsumerInfo(getOpenWireQueue());
consumerInfo.setDispatchAsync(false);
consumerInfo.setPrefetchSize(1);
assertTrue(request(consumerInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueSubscribers().length);
assertTrue("Should have received a message", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
return messages.size() == 1;
}
}));
Message incoming = messages.poll();
assertTrue(incoming instanceof OpenWireTextMessage);
OpenWireTextMessage received = (OpenWireTextMessage) incoming;
MessageAck ack = new MessageAck();
ack.setAckType(MessageAck.STANDARD_ACK_TYPE);
ack.setConsumerId(consumerId.getConsumerId());
ack.setDestination(getOpenWireQueue());
ack.setLastMessageId(received.getMessageId());
ack.setMessageCount(1);
assertTrue(request(ack, 60, TimeUnit.SECONDS));
assertEquals(0, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
assertTrue(request(connection.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getCurrentConnectionsCount());
disconnect();
return received;
}
public OpenWireBytesMessage receiveOpenWireBytesMessage() throws Exception {
connect();
assertTrue(awaitConnected(10, TimeUnit.SECONDS));
OpenWireConnection connection = new OpenWireConnection();
ConnectionInfo connectionInfo = connection.createConnectionInfo();
connectionInfo.setClientId(name.getMethodName());
assertTrue(request(connectionInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getCurrentConnectionsCount());
OpenWireSession sessionId = connection.createOpenWireSession();
assertTrue(request(sessionId.createSessionInfo(), 10, TimeUnit.SECONDS));
assertEquals(1, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
OpenWireConsumer consumerId = sessionId.createOpenWireConsumer();
ConsumerInfo consumerInfo = consumerId.createConsumerInfo(getOpenWireQueue());
consumerInfo.setDispatchAsync(false);
consumerInfo.setPrefetchSize(1);
assertTrue(request(consumerInfo, 10, TimeUnit.SECONDS));
assertEquals(1, brokerService.getAdminView().getQueueSubscribers().length);
assertTrue("Should have received a message", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
return messages.size() == 1;
}
}));
Message incoming = messages.poll();
assertTrue(incoming instanceof OpenWireBytesMessage);
OpenWireBytesMessage received = (OpenWireBytesMessage) incoming;
MessageAck ack = new MessageAck();
ack.setAckType(MessageAck.STANDARD_ACK_TYPE);
ack.setConsumerId(consumerId.getConsumerId());
ack.setDestination(getOpenWireQueue());
ack.setLastMessageId(received.getMessageId());
ack.setMessageCount(1);
assertTrue(request(ack, 60, TimeUnit.SECONDS));
assertEquals(0, getProxyToQueue(getOpenWireQueue().getPhysicalName()).getQueueSize());
assertTrue(request(connection.createRemoveInfo(), 10, TimeUnit.SECONDS));
assertEquals(0, brokerService.getAdminView().getCurrentConnectionsCount());
disconnect();
return received;
}
@Override
protected int getOpenWireVersion() {
return 10;
}
@Override
protected boolean isTightEncodingEnabled() {
return false;
}
}
| 670 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v6/OpenWireV6Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV6Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV6Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 6;
}
}
| 671 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v6/WireFormatInfoV6MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV6MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 6;
}
}
| 672 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v1/WireFormatInfoV1MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v1;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV1MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 1;
}
}
| 673 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v1/OpenWireV1Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v1;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV1Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV1Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 1;
}
}
| 674 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v8/WireFormatInfoV8MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v8;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV8MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 8;
}
}
| 675 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v8/OpenWireV8Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v8;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV8Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV8Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 8;
}
}
| 676 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v9/WireFormatInfoV9MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v9;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV9MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 9;
}
}
| 677 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v9/OpenWireV9Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v9;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV9Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV9Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 9;
}
}
| 678 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v7/OpenWireV7Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v7;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV7Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV7Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 7;
}
}
| 679 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v7/WireFormatInfoV7MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v7;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV7MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 7;
}
}
| 680 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v2/WireFormatInfoV2MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v2;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV2MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 2;
}
}
| 681 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v2/OpenWireV2Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v2;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV2Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV2Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 2;
}
}
| 682 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v5/WireFormatInfoV5MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v5;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV5MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 5;
}
}
| 683 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v5/OpenWireV5Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v5;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV5Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV5Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 5;
}
}
| 684 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v4/OpenWireV4Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v4;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV4Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV4Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 4;
}
}
| 685 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v4/WireFormatInfoV4MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v4;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV4MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 4;
}
}
| 686 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v3/WireFormatInfoV3MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v3;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV3MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 3;
}
}
| 687 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v3/OpenWireV3Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v3;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV3Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV3Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 3;
}
}
| 688 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v11/OpenWireV11Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v11;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV11Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV11Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 11;
}
}
| 689 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v11/WireFormatInfoV11MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v11;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV11MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 11;
}
}
| 690 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v10/OpenWireV10Test.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v10;
import org.apache.activemq.openwire.codec.OpenWireInteropTests;
public class OpenWireV10Test extends OpenWireInteropTests {
/**
* @param tightEncodingEnabled
*/
public OpenWireV10Test(boolean tightEncodingEnabled) {
super(tightEncodingEnabled);
}
@Override
protected int getOpenWireVersion() {
return 10;
}
}
| 691 |
0 | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-interop-tests/src/test/java/org/apache/activemq/openwire/codec/v10/WireFormatInfoV10MarshaledSizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v10;
import org.apache.activemq.openwire.codec.WireFormatInfoMarshaledSizeTest;
/**
* Test marshaling with WireFormatInfo for this Version.
*/
public class WireFormatInfoV10MarshaledSizeTest extends WireFormatInfoMarshaledSizeTest {
@Override
public int getVersion() {
return 10;
}
}
| 692 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/SessionInfoMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.SessionId;
import org.apache.activemq.openwire.commands.SessionInfo;
public class SessionInfoMarshaller extends BaseCommandMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return SessionInfo.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new SessionInfo();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
SessionInfo info = (SessionInfo) o;
info.setSessionId((SessionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
SessionInfo info = (SessionInfo) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalCachedObject1(wireFormat, info.getSessionId(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
SessionInfo info = (SessionInfo) o;
tightMarshalCachedObject2(wireFormat, info.getSessionId(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
SessionInfo info = (SessionInfo) o;
info.setSessionId((SessionId) looseUnmarsalCachedObject(wireFormat, dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
SessionInfo info = (SessionInfo) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalCachedObject(wireFormat, info.getSessionId(), dataOut);
}
}
| 693 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/BrokerInfoMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.BrokerId;
import org.apache.activemq.openwire.commands.BrokerInfo;
import org.apache.activemq.openwire.commands.DataStructure;
public class BrokerInfoMarshaller extends BaseCommandMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return BrokerInfo.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new BrokerInfo();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
BrokerInfo info = (BrokerInfo) o;
info.setBrokerId((BrokerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs));
info.setBrokerURL(tightUnmarshalString(dataIn, bs));
if (bs.readBoolean()) {
short size = dataIn.readShort();
BrokerInfo value[] = new BrokerInfo[size];
for (int i = 0; i < size; i++) {
value[i] = (BrokerInfo) tightUnmarsalNestedObject(wireFormat, dataIn, bs);
}
info.setPeerBrokerInfos(value);
} else {
info.setPeerBrokerInfos(null);
}
info.setBrokerName(tightUnmarshalString(dataIn, bs));
info.setSlaveBroker(bs.readBoolean());
info.setMasterBroker(bs.readBoolean());
info.setFaultTolerantConfiguration(bs.readBoolean());
info.setDuplexConnection(bs.readBoolean());
info.setNetworkConnection(bs.readBoolean());
info.setConnectionId(tightUnmarshalLong(wireFormat, dataIn, bs));
info.setBrokerUploadUrl(tightUnmarshalString(dataIn, bs));
info.setNetworkProperties(tightUnmarshalString(dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
BrokerInfo info = (BrokerInfo) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalCachedObject1(wireFormat, info.getBrokerId(), bs);
rc += tightMarshalString1(info.getBrokerURL(), bs);
rc += tightMarshalObjectArray1(wireFormat, info.getPeerBrokerInfos(), bs);
rc += tightMarshalString1(info.getBrokerName(), bs);
bs.writeBoolean(info.isSlaveBroker());
bs.writeBoolean(info.isMasterBroker());
bs.writeBoolean(info.isFaultTolerantConfiguration());
bs.writeBoolean(info.isDuplexConnection());
bs.writeBoolean(info.isNetworkConnection());
rc += tightMarshalLong1(wireFormat, info.getConnectionId(), bs);
rc += tightMarshalString1(info.getBrokerUploadUrl(), bs);
rc += tightMarshalString1(info.getNetworkProperties(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
BrokerInfo info = (BrokerInfo) o;
tightMarshalCachedObject2(wireFormat, info.getBrokerId(), dataOut, bs);
tightMarshalString2(info.getBrokerURL(), dataOut, bs);
tightMarshalObjectArray2(wireFormat, info.getPeerBrokerInfos(), dataOut, bs);
tightMarshalString2(info.getBrokerName(), dataOut, bs);
bs.readBoolean();
bs.readBoolean();
bs.readBoolean();
bs.readBoolean();
bs.readBoolean();
tightMarshalLong2(wireFormat, info.getConnectionId(), dataOut, bs);
tightMarshalString2(info.getBrokerUploadUrl(), dataOut, bs);
tightMarshalString2(info.getNetworkProperties(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
BrokerInfo info = (BrokerInfo) o;
info.setBrokerId((BrokerId) looseUnmarsalCachedObject(wireFormat, dataIn));
info.setBrokerURL(looseUnmarshalString(dataIn));
if (dataIn.readBoolean()) {
short size = dataIn.readShort();
BrokerInfo value[] = new BrokerInfo[size];
for (int i = 0; i < size; i++) {
value[i] = (BrokerInfo) looseUnmarsalNestedObject(wireFormat, dataIn);
}
info.setPeerBrokerInfos(value);
} else {
info.setPeerBrokerInfos(null);
}
info.setBrokerName(looseUnmarshalString(dataIn));
info.setSlaveBroker(dataIn.readBoolean());
info.setMasterBroker(dataIn.readBoolean());
info.setFaultTolerantConfiguration(dataIn.readBoolean());
info.setDuplexConnection(dataIn.readBoolean());
info.setNetworkConnection(dataIn.readBoolean());
info.setConnectionId(looseUnmarshalLong(wireFormat, dataIn));
info.setBrokerUploadUrl(looseUnmarshalString(dataIn));
info.setNetworkProperties(looseUnmarshalString(dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
BrokerInfo info = (BrokerInfo) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalCachedObject(wireFormat, info.getBrokerId(), dataOut);
looseMarshalString(info.getBrokerURL(), dataOut);
looseMarshalObjectArray(wireFormat, info.getPeerBrokerInfos(), dataOut);
looseMarshalString(info.getBrokerName(), dataOut);
dataOut.writeBoolean(info.isSlaveBroker());
dataOut.writeBoolean(info.isMasterBroker());
dataOut.writeBoolean(info.isFaultTolerantConfiguration());
dataOut.writeBoolean(info.isDuplexConnection());
dataOut.writeBoolean(info.isNetworkConnection());
looseMarshalLong(wireFormat, info.getConnectionId(), dataOut);
looseMarshalString(info.getBrokerUploadUrl(), dataOut);
looseMarshalString(info.getNetworkProperties(), dataOut);
}
}
| 694 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/OpenWireMapMessageMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.OpenWireMapMessage;
public class OpenWireMapMessageMarshaller extends OpenWireMessageMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return OpenWireMapMessage.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new OpenWireMapMessage();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
int rc = super.tightMarshal1(wireFormat, o, bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
}
}
| 695 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/MessageAckMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.ConsumerId;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.MessageAck;
import org.apache.activemq.openwire.commands.MessageId;
import org.apache.activemq.openwire.commands.OpenWireDestination;
import org.apache.activemq.openwire.commands.TransactionId;
public class MessageAckMarshaller extends BaseCommandMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return MessageAck.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new MessageAck();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
MessageAck info = (MessageAck) o;
info.setDestination((OpenWireDestination) tightUnmarsalCachedObject(wireFormat, dataIn, bs));
info.setTransactionId((TransactionId) tightUnmarsalCachedObject(wireFormat, dataIn, bs));
info.setConsumerId((ConsumerId) tightUnmarsalCachedObject(wireFormat, dataIn, bs));
info.setAckType(dataIn.readByte());
info.setFirstMessageId((MessageId) tightUnmarsalNestedObject(wireFormat, dataIn, bs));
info.setLastMessageId((MessageId) tightUnmarsalNestedObject(wireFormat, dataIn, bs));
info.setMessageCount(dataIn.readInt());
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
MessageAck info = (MessageAck) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalCachedObject1(wireFormat, info.getDestination(), bs);
rc += tightMarshalCachedObject1(wireFormat, info.getTransactionId(), bs);
rc += tightMarshalCachedObject1(wireFormat, info.getConsumerId(), bs);
rc += tightMarshalNestedObject1(wireFormat, info.getFirstMessageId(), bs);
rc += tightMarshalNestedObject1(wireFormat, info.getLastMessageId(), bs);
return rc + 5;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
MessageAck info = (MessageAck) o;
tightMarshalCachedObject2(wireFormat, info.getDestination(), dataOut, bs);
tightMarshalCachedObject2(wireFormat, info.getTransactionId(), dataOut, bs);
tightMarshalCachedObject2(wireFormat, info.getConsumerId(), dataOut, bs);
dataOut.writeByte(info.getAckType());
tightMarshalNestedObject2(wireFormat, info.getFirstMessageId(), dataOut, bs);
tightMarshalNestedObject2(wireFormat, info.getLastMessageId(), dataOut, bs);
dataOut.writeInt(info.getMessageCount());
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
MessageAck info = (MessageAck) o;
info.setDestination((OpenWireDestination) looseUnmarsalCachedObject(wireFormat, dataIn));
info.setTransactionId((TransactionId) looseUnmarsalCachedObject(wireFormat, dataIn));
info.setConsumerId((ConsumerId) looseUnmarsalCachedObject(wireFormat, dataIn));
info.setAckType(dataIn.readByte());
info.setFirstMessageId((MessageId) looseUnmarsalNestedObject(wireFormat, dataIn));
info.setLastMessageId((MessageId) looseUnmarsalNestedObject(wireFormat, dataIn));
info.setMessageCount(dataIn.readInt());
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
MessageAck info = (MessageAck) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalCachedObject(wireFormat, info.getDestination(), dataOut);
looseMarshalCachedObject(wireFormat, info.getTransactionId(), dataOut);
looseMarshalCachedObject(wireFormat, info.getConsumerId(), dataOut);
dataOut.writeByte(info.getAckType());
looseMarshalNestedObject(wireFormat, info.getFirstMessageId(), dataOut);
looseMarshalNestedObject(wireFormat, info.getLastMessageId(), dataOut);
dataOut.writeInt(info.getMessageCount());
}
}
| 696 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/OpenWireTempQueueMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.OpenWireTempQueue;
public class OpenWireTempQueueMarshaller extends OpenWireTempDestinationMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return OpenWireTempQueue.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new OpenWireTempQueue();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
int rc = super.tightMarshal1(wireFormat, o, bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
super.looseMarshal(wireFormat, o, dataOut);
}
}
| 697 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/ExceptionResponseMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.DataStructure;
import org.apache.activemq.openwire.commands.ExceptionResponse;
public class ExceptionResponseMarshaller extends ResponseMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return ExceptionResponse.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new ExceptionResponse();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
ExceptionResponse info = (ExceptionResponse) o;
info.setException(tightUnmarsalThrowable(wireFormat, dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
ExceptionResponse info = (ExceptionResponse) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalThrowable1(wireFormat, info.getException(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
ExceptionResponse info = (ExceptionResponse) o;
tightMarshalThrowable2(wireFormat, info.getException(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
ExceptionResponse info = (ExceptionResponse) o;
info.setException(looseUnmarsalThrowable(wireFormat, dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
ExceptionResponse info = (ExceptionResponse) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalThrowable(wireFormat, info.getException(), dataOut);
}
}
| 698 |
0 | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec | Create_ds/activemq-openwire/openwire-legacy/src/main/java/org/apache/activemq/openwire/codec/v6/BrokerIdMarshaller.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.openwire.codec.v6;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.activemq.openwire.codec.BaseDataStreamMarshaller;
import org.apache.activemq.openwire.codec.BooleanStream;
import org.apache.activemq.openwire.codec.OpenWireFormat;
import org.apache.activemq.openwire.commands.BrokerId;
import org.apache.activemq.openwire.commands.DataStructure;
public class BrokerIdMarshaller extends BaseDataStreamMarshaller {
/**
* Return the type of Data Structure we marshal
*
* @return short representation of the type data structure
*/
@Override
public byte getDataStructureType() {
return BrokerId.DATA_STRUCTURE_TYPE;
}
/**
* @return a new object instance
*/
@Override
public DataStructure createObject() {
return new BrokerId();
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void tightUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn, BooleanStream bs) throws IOException {
super.tightUnmarshal(wireFormat, o, dataIn, bs);
BrokerId info = (BrokerId) o;
info.setValue(tightUnmarshalString(dataIn, bs));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public int tightMarshal1(OpenWireFormat wireFormat, Object o, BooleanStream bs) throws IOException {
BrokerId info = (BrokerId) o;
int rc = super.tightMarshal1(wireFormat, o, bs);
rc += tightMarshalString1(info.getValue(), bs);
return rc + 0;
}
/**
* Write a object instance to data output stream
*
* @param o
* the instance to be marshaled
* @param dataOut
* the output stream
* @throws IOException
* thrown if an error occurs
*/
@Override
public void tightMarshal2(OpenWireFormat wireFormat, Object o, DataOutput dataOut, BooleanStream bs) throws IOException {
super.tightMarshal2(wireFormat, o, dataOut, bs);
BrokerId info = (BrokerId) o;
tightMarshalString2(info.getValue(), dataOut, bs);
}
/**
* Un-marshal an object instance from the data input stream
*
* @param o
* the object to un-marshal
* @param dataIn
* the data input stream to build the object from
* @throws IOException
*/
@Override
public void looseUnmarshal(OpenWireFormat wireFormat, Object o, DataInput dataIn) throws IOException {
super.looseUnmarshal(wireFormat, o, dataIn);
BrokerId info = (BrokerId) o;
info.setValue(looseUnmarshalString(dataIn));
}
/**
* Write the booleans that this object uses to a BooleanStream
*/
@Override
public void looseMarshal(OpenWireFormat wireFormat, Object o, DataOutput dataOut) throws IOException {
BrokerId info = (BrokerId) o;
super.looseMarshal(wireFormat, o, dataOut);
looseMarshalString(info.getValue(), dataOut);
}
}
| 699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.