Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2017-02-02 21:12:43 -06:00
commit 917d7eac95
94 changed files with 6894 additions and 349 deletions

3
.gitignore vendored
View File

@ -27,4 +27,5 @@ target/
spring-openid/src/main/resources/application.properties spring-openid/src/main/resources/application.properties
.recommenders/ .recommenders/
/spring-hibernate4/nbproject/ /spring-hibernate4/nbproject/
spring-security-openid/src/main/resources/application.properties

View File

@ -0,0 +1,579 @@
/**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.baeldung.thrift.impl;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
public class CrossPlatformResource implements org.apache.thrift.TBase<CrossPlatformResource, CrossPlatformResource._Fields>, java.io.Serializable, Cloneable, Comparable<CrossPlatformResource> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("CrossPlatformResource");
private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField SALUTATION_FIELD_DESC = new org.apache.thrift.protocol.TField("salutation", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new CrossPlatformResourceStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new CrossPlatformResourceTupleSchemeFactory();
public int id; // required
public java.lang.String name; // required
public java.lang.String salutation; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
ID((short)1, "id"),
NAME((short)2, "name"),
SALUTATION((short)3, "salutation");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // ID
return ID;
case 2: // NAME
return NAME;
case 3: // SALUTATION
return SALUTATION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __ID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.SALUTATION};
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.SALUTATION, new org.apache.thrift.meta_data.FieldMetaData("salutation", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(CrossPlatformResource.class, metaDataMap);
}
public CrossPlatformResource() {
}
public CrossPlatformResource(
int id,
java.lang.String name)
{
this();
this.id = id;
setIdIsSet(true);
this.name = name;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public CrossPlatformResource(CrossPlatformResource other) {
__isset_bitfield = other.__isset_bitfield;
this.id = other.id;
if (other.isSetName()) {
this.name = other.name;
}
if (other.isSetSalutation()) {
this.salutation = other.salutation;
}
}
public CrossPlatformResource deepCopy() {
return new CrossPlatformResource(this);
}
@Override
public void clear() {
setIdIsSet(false);
this.id = 0;
this.name = null;
this.salutation = null;
}
public int getId() {
return this.id;
}
public CrossPlatformResource setId(int id) {
this.id = id;
setIdIsSet(true);
return this;
}
public void unsetId() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID);
}
/** Returns true if field id is set (has been assigned a value) and false otherwise */
public boolean isSetId() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID);
}
public void setIdIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value);
}
public java.lang.String getName() {
return this.name;
}
public CrossPlatformResource setName(java.lang.String name) {
this.name = name;
return this;
}
public void unsetName() {
this.name = null;
}
/** Returns true if field name is set (has been assigned a value) and false otherwise */
public boolean isSetName() {
return this.name != null;
}
public void setNameIsSet(boolean value) {
if (!value) {
this.name = null;
}
}
public java.lang.String getSalutation() {
return this.salutation;
}
public CrossPlatformResource setSalutation(java.lang.String salutation) {
this.salutation = salutation;
return this;
}
public void unsetSalutation() {
this.salutation = null;
}
/** Returns true if field salutation is set (has been assigned a value) and false otherwise */
public boolean isSetSalutation() {
return this.salutation != null;
}
public void setSalutationIsSet(boolean value) {
if (!value) {
this.salutation = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case ID:
if (value == null) {
unsetId();
} else {
setId((java.lang.Integer)value);
}
break;
case NAME:
if (value == null) {
unsetName();
} else {
setName((java.lang.String)value);
}
break;
case SALUTATION:
if (value == null) {
unsetSalutation();
} else {
setSalutation((java.lang.String)value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case ID:
return getId();
case NAME:
return getName();
case SALUTATION:
return getSalutation();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case ID:
return isSetId();
case NAME:
return isSetName();
case SALUTATION:
return isSetSalutation();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof CrossPlatformResource)
return this.equals((CrossPlatformResource)that);
return false;
}
public boolean equals(CrossPlatformResource that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_id = true;
boolean that_present_id = true;
if (this_present_id || that_present_id) {
if (!(this_present_id && that_present_id))
return false;
if (this.id != that.id)
return false;
}
boolean this_present_name = true && this.isSetName();
boolean that_present_name = true && that.isSetName();
if (this_present_name || that_present_name) {
if (!(this_present_name && that_present_name))
return false;
if (!this.name.equals(that.name))
return false;
}
boolean this_present_salutation = true && this.isSetSalutation();
boolean that_present_salutation = true && that.isSetSalutation();
if (this_present_salutation || that_present_salutation) {
if (!(this_present_salutation && that_present_salutation))
return false;
if (!this.salutation.equals(that.salutation))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + id;
hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287);
if (isSetName())
hashCode = hashCode * 8191 + name.hashCode();
hashCode = hashCode * 8191 + ((isSetSalutation()) ? 131071 : 524287);
if (isSetSalutation())
hashCode = hashCode * 8191 + salutation.hashCode();
return hashCode;
}
@Override
public int compareTo(CrossPlatformResource other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetId()).compareTo(other.isSetId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetName()).compareTo(other.isSetName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetSalutation()).compareTo(other.isSetSalutation());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSalutation()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.salutation, other.salutation);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("CrossPlatformResource(");
boolean first = true;
sb.append("id:");
sb.append(this.id);
first = false;
if (!first) sb.append(", ");
sb.append("name:");
if (this.name == null) {
sb.append("null");
} else {
sb.append(this.name);
}
first = false;
if (isSetSalutation()) {
if (!first) sb.append(", ");
sb.append("salutation:");
if (this.salutation == null) {
sb.append("null");
} else {
sb.append(this.salutation);
}
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class CrossPlatformResourceStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public CrossPlatformResourceStandardScheme getScheme() {
return new CrossPlatformResourceStandardScheme();
}
}
private static class CrossPlatformResourceStandardScheme extends org.apache.thrift.scheme.StandardScheme<CrossPlatformResource> {
public void read(org.apache.thrift.protocol.TProtocol iprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.id = iprot.readI32();
struct.setIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // SALUTATION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.salutation = iprot.readString();
struct.setSalutationIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, CrossPlatformResource struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(ID_FIELD_DESC);
oprot.writeI32(struct.id);
oprot.writeFieldEnd();
if (struct.name != null) {
oprot.writeFieldBegin(NAME_FIELD_DESC);
oprot.writeString(struct.name);
oprot.writeFieldEnd();
}
if (struct.salutation != null) {
if (struct.isSetSalutation()) {
oprot.writeFieldBegin(SALUTATION_FIELD_DESC);
oprot.writeString(struct.salutation);
oprot.writeFieldEnd();
}
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class CrossPlatformResourceTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public CrossPlatformResourceTupleScheme getScheme() {
return new CrossPlatformResourceTupleScheme();
}
}
private static class CrossPlatformResourceTupleScheme extends org.apache.thrift.scheme.TupleScheme<CrossPlatformResource> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetId()) {
optionals.set(0);
}
if (struct.isSetName()) {
optionals.set(1);
}
if (struct.isSetSalutation()) {
optionals.set(2);
}
oprot.writeBitSet(optionals, 3);
if (struct.isSetId()) {
oprot.writeI32(struct.id);
}
if (struct.isSetName()) {
oprot.writeString(struct.name);
}
if (struct.isSetSalutation()) {
oprot.writeString(struct.salutation);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, CrossPlatformResource struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(3);
if (incoming.get(0)) {
struct.id = iprot.readI32();
struct.setIdIsSet(true);
}
if (incoming.get(1)) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
}
if (incoming.get(2)) {
struct.salutation = iprot.readString();
struct.setSalutationIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,472 @@
/**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.baeldung.thrift.impl;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-02-01")
public class InvalidOperationException extends org.apache.thrift.TException implements org.apache.thrift.TBase<InvalidOperationException, InvalidOperationException._Fields>, java.io.Serializable, Cloneable, Comparable<InvalidOperationException> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("InvalidOperationException");
private static final org.apache.thrift.protocol.TField CODE_FIELD_DESC = new org.apache.thrift.protocol.TField("code", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField DESCRIPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("description", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new InvalidOperationExceptionStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new InvalidOperationExceptionTupleSchemeFactory();
public int code; // required
public java.lang.String description; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
CODE((short)1, "code"),
DESCRIPTION((short)2, "description");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // CODE
return CODE;
case 2: // DESCRIPTION
return DESCRIPTION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __CODE_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.CODE, new org.apache.thrift.meta_data.FieldMetaData("code", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));
tmpMap.put(_Fields.DESCRIPTION, new org.apache.thrift.meta_data.FieldMetaData("description", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(InvalidOperationException.class, metaDataMap);
}
public InvalidOperationException() {
}
public InvalidOperationException(
int code,
java.lang.String description)
{
this();
this.code = code;
setCodeIsSet(true);
this.description = description;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public InvalidOperationException(InvalidOperationException other) {
__isset_bitfield = other.__isset_bitfield;
this.code = other.code;
if (other.isSetDescription()) {
this.description = other.description;
}
}
public InvalidOperationException deepCopy() {
return new InvalidOperationException(this);
}
@Override
public void clear() {
setCodeIsSet(false);
this.code = 0;
this.description = null;
}
public int getCode() {
return this.code;
}
public InvalidOperationException setCode(int code) {
this.code = code;
setCodeIsSet(true);
return this;
}
public void unsetCode() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __CODE_ISSET_ID);
}
/** Returns true if field code is set (has been assigned a value) and false otherwise */
public boolean isSetCode() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __CODE_ISSET_ID);
}
public void setCodeIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __CODE_ISSET_ID, value);
}
public java.lang.String getDescription() {
return this.description;
}
public InvalidOperationException setDescription(java.lang.String description) {
this.description = description;
return this;
}
public void unsetDescription() {
this.description = null;
}
/** Returns true if field description is set (has been assigned a value) and false otherwise */
public boolean isSetDescription() {
return this.description != null;
}
public void setDescriptionIsSet(boolean value) {
if (!value) {
this.description = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case CODE:
if (value == null) {
unsetCode();
} else {
setCode((java.lang.Integer)value);
}
break;
case DESCRIPTION:
if (value == null) {
unsetDescription();
} else {
setDescription((java.lang.String)value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case CODE:
return getCode();
case DESCRIPTION:
return getDescription();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case CODE:
return isSetCode();
case DESCRIPTION:
return isSetDescription();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof InvalidOperationException)
return this.equals((InvalidOperationException)that);
return false;
}
public boolean equals(InvalidOperationException that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_code = true;
boolean that_present_code = true;
if (this_present_code || that_present_code) {
if (!(this_present_code && that_present_code))
return false;
if (this.code != that.code)
return false;
}
boolean this_present_description = true && this.isSetDescription();
boolean that_present_description = true && that.isSetDescription();
if (this_present_description || that_present_description) {
if (!(this_present_description && that_present_description))
return false;
if (!this.description.equals(that.description))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + code;
hashCode = hashCode * 8191 + ((isSetDescription()) ? 131071 : 524287);
if (isSetDescription())
hashCode = hashCode * 8191 + description.hashCode();
return hashCode;
}
@Override
public int compareTo(InvalidOperationException other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetCode()).compareTo(other.isSetCode());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetCode()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.code, other.code);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.valueOf(isSetDescription()).compareTo(other.isSetDescription());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetDescription()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.description, other.description);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("InvalidOperationException(");
boolean first = true;
sb.append("code:");
sb.append(this.code);
first = false;
if (!first) sb.append(", ");
sb.append("description:");
if (this.description == null) {
sb.append("null");
} else {
sb.append(this.description);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class InvalidOperationExceptionStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public InvalidOperationExceptionStandardScheme getScheme() {
return new InvalidOperationExceptionStandardScheme();
}
}
private static class InvalidOperationExceptionStandardScheme extends org.apache.thrift.scheme.StandardScheme<InvalidOperationException> {
public void read(org.apache.thrift.protocol.TProtocol iprot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // CODE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.code = iprot.readI32();
struct.setCodeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // DESCRIPTION
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, InvalidOperationException struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(CODE_FIELD_DESC);
oprot.writeI32(struct.code);
oprot.writeFieldEnd();
if (struct.description != null) {
oprot.writeFieldBegin(DESCRIPTION_FIELD_DESC);
oprot.writeString(struct.description);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class InvalidOperationExceptionTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public InvalidOperationExceptionTupleScheme getScheme() {
return new InvalidOperationExceptionTupleScheme();
}
}
private static class InvalidOperationExceptionTupleScheme extends org.apache.thrift.scheme.TupleScheme<InvalidOperationException> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetCode()) {
optionals.set(0);
}
if (struct.isSetDescription()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetCode()) {
oprot.writeI32(struct.code);
}
if (struct.isSetDescription()) {
oprot.writeString(struct.description);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, InvalidOperationException struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.code = iprot.readI32();
struct.setCodeIsSet(true);
}
if (incoming.get(1)) {
struct.description = iprot.readString();
struct.setDescriptionIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}

68
apache-thrift/pom.xml Normal file
View File

@ -0,0 +1,68 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-thrift</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<java.versin>1.8</java.versin>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<thrift.version>0.10.0</thrift.version>
<maven-thrift.version>0.1.11</maven-thrift.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>${thrift.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<goals><goal>add-source</goal></goals>
<configuration>
<sources>
<source>generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,9 @@
package com.baeldung.thrift;
public class Application {
public static void main(String[] args) {
CrossPlatformServiceServer server = new CrossPlatformServiceServer();
server.start();
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceClient {
public boolean ping() {
try {
TTransport transport;
transport = new TSocket("localhost", 9090);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
CrossPlatformService.Client client = new CrossPlatformService.Client(protocol);
System.out.print("Calling remote method...");
boolean result = client.ping();
System.out.println("done.");
transport.close();
return result;
} catch (TTransportException e) {
e.printStackTrace();
} catch (TException x) {
x.printStackTrace();
}
return false;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformResource;
import com.baeldung.thrift.impl.CrossPlatformService;
import com.baeldung.thrift.impl.InvalidOperationException;
import org.apache.thrift.TException;
import java.util.Collections;
import java.util.List;
public class CrossPlatformServiceImpl implements CrossPlatformService.Iface {
@Override
public CrossPlatformResource get(final int id) throws InvalidOperationException, TException {
// add some action
return new CrossPlatformResource();
}
@Override
public void save(final CrossPlatformResource resource) throws InvalidOperationException, TException {
// add some action
}
@Override
public List<CrossPlatformResource> getList() throws InvalidOperationException, TException {
// add some action
return Collections.emptyList();
}
@Override
public boolean ping() throws InvalidOperationException, TException {
return true;
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.thrift;
import com.baeldung.thrift.impl.CrossPlatformService;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
public class CrossPlatformServiceServer {
private TServer server;
public void start() {
try {
TServerTransport serverTransport = new TServerSocket(9090);
server = new TSimpleServer(new TServer.Args(serverTransport)
.processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl())));
System.out.print("Starting the server... ");
server.serve();
System.out.println("done.");
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop() {
if (server != null && server.isServing()) {
System.out.print("Stopping the server... ");
server.stop();
System.out.println("done.");
}
}
}

View File

@ -0,0 +1,24 @@
namespace cpp com.baeldung.thrift.impl
namespace java com.baeldung.thrift.impl
exception InvalidOperationException {
1: i32 code,
2: string description
}
struct CrossPlatformResource {
1: i32 id,
2: string name,
3: optional string salutation
}
service CrossPlatformService {
CrossPlatformResource get(1:i32 id) throws (1:InvalidOperationException e),
void save(1:CrossPlatformResource resource) throws (1:InvalidOperationException e),
list <CrossPlatformResource> getList() throws (1:InvalidOperationException e),
bool ping() throws (1:InvalidOperationException e)
}

View File

@ -0,0 +1,33 @@
package com.baeldung.thrift;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CrossPlatformServiceTest {
private CrossPlatformServiceServer server = new CrossPlatformServiceServer();
@Before
public void setUp() {
new Thread(() -> server.start()).start();
try {
// wait for the server start up
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() {
server.stop();
}
@Test
public void ping() {
CrossPlatformServiceClient client = new CrossPlatformServiceClient();
Assert.assertTrue(client.ping());
}
}

View File

@ -57,7 +57,6 @@
<configuration> <configuration>
<source>1.9</source> <source>1.9</source>
<target>1.9</target> <target>1.9</target>
<verbose>true</verbose>
</configuration> </configuration>
</plugin> </plugin>
@ -72,6 +71,9 @@
</build> </build>
<properties> <properties>
<!-- project build encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- logging --> <!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version> <org.slf4j.version>1.7.21</org.slf4j.version>

View File

@ -0,0 +1,61 @@
package com.baeldung.java9.language.collections;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class ListFactoryMethodsTest {
@Test
public void whenListCreated_thenSuccess() {
List<String> traditionlList = new ArrayList<String>();
traditionlList.add("foo");
traditionlList.add("bar");
traditionlList.add("baz");
List<String> factoryCreatedList = List.of("foo", "bar", "baz");
assertEquals(traditionlList, factoryCreatedList);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.set(0, "baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
List<String> list = List.of("foo", "bar");
list.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
List.of("foo", "bar", null);
}
@Test
public void ifNotArrayList_thenSuccess() {
List<String> list = List.of("foo", "bar");
assertFalse(list instanceof ArrayList);
}
@Test
public void ifListSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
List<int[]> list = List.of(arr);
assertEquals(1, list.size());
assertArrayEquals(arr, list.get(0));
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.java9.language.collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class MapFactoryMethodsTest {
@Test
public void whenMapCreated_thenSuccess() {
Map<String, String> traditionlMap = new HashMap<String, String>();
traditionlMap.put("foo", "a");
traditionlMap.put("bar", "b");
traditionlMap.put("baz", "c");
Map<String, String> factoryCreatedMap = Map.of("foo", "a", "bar", "b", "baz", "c");
assertEquals(traditionlMap, factoryCreatedMap);
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("baz", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemModify_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.put("foo", "c");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
map.remove("foo");
}
@Test(expected = IllegalArgumentException.class)
public void givenDuplicateKeys_ifIllegalArgExp_thenSuccess() {
Map.of("foo", "a", "foo", "b");
}
@Test(expected = NullPointerException.class)
public void onNullKey_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", null, "b");
}
@Test(expected = NullPointerException.class)
public void onNullValue_ifNullPtrExp_thenSuccess() {
Map.of("foo", "a", "bar", null);
}
@Test
public void ifNotHashMap_thenSuccess() {
Map<String, String> map = Map.of("foo", "a", "bar", "b");
assertFalse(map instanceof HashMap);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.java9.language.collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class SetFactoryMethodsTest {
@Test
public void whenSetCreated_thenSuccess() {
Set<String> traditionlSet = new HashSet<String>();
traditionlSet.add("foo");
traditionlSet.add("bar");
traditionlSet.add("baz");
Set<String> factoryCreatedSet = Set.of("foo", "bar", "baz");
assertEquals(traditionlSet, factoryCreatedSet);
}
@Test(expected = IllegalArgumentException.class)
public void onDuplicateElem_IfIllegalArgExp_thenSuccess() {
Set.of("foo", "bar", "baz", "foo");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemAdd_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar");
set.add("baz");
}
@Test(expected = UnsupportedOperationException.class)
public void onElemRemove_ifUnSupportedOpExpnThrown_thenSuccess() {
Set<String> set = Set.of("foo", "bar", "baz");
set.remove("foo");
}
@Test(expected = NullPointerException.class)
public void onNullElem_ifNullPtrExpnThrown_thenSuccess() {
Set.of("foo", "bar", null);
}
@Test
public void ifNotHashSet_thenSuccess() {
Set<String> list = Set.of("foo", "bar");
assertFalse(list instanceof HashSet);
}
@Test
public void ifSetSizeIsOne_thenSuccess() {
int[] arr = { 1, 2, 3, 4 };
Set<int[]> set = Set.of(arr);
assertEquals(1, set.size());
assertArrayEquals(arr, set.iterator().next());
}
}

View File

@ -54,3 +54,6 @@
- [The Basics of Java Generics](http://www.baeldung.com/java-generics) - [The Basics of Java Generics](http://www.baeldung.com/java-generics)
- [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman) - [The Traveling Salesman Problem in Java](http://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
- [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven) - [How to Create an Executable JAR with Maven](http://www.baeldung.com/executable-jar-with-maven)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)

View File

@ -1,6 +1,5 @@
package com.baeldung.concurrent.future; package com.baeldung.concurrent.future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -13,12 +12,9 @@ public class SquareCalculator {
} }
public Future<Integer> calculate(Integer input) { public Future<Integer> calculate(Integer input) {
return executor.submit(new Callable<Integer>() { return executor.submit(() -> {
@Override Thread.sleep(1000);
public Integer call() throws Exception { return input * input;
Thread.sleep(1000); });
return input * input;
}
});
} }
} }

View File

@ -0,0 +1,62 @@
package com.baeldung;
import static org.junit.Assert.*;
import org.junit.Test;
public class CharArrayToStringUnitTest {
@Test
public void givenCharArray_whenCallingStringConstructor_shouldConvertToString() {
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = new String(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringConstructorWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = new String(charArray, 4, 3);
String expectedValue = "act";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOf_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = String.copyValueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringCopyValueOfWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = String.copyValueOf(charArray, 0, 4);
String expectedValue = "char";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOf_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = String.valueOf(charArray);
String expectedValue = "character";
assertEquals(expectedValue, result);
}
@Test
public void givenCharArray_whenCallingStringValueOfWithOffsetAndLength_shouldConvertToString(){
char[] charArray = {'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r'};
String result = String.valueOf(charArray, 3, 4);
String expectedValue = "ract";
assertEquals(expectedValue, result);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung;
import static org.junit.Assert.*;
import org.junit.Test;
public class StringToCharArrayUnitTest {
@Test
public void givenString_whenCallingStringToCharArray_shouldConvertToCharArray() {
String givenString = "characters";
char[] result = givenString.toCharArray();
char[] expectedCharArray = { 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };
assertArrayEquals(expectedCharArray, result);
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.java.concurrentmap;
import org.junit.Test;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.testng.Assert.*;
public class ConcurrentNavigableMapTests {
@Test
public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException {
NavigableMap<Integer, String> skipListMap = new ConcurrentSkipListMap<>();
updateMapConcurrently(skipListMap, 4);
Iterator<Integer> skipListIter = skipListMap
.keySet()
.iterator();
int previous = skipListIter.next();
while (skipListIter.hasNext()) {
int current = skipListIter.next();
assertTrue(previous < current);
}
}
private void updateMapConcurrently(NavigableMap<Integer, String> navigableMap, int concurrencyLevel) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel);
for (int i = 0; i < concurrencyLevel; i++) {
executorService.execute(() -> {
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int j = 0; j < 10000; j++) {
navigableMap.put(random.nextInt(), "test");
}
});
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
}
@Test
public void givenSkipListMap_whenNavConcurrently_thenCountCorrect() throws InterruptedException {
NavigableMap<Integer, Integer> skipListMap = new ConcurrentSkipListMap<>();
int count = countMapElementByPollingFirstEntry(skipListMap, 10000, 4);
assertEquals(10000 * 4, count);
}
@Test
public void givenTreeMap_whenNavConcurrently_thenCountError() throws InterruptedException {
NavigableMap<Integer, Integer> treeMap = new TreeMap<>();
int count = countMapElementByPollingFirstEntry(treeMap, 10000, 4);
assertNotEquals(10000 * 4, count);
}
private int countMapElementByPollingFirstEntry(NavigableMap<Integer, Integer> navigableMap, int elementCount, int concurrencyLevel) throws InterruptedException {
for (int i = 0; i < elementCount * concurrencyLevel; i++) {
navigableMap.put(i, i);
}
AtomicInteger counter = new AtomicInteger(0);
ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel);
for (int j = 0; j < concurrencyLevel; j++) {
executorService.execute(() -> {
for (int i = 0; i < elementCount; i++) {
if (navigableMap.pollFirstEntry() != null) {
counter.incrementAndGet();
}
}
});
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
return counter.get();
}
}

View File

@ -0,0 +1,41 @@
package org.baeldung.java.streams;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStream {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
throws InterruptedException, ExecutionException {
long firstNum = 1;
long lastNum = 1_000_000;
List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
.collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
.reduce(0L, Long::sum)).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test
public void givenList_whenCallingParallelStream_shouldBeParallelStream(){
List<Long> aList = new ArrayList<>();
Stream<Long> parallelStream = aList.parallelStream();
assertTrue(parallelStream.isParallel());
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung.guava;
public class CustomEvent {
private String action;
public CustomEvent(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.guava;
import com.google.common.eventbus.EventBus;
class EventBusWrapper {
private static EventBus eventBus = new EventBus();
static void register(Object object){
eventBus.register(object);
}
static void unregister(Object object){
eventBus.unregister(object);
}
static void post(Object object){
eventBus.post(object);
}
}

View File

@ -0,0 +1,33 @@
package org.baeldung.guava;
import com.google.common.eventbus.Subscribe;
public class EventListener {
private static int eventsHandled;
/**
* Handles events of type String *
*/
@Subscribe
public void stringEvent(String event){
System.out.println("do event ["+event+"]");
eventsHandled++;
}
/**
* Handles events of type CustomEvent
*/
@Subscribe
public void someEvent(CustomEvent customEvent){
System.out.println("do event ["+ customEvent.getAction()+"]");
eventsHandled++;
}
public int getEventsHandled() {
return eventsHandled;
}
public void resetEventsHandled(){
eventsHandled = 0;
}
}

View File

@ -0,0 +1,42 @@
package org.baeldung.guava;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class GuavaEventBusTest {
private EventListener listener;
@Before
public void setUp() throws Exception {
listener = new EventListener();
EventBusWrapper.register(listener);
}
@After
public void tearDown() throws Exception {
EventBusWrapper.unregister(listener);
}
@Test
public void givenStringEvent_whenEventHandled_thenSuccess() throws Exception {
listener.resetEventsHandled();
EventBusWrapper.post("String Event");
assertEquals(1, listener.getEventsHandled());
}
@Test
public void givenCustomEvent_whenEventHandled_thenSuccess() throws Exception {
listener.resetEventsHandled();
CustomEvent customEvent = new CustomEvent("Custom Event");
EventBusWrapper.post(customEvent);
assertEquals(1, listener.getEventsHandled());
}
}

View File

@ -0,0 +1,91 @@
package org.baeldung.guava;
import com.google.common.base.Function;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class GuavaOrderingTest {
@Test
public void givenListOfIntegers_whenCreateNaturalOrderOrdering_shouldSortProperly() {
//given
List<Integer> integers = Arrays.asList(3, 2, 1);
//when
integers.sort(Ordering.natural());
//then
assertEquals(Arrays.asList(1, 2, 3), integers);
}
@Test
public void givenListOfPersonObject_whenSortedUsingCustomOrdering_shouldSortProperly() {
//given
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3));
Ordering<Person> orderingByAge = new Ordering<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Ints.compare(p1.age, p2.age);
}
};
//when
persons.sort(orderingByAge);
//then
assertEquals(Arrays.asList(new Person("Alice", 3), new Person("Michael", 10)), persons);
}
@Test
public void givenListOfPersonObject_whenSortedUsingChainedOrdering_shouldSortPropely() {
//given
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3), new Person("Thomas", null));
Ordering<Person> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Person, Comparable>() {
@Override
public Comparable apply(Person person) {
return person.age;
}
});
//when
persons.sort(ordering);
//then
assertEquals(Arrays.asList(new Person("Thomas", null), new Person("Alice", 3), new Person("Michael", 10)), persons);
}
class Person {
private final String name;
private final Integer age;
private Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
return age != null ? age.equals(person.age) : person.age == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
return result;
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.javaslang.exception.handling;
import com.baeldung.javaslang.exception.handling.client.ClientException;
import com.baeldung.javaslang.exception.handling.client.HttpClient;
import com.baeldung.javaslang.exception.handling.client.Response;
public class JavaTryCatch {
private HttpClient httpClient;
public JavaTryCatch(HttpClient httpClient) {
this.httpClient = httpClient;
}
public Response getResponse() {
try {
return httpClient.call();
} catch (ClientException e) {
return null;
}
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.javaslang.exception.handling;
import com.baeldung.javaslang.exception.handling.client.HttpClient;
import com.baeldung.javaslang.exception.handling.client.Response;
import javaslang.control.Try;
public class JavaslangTry {
private final HttpClient httpClient;
public JavaslangTry(HttpClient httpClient) {
this.httpClient = httpClient;
}
public Try<Response> getResponse() {
return Try.of(httpClient::call);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.javaslang.exception.handling.client;
public class ClientException extends Exception {
public ClientException(String message) {
super(message);
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.javaslang.exception.handling.client;
public interface HttpClient {
Response call() throws ClientException;
}

View File

@ -0,0 +1,9 @@
package com.baeldung.javaslang.exception.handling.client;
public class Response {
public final String id;
public Response(String id) {
this.id = id;
}
}

View File

@ -0,0 +1,115 @@
package com.baeldung.javaslang.exception.handling;
import com.baeldung.javaslang.exception.handling.client.ClientException;
import com.baeldung.javaslang.exception.handling.client.HttpClient;
import com.baeldung.javaslang.exception.handling.client.Response;
import javaslang.collection.Stream;
import javaslang.control.Option;
import javaslang.control.Try;
import org.junit.Test;
import java.util.function.Function;
import java.util.stream.Collectors;
import static javaslang.API.Case;
import static javaslang.API.Match;
import static javaslang.Predicates.instanceOf;
import static org.junit.Assert.*;
public class JavaslangTryTest {
@Test
public void givenHttpClient_whenMakeACall_shouldReturnSuccess() {
//given
Integer defaultChainedResult = 1;
String id = "a";
HttpClient httpClient = () -> new Response(id);
//when
Try<Response> response = new JavaslangTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Stream<String> stream = response.toStream().map(it -> it.id);
//then
assertTrue(!stream.isEmpty());
assertTrue(response.isSuccess());
response.onSuccess(r -> assertEquals(id, r.id));
response.andThen(r -> assertEquals(id, r.id));
assertNotEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientFailure_whenMakeACall_shouldReturnFailure() {
//given
Integer defaultChainedResult = 1;
HttpClient httpClient = () -> {
throw new ClientException("problem");
};
//when
Try<Response> response = new JavaslangTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Option<Response> optionalResponse = response.toOption();
//then
assertTrue(optionalResponse.isEmpty());
assertTrue(response.isFailure());
response.onFailure(ex -> assertTrue(ex instanceof ClientException));
assertEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndNotRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new RuntimeException("critical problem");
};
//when
Try<Response> recovered = new JavaslangTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case(instanceOf(ClientException.class), defaultResponse)
));
//then
assertTrue(recovered.isFailure());
// recovered.getOrElseThrow(throwable -> {
// throw new RuntimeException(throwable);
// });
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new ClientException("non critical problem");
};
//when
Try<Response> recovered = new JavaslangTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case(instanceOf(ClientException.class), defaultResponse),
Case(instanceOf(IllegalArgumentException.class), defaultResponse)
));
//then
assertTrue(recovered.isSuccess());
}
public int actionThatTakesResponse(Response response) {
return response.id.hashCode();
}
public int actionThatTakesTryResponse(Try<Response> response, int defaultTransformation){
return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation));
}
}

View File

@ -5,7 +5,7 @@ import org.junit.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
class KotlinScalaInteroperabilityTest { class KotlinJavaInteroperabilityTest {
@Test @Test
fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() { fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() {

View File

@ -20,6 +20,7 @@
<module>apache-cxf</module> <module>apache-cxf</module>
<module>apache-fop</module> <module>apache-fop</module>
<module>apache-poi</module> <module>apache-poi</module>
<module>apache-thrift</module>
<module>aspectj</module> <module>aspectj</module>
<module>assertj</module> <module>assertj</module>
<module>autovalue</module> <module>autovalue</module>
@ -95,6 +96,7 @@
<module>resteasy</module> <module>resteasy</module>
<module>selenium-junit-testng</module> <module>selenium-junit-testng</module>
<module>solr-fulltext-search</module>
<module>spark-java</module> <module>spark-java</module>
<module>spring-akka</module> <module>spring-akka</module>
<module>spring-amqp</module> <module>spring-amqp</module>
@ -137,7 +139,7 @@
<module>spring-mvc-web-vs-initializer</module> <module>spring-mvc-web-vs-initializer</module>
<module>spring-mvc-xml</module> <module>spring-mvc-xml</module>
<module>spring-mvc-simple</module> <module>spring-mvc-simple</module>
<module>spring-openid</module> <module>spring-security-openid</module>
<module>spring-protobuf</module> <module>spring-protobuf</module>
<module>spring-quartz</module> <module>spring-quartz</module>
<module>spring-rest-angular</module> <module>spring-rest-angular</module>

View File

@ -0,0 +1,90 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>solr-fulltext-search</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>solr-fulltext-search</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.1.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1,5 @@
package com.baeldung.solr.fulltexh.search.model;
public class Product {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.solr.fulltexh.search.service;
public interface SolrSearchService {
}

6
spark-java/README.md Normal file
View File

@ -0,0 +1,6 @@
=========
## Spark Java Framework Tutorial Sample Project
### Relevant Articles
- [Intro to Spark Java Framework](http://www.baeldung.com/spark-framework-rest-api)

View File

@ -1,4 +1,4 @@
spring.application.name=spring-cloud-rest-server spring.application.name=discovery
server.port=8761 server.port=8761
#### cloud #### cloud

View File

@ -7,8 +7,8 @@
<artifactId>spring-cloud-rest</artifactId> <artifactId>spring-cloud-rest</artifactId>
<version>1.0.0-SNAPSHOT</version> <version>1.0.0-SNAPSHOT</version>
<modules> <modules>
<module>spring-cloud-rest-config</module> <module>spring-cloud-rest-config-server</module>
<module>spring-cloud-rest-server</module> <module>spring-cloud-rest-discovery-server</module>
<module>spring-cloud-rest-books-api</module> <module>spring-cloud-rest-books-api</module>
<module>spring-cloud-rest-reviews-api</module> <module>spring-cloud-rest-reviews-api</module>
</modules> </modules>

View File

@ -4,11 +4,11 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId> <groupId>org.baeldung</groupId>
<artifactId>spring-cloud-rest-config</artifactId> <artifactId>spring-cloud-rest-config-server</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>spring-cloud-rest-config</name> <name>spring-cloud-rest-config-server</name>
<description>Spring Cloud REST configuration server</description> <description>Spring Cloud REST configuration server</description>
<parent> <parent>

View File

@ -4,11 +4,11 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId> <groupId>org.baeldung</groupId>
<artifactId>spring-cloud-rest-server</artifactId> <artifactId>spring-cloud-rest-discovery-server</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>spring-cloud-rest-server</name> <name>spring-cloud-rest-discovery-server</name>
<description>Spring Cloud REST server</description> <description>Spring Cloud REST server</description>
<parent> <parent>

View File

@ -1,4 +1,4 @@
spring.cloud.config.name=spring-cloud-rest-server spring.cloud.config.name=discovery
spring.cloud.config.uri=http://localhost:8081 spring.cloud.config.uri=http://localhost:8081
spring.cloud.config.username=configUser spring.cloud.config.username=configUser
spring.cloud.config.password=configPassword spring.cloud.config.password=configPassword

View File

@ -3,3 +3,4 @@
- [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory) - [Exploring the Spring BeanFactory API](http://www.baeldung.com/spring-beanfactory)
- [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean) - [How to use the Spring FactoryBean?](http://www.baeldung.com/spring-factorybean)
- [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring) - [Constructor Dependency Injection in Spring](http://www.baeldung.com/constructor-injection-in-spring)
- [Constructor Injection in Spring with Lombok](http://inprogress.baeldung.com/constructor-injection-in-spring-with-lombok)

View File

@ -52,6 +52,11 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>${guava.version}</version> <version>${guava.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -131,6 +136,7 @@
<junit.version>4.12</junit.version> <junit.version>4.12</junit.version>
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-war-plugin.version>2.6</maven-war-plugin.version>
<lombok.version>1.16.12</lombok.version>
</properties> </properties>
<repositories> <repositories>

View File

@ -0,0 +1,22 @@
package com.baeldung.lombok;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class Apologizer {
private final Translator translator;
private final String message;
@Autowired
public Apologizer(Translator translator) {
this(translator, "sorry");
}
public String apologize() {
return translator.translate(message);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Fareweller {
private final Translator translator;
public Fareweller(Translator translator) {
this.translator = translator;
}
public String farewell() {
return translator.translate("bye");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.lombok;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Greeter {
@Autowired
private Translator translator;
public String greet() {
return translator.translate("hello");
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.lombok;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class Thanker {
private final Translator translator;
public String thank() {
return translator.translate("thank you");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.lombok;
public interface Translator {
String translate(String input);
}

View File

@ -0,0 +1,33 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class ApologizerAutowiringTest {
private final static String TRANSLATED = "TRANSLATED";
@Autowired
private Apologizer apologizer;
@Autowired
private Translator translator;
@Test
public void apologizeWithTranslatedMessage() {
when(translator.translate("sorry")).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize());
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ApologizerTest {
private final static String MESSAGE = "MESSAGE";
private final static String TRANSLATED = "TRANSLATED";
@Test
public void apologizeWithCustomTranslatedMessage() {
Translator translator = mock(Translator.class);
Apologizer apologizer = new Apologizer(translator, MESSAGE);
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizer.apologize());
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class FarewellAutowiringTest {
@Autowired
private Fareweller fareweller;
@Autowired
private Translator translator;
@Test
public void sayByeWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("bye")).thenReturn(translated);
assertEquals(translated, fareweller.farewell());
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FarewellerTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void sayByeWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("bye")).thenReturn(TRANSLATED);
Fareweller fareweller = new Fareweller(translator);
assertEquals(TRANSLATED, fareweller.farewell());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class GreeterTest {
@Autowired
private Greeter greeter;
@Autowired
private Translator translator;
@Test
public void greetWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("hello")).thenReturn(translated);
assertEquals(translated, greeter.greet());
}
@Test(expected = NullPointerException.class)
public void throwWhenInstantiated() {
Greeter greeter = new Greeter();
greeter.greet();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.lombok;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import static org.mockito.Mockito.mock;
@Configuration
@ComponentScan("com.baeldung.lombok")
class TestConfig {
@Bean
public Translator mockTranslator() {
return mock(Translator.class);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.lombok;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
loader = AnnotationConfigContextLoader.class,
classes = TestConfig.class)
public class ThankerAutowiringTest {
@Autowired
private Thanker thanker;
@Autowired
private Translator translator;
@Test
public void thankWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("thank you")).thenReturn(translated);
assertEquals(translated, thanker.thank());
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.lombok;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ThankerTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void thankWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("thank you")).thenReturn(TRANSLATED);
Thanker thanker = new Thanker(translator);
assertEquals(TRANSLATED, thanker.thank());
}
}

View File

@ -5,15 +5,15 @@
<hibernate-configuration> <hibernate-configuration>
<session-factory> <session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">bastard5</property> <property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/setup</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true</property>
<property name="hibernate.connection.username">root</property> <property name="hibernate.connection.username">myuser</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property> <property name="hibernate.show_sql">true</property>
<mapping class="com.baeldung.hibernate.model.Cart"/> <mapping class="com.baeldung.hibernate.oneToMany.model.Cart"/>
<mapping class="com.baeldung.hibernate.model.Items"/> <mapping class="com.baeldung.hibernate.oneToMany.model.Items"/>
</session-factory> </session-factory>
</hibernate-configuration> </hibernate-configuration>

View File

@ -14,4 +14,4 @@ CREATE TABLE `Items` (
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
KEY `cart_id` (`cart_id`), KEY `cart_id` (`cart_id`),
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`) CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

View File

@ -1,43 +0,0 @@
package com.baeldung.hibernate.oneToMany.config;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class HibernateAnnotationUtilTest {
public HibernateAnnotationUtilTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetSessionFactory() {
System.out.println("getSessionFactory");
SessionFactory expResult = null;
SessionFactory result = HibernateAnnotationUtil.getSessionFactory();
assertEquals(expResult, result);
fail("The test failed.");
}
}

View File

@ -1,8 +1,19 @@
package com.baeldung.hibernate.oneToMany.main; package com.baeldung.hibernate.oneToMany.main;
import org.junit.After;
import org.junit.AfterClass; import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Items;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.Matchers.hasSize;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.service.ServiceRegistry;
import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
@ -11,30 +22,68 @@ import static org.junit.Assert.*;
public class HibernateOneToManyAnnotationMainTest { public class HibernateOneToManyAnnotationMainTest {
private static SessionFactory sessionFactory;
private Session session;
public HibernateOneToManyAnnotationMainTest() { public HibernateOneToManyAnnotationMainTest() {
} }
@BeforeClass
public static void setUpClass() {
}
@AfterClass @BeforeClass
public static void tearDownClass() { public static void beforeTests() {
Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class).setProperty("hibernate.dialect", HSQLDialect.class.getName()).setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test").setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} }
@Before @Before
public void setUp() { public void setUp() {
session = sessionFactory.openSession();
session.beginTransaction();
} }
@After
public void tearDown() {
}
@Test @Test
public void testMain() { public void testAddItemsToCart() {
System.out.println("main"); Cart cart = new Cart();
String[] args = null; Set <Items> cartItems = new HashSet<>();
HibernateOneToManyAnnotationMain.main(args); cartItems = cart.getItems();
fail("The test failed."); Assert.assertNull(cartItems);
Items item1 = new Items("I10", 10, 1, cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
cart.setItems(itemsSet);
assertNotNull(cart);
System.out.println("Items added to cart");
} }
@Test
public void testSaveCart(){
Cart cart = new Cart();
Set <Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setItemId("I10");
item1.setItemTotal(10);
item1.setQuantity(1);
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
session.close();
}
} }

View File

@ -1,111 +0,0 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class CartTest {
public CartTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetId() {
System.out.println("getId");
Cart instance = new Cart();
long expResult = 0L;
long result = instance.getId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetId() {
System.out.println("setId");
long id = 0L;
Cart instance = new Cart();
instance.setId(id);
fail("The test failed.");
}
@Test
public void testGetTotal() {
System.out.println("getTotal");
Cart instance = new Cart();
double expResult = 0.0;
double result = instance.getTotal();
assertEquals(expResult, result, 0.0);
fail("The test failed.");
}
@Test
public void testSetTotal() {
System.out.println("setTotal");
double total = 0.0;
Cart instance = new Cart();
instance.setTotal(total);
fail("The test failed.");
}
@Test
public void testGetName() {
System.out.println("getName");
Cart instance = new Cart();
String expResult = "";
String result = instance.getName();
assertEquals(expResult, result);
fail("The test failed");
}
@Test
public void testSetName() {
System.out.println("setName");
String name = "";
Cart instance = new Cart();
instance.setName(name);
fail("The test failed.");
}
@Test
public void testGetItems() {
System.out.println("getItems");
Cart instance = new Cart();
Set<Items> expResult = null;
Set<Items> result = instance.getItems();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetItems() {
System.out.println("setItems");
Set<Items> items = null;
Cart instance = new Cart();
instance.setItems(items);
fail("The test case failed");
}
}

View File

@ -1,129 +0,0 @@
package com.baeldung.hibernate.oneToMany.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ItemsTest {
public ItemsTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testGetItemId() {
System.out.println("getItemId");
Items instance = new Items();
String expResult = "";
String result = instance.getItemId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetItemId() {
System.out.println("setItemId");
String itemId = "";
Items instance = new Items();
instance.setItemId(itemId);
fail("The test failed.");
}
@Test
public void testGetItemTotal() {
System.out.println("getItemTotal");
Items instance = new Items();
double expResult = 0.0;
double result = instance.getItemTotal();
assertEquals(expResult, result, 0.0);
fail("The test failed.");
}
@Test
public void testSetItemTotal() {
System.out.println("setItemTotal");
double itemTotal = 0.0;
Items instance = new Items();
instance.setItemTotal(itemTotal);
fail("The test failed.");
}
@Test
public void testGetQuantity() {
System.out.println("getQuantity");
Items instance = new Items();
int expResult = 0;
int result = instance.getQuantity();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetQuantity() {
System.out.println("setQuantity");
int quantity = 0;
Items instance = new Items();
instance.setQuantity(quantity);
fail("The test failed.");
}
@Test
public void testGetCart() {
System.out.println("getCart");
Items instance = new Items();
Cart expResult = null;
Cart result = instance.getCart();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetCart() {
System.out.println("setCart");
Cart cart = null;
Items instance = new Items();
instance.setCart(cart);
fail("The test failed.");
}
@Test
public void testGetId() {
System.out.println("getId");
Items instance = new Items();
long expResult = 0L;
long result = instance.getId();
assertEquals(expResult, result);
fail("The test failed.");
}
@Test
public void testSetId() {
System.out.println("setId");
long id = 0L;
Items instance = new Items();
instance.setId(id);
fail("The test failed.");
}
}

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>jersey-api</artifactId> <artifactId>spring-jersey</artifactId>
<version>0.1-SNAPSHOT</version> <version>0.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
@ -23,6 +23,7 @@
</properties> </properties>
<build> <build>
<finalName>spring-jersey</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
@ -75,11 +76,6 @@
<!-- core library --> <!-- core library -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.containers</groupId> <groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId> <artifactId>jersey-container-servlet</artifactId>
@ -90,6 +86,12 @@
<artifactId>jersey-media-json-jackson</artifactId> <artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version> <version>${jersey.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- servlet api --> <!-- servlet api -->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
@ -97,8 +99,8 @@
<version>${servlet-api-version}</version> <version>${servlet-api-version}</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!-- optional library -->
<!-- optional library -->
<dependency> <dependency>
<groupId>org.glassfish.jersey.ext</groupId> <groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId> <artifactId>jersey-spring3</artifactId>

View File

@ -0,0 +1,31 @@
package com.baeldung.client.rest;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.baeldung.server.model.Employee;
public class RestClient {
private static final String REST_URI = "http://localhost:8082/spring-jersey/resources/employees";
private Client client = ClientBuilder.newClient();
public Response createJsonEmployee(Employee emp) {
return client.target(REST_URI).request(MediaType.APPLICATION_JSON).post(Entity.entity(emp, MediaType.APPLICATION_JSON));
}
public Employee getJsonEmployee(int id) {
return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_JSON).get(Employee.class);
}
public Response createXmlEmployee(Employee emp) {
return client.target(REST_URI).request(MediaType.APPLICATION_XML).post(Entity.entity(emp, MediaType.APPLICATION_XML));
}
public Employee getXmlEmployee(int id) {
return client.target(REST_URI).path(new Integer(id).toString()).request(MediaType.APPLICATION_XML).get(Employee.class);
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.client;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.core.Response;
import org.junit.Test;
import com.baeldung.client.rest.RestClient;
import com.baeldung.server.model.Employee;
public class JerseyClientLiveTest {
public static final int HTTP_CREATED = 201;
private RestClient client = new RestClient();
@Test
public void givenCorrectObject_whenCorrectJsonRequest_thenResponseCodeCreated() {
Employee emp = new Employee(6, "Johny");
Response response = client.createJsonEmployee(emp);
assertEquals(response.getStatus(), HTTP_CREATED);
}
@Test
public void givenCorrectObject_whenCorrectXmlRequest_thenResponseCodeCreated() {
Employee emp = new Employee(7, "Jacky");
Response response = client.createXmlEmployee(emp);
assertEquals(response.getStatus(), HTTP_CREATED);
}
@Test
public void givenCorrectId_whenCorrectJsonRequest_thenCorrectEmployeeRetrieved() {
int employeeId = 1;
Employee emp = client.getJsonEmployee(employeeId);
assertEquals(emp.getFirstName(), "Jane");
}
@Test
public void givenCorrectId_whenCorrectXmlRequest_thenCorrectEmployeeRetrieved() {
int employeeId = 1;
Employee emp = client.getXmlEmployee(employeeId);
assertEquals(emp.getFirstName(), "Jane");
}
}

View File

@ -1,5 +1,8 @@
package com.baeldung.server; package com.baeldung.server;
import static org.junit.Assert.assertEquals;
import com.baeldung.server.model.Employee; import com.baeldung.server.model.Employee;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -15,7 +18,7 @@ import java.io.IOException;
public class JerseyApiLiveTest { public class JerseyApiLiveTest {
private static final String SERVICE_URL = "http://localhost:8082/jersey-api/resources/employees"; private static final String SERVICE_URL = "http://localhost:8082/spring-jersey/resources/employees";
@Test @Test
public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() throws IOException { public void givenGetAllEmployees_whenCorrectRequest_thenResponseCodeSuccess() throws IOException {
@ -23,7 +26,7 @@ public class JerseyApiLiveTest {
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
} }
@Test @Test
@ -32,7 +35,7 @@ public class JerseyApiLiveTest {
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
} }
@Test @Test
@ -41,7 +44,7 @@ public class JerseyApiLiveTest {
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_NOT_FOUND);
} }
@Test @Test
@ -53,7 +56,7 @@ public class JerseyApiLiveTest {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
Employee emp = mapper.readValue(httpResponse.getEntity().getContent(), Employee.class); Employee emp = mapper.readValue(httpResponse.getEntity().getContent(), Employee.class);
assert(emp.getFirstName().equals("Jane")); assertEquals(emp.getFirstName(), "Jane");
} }
@Test @Test
@ -68,7 +71,7 @@ public class JerseyApiLiveTest {
request.setEntity(input); request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
} }
@Test @Test
@ -83,7 +86,7 @@ public class JerseyApiLiveTest {
request.setEntity(input); request.setEntity(input);
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
assert(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_CONFLICT);
} }
} }

View File

@ -160,6 +160,28 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.jxls</groupId>
<artifactId>jxls-jexcel</artifactId>
<version>${jexcel.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -370,6 +392,10 @@
<!-- AspectJ --> <!-- AspectJ -->
<aspectj.version>1.8.9</aspectj.version> <aspectj.version>1.8.9</aspectj.version>
<!-- excel -->
<poi.version>3.16-beta1</poi.version>
<jexcel.version>1.0.6</jexcel.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,140 @@
package com.baeldung.excel;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
@Service
public class ExcelPOIHelper {
public Map<Integer, ArrayList<String>> readExcel(String fileLocation) throws IOException {
Map<Integer, ArrayList<String>> data = new HashMap<Integer, ArrayList<String>>();
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING:
data.get(i)
.add(cell.getRichStringCellValue()
.getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
data.get(i)
.add(cell.getDateCellValue() + "");
} else {
data.get(i)
.add(cell.getNumericCellValue() + "");
}
break;
case BOOLEAN:
data.get(i)
.add(cell.getBooleanCellValue() + "");
break;
case FORMULA:
data.get(i)
.add(cell.getCellFormula() + "");
break;
default:
data.get(i)
.add(" ");
}
}
i++;
}
if (workbook != null){
workbook.close();
}
return data;
}
public void writeExcel() throws IOException {
Workbook workbook = new XSSFWorkbook();
try {
Sheet sheet = workbook.createSheet("Persons");
sheet.setColumnWidth(0, 6000);
sheet.setColumnWidth(1, 4000);
Row header = sheet.createRow(0);
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFFont font = ((XSSFWorkbook) workbook).createFont();
font.setFontName("Arial");
font.setFontHeightInPoints((short) 16);
font.setBold(true);
headerStyle.setFont(font);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("Name");
headerCell.setCellStyle(headerStyle);
headerCell = header.createCell(1);
headerCell.setCellValue("Age");
headerCell.setCellStyle(headerStyle);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
Row row = sheet.createRow(2);
Cell cell = row.createCell(0);
cell.setCellValue("John Smith");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(20);
cell.setCellStyle(style);
row = sheet.createRow(3);
cell = row.createCell(0);
cell.setCellValue("Ana Johnson");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(30);
cell.setCellStyle(style);
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xlsx";
FileOutputStream outputStream = new FileOutputStream(fileLocation);
workbook.write(outputStream);
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

View File

@ -0,0 +1,80 @@
package com.baeldung.excel;
import jxl.*;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
import org.springframework.stereotype.Service;
import jxl.write.*;
import jxl.write.Number;
import jxl.format.Colour;
@Service
public class JExcelHelper {
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
Map<Integer, ArrayList<String>> data = new HashMap<Integer, ArrayList<String>>();
Workbook workbook = Workbook.getWorkbook(new File(fileLocation));
Sheet sheet = workbook.getSheet(0);
int rows = sheet.getRows();
int columns = sheet.getColumns();
for (int i = 0; i < rows; i++) {
data.put(i, new ArrayList<String>());
for (int j = 0; j < columns; j++) {
data.get(i).add(sheet.getCell(j, i).getContents());
}
}
return data;
}
public void writeJExcel() throws IOException, WriteException {
WritableWorkbook workbook = null;
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
String fileLocation = path.substring(0, path.length() - 1) + "temp.xls";
workbook = Workbook.createWorkbook(new File(fileLocation));
WritableSheet sheet = workbook.createSheet("Sheet 1", 0);
WritableCellFormat headerFormat = new WritableCellFormat();
WritableFont font = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
headerFormat.setFont(font);
headerFormat.setBackground(Colour.LIGHT_BLUE);
headerFormat.setWrap(true);
Label headerLabel = new Label(0, 0, "Name", headerFormat);
sheet.setColumnView(0, 60);
sheet.addCell(headerLabel);
headerLabel = new Label(1, 0, "Age", headerFormat);
sheet.setColumnView(0, 40);
sheet.addCell(headerLabel);
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setWrap(true);
Label cellLabel = new Label(0, 2, "John Smith", cellFormat);
sheet.addCell(cellLabel);
Number cellNumber = new Number(1, 2, 20, cellFormat);
sheet.addCell(cellNumber);
cellLabel = new Label(0, 3, "Ana Johnson", cellFormat);
sheet.addCell(cellLabel);
cellNumber = new Number(1, 3, 30, cellFormat);
sheet.addCell(cellNumber);
workbook.write();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
}

View File

@ -21,6 +21,7 @@ import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver; import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver; import org.springframework.web.servlet.view.XmlViewResolver;
import org.springframework.web.util.UrlPathHelper; import org.springframework.web.util.UrlPathHelper;
import com.baeldung.excel.*;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
@ -106,4 +107,15 @@ public class WebConfig extends WebMvcConfigurerAdapter {
configurer.setUrlPathHelper(urlPathHelper); configurer.setUrlPathHelper(urlPathHelper);
} }
@Bean
public JExcelHelper jExcelHelper() {
return new JExcelHelper();
}
@Bean
public ExcelPOIHelper excelPOIHelper() {
return new ExcelPOIHelper();
}
} }

View File

@ -0,0 +1,105 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.baeldung.excel.*;
import jxl.read.biff.BiffException;
import java.util.Map;
import java.util.ArrayList;
import javax.annotation.Resource;
import jxl.write.WriteException;
@Controller
public class ExcelController {
private String fileLocation;
@Resource(name = "jExcelHelper")
private JExcelHelper jExcelHelper;
@Resource(name = "excelPOIHelper")
private ExcelPOIHelper excelPOIHelper;
@RequestMapping(method = RequestMethod.GET, value = "/excelProcessing")
public String getExcelProcessingPage() {
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/uploadExcelFile")
public String uploadFile(Model model, MultipartFile file) throws IOException {
InputStream in = file.getInputStream();
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename();
FileOutputStream f = new FileOutputStream(fileLocation);
int ch = 0;
while ((ch = in.read()) != -1) {
f.write(ch);
}
f.flush();
f.close();
System.out.println(fileLocation);
model.addAttribute("message", "File: " + file.getOriginalFilename() + " has been uploaded successfully!");
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readJExcel")
public String readJExcel(Model model) throws IOException, BiffException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xls")) {
Map<Integer, ArrayList<String>> data = jExcelHelper.readJExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid .xls file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
@RequestMapping(method = RequestMethod.GET, value = "/readPOI")
public String readPOI(Model model) throws IOException {
if (fileLocation != null) {
if (fileLocation.endsWith(".xlsx")) {
Map<Integer, ArrayList<String>> data = excelPOIHelper.readExcel(fileLocation);
model.addAttribute("data", data);
} else {
model.addAttribute("message", "Not a valid .xlsx file!");
}
} else {
model.addAttribute("message", "File missing! Please upload an excel file.");
}
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/writeJExcel")
public String writeJExcel(Model model) throws IOException, BiffException, WriteException {
jExcelHelper.writeJExcel();
model.addAttribute("message", "Write successful!");
return "excel";
}
@RequestMapping(method = RequestMethod.POST, value = "/writePOI")
public String writePOI(Model model) throws IOException {
excelPOIHelper.writeExcel();
model.addAttribute("message", "Write successful!");
return "excel";
}
}

View File

@ -0,0 +1,56 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Excel Processing</title>
</head>
<body>
<c:url value="/uploadExcelFile" var="uploadFileUrl" />
<c:url value="/excelProcessing" var="resetUrl" />
<c:url value="/readJExcel" var="readJExcelUrl" />
<c:url value="/writeJExcel" var="writeJExcelUrl" />
<c:url value="/readPOI" var="readPOIUrl" />
<c:url value="/writePOI" var="writePOIUrl" />
<form method="post" enctype="multipart/form-data" action="${uploadFileUrl}" >
<input type="file" name="file" accept=".xls,.xlsx"/>
<input type="submit" value="Upload file"/>
</form>
<br />
${message }
<br /> <br />
<form method="GET" action="${resetUrl}" >
<input type="submit" value="Reset" />
</form>
<br /> <br />
<a href="${readJExcelUrl}">Read file using JExcel</a> &nbsp;&nbsp;&nbsp;
<a href="${readPOIUrl}">Read file using Apache POI</a>
<br /> <br />
File content:
<c:if test="${not empty data}">
<table style="border:1px solid black;border-collapse:collapse;">
<c:forEach items="${data}" var="row">
<tr>
<c:forEach items="${row.value}" var="cell">
<td style="border:1px solid black">${cell}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</c:if>
<br /> <br />
<form action="${writeJExcelUrl}" method="POST">
<input type="submit" value="Write to file using JExcel" />
</form>
<br />
<form action="${writePOIUrl}" method="POST">
<input type="submit" value="Write to file using Apache POI" />
</form>
</body>
</html>

View File

@ -2,15 +2,13 @@
## OpenID Connect with Spring Security ## OpenID Connect with Spring Security
### Run the Project
### Build the Project
``` ```
mvn clean install mvn spring-boot:run
``` ```
### Obtain Google App - Client ID, Secret ### Obtain Google App - Client ID, Secret
- You need to get client id and client secret from [Google Developer Console](https://console.developers.google.com/project/_/apiui/credential?pli=1) - You need to get client id and client secret by creating a new project at [Google Developer Console](https://console.developers.google.com/project/_/apiui/credential?pli=1)
- Make sure to add OAuth2 credentials by selecting Add credentials > OAuth 2.0 client ID - Make sure to add OAuth2 credentials by selecting Add credentials > OAuth 2.0 client ID
- Make sure you set redirect URI to http://localhost:8081/google-login - Make sure you set redirect URI to http://localhost:8081/google-login

View File

@ -3,11 +3,11 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>spring-openid</artifactId> <artifactId>spring-security-openid</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>spring-openid</name> <name>spring-security-openid</name>
<description>Spring OpenID sample project</description> <description>Spring OpenID sample project</description>
<parent> <parent>

View File

@ -0,0 +1,33 @@
package com.baeldung.jacksonannotation.serialization.jsongetter;
import com.baeldung.jacksonannotation.domain.Item;
import com.baeldung.jacksonannotation.domain.Person;
import com.fasterxml.jackson.annotation.JsonGetter;
import java.util.ArrayList;
import java.util.List;
/**
* Source code github.com/eugenp/tutorials
*
* @author Alex Theedom www.baeldung.com
* @version 1.0
*/
public class Author1 extends Person {
List<Item> items = new ArrayList<>();
public Author1(String firstName, String lastName) {
super(firstName, lastName);
}
@JsonGetter
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}

View File

@ -14,11 +14,11 @@ import java.util.List;
* @author Alex Theedom www.baeldung.com * @author Alex Theedom www.baeldung.com
* @version 1.0 * @version 1.0
*/ */
public class Author extends Person { public class Author2 extends Person {
List<Item> items = new ArrayList<>(); List<Item> items = new ArrayList<>();
public Author(String firstName, String lastName) { public Author2(String firstName, String lastName) {
super(firstName, lastName); super(firstName, lastName);
} }
@ -27,6 +27,7 @@ public class Author extends Person {
return items; return items;
} }
public void setItems(List<Item> items) { public void setItems(List<Item> items) {
this.items = items; this.items = items;
} }

View File

@ -16,10 +16,33 @@ import static org.assertj.core.api.Assertions.assertThat;
public class JsonGetterTest { public class JsonGetterTest {
@Test @Test
public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException { public void whenSerializingUsingJsonGetter_andNoPropertyNameSet_thenCorrect() throws JsonProcessingException {
// arrange // arrange
Author author = new Author("Alex", "Theedom"); Author1 author = new Author1("Alex", "Theedom");
// act
String result = new ObjectMapper().writeValueAsString(author);
// assert
assertThat(from(result).getList("items")).isNotNull();
/*
{
"firstName": "Alex",
"lastName": "Theedom",
"items": []
}
*/
}
@Test
public void whenSerializingUsingJsonGetter_andPropertyNameSet_thenCorrect() throws JsonProcessingException {
// arrange
Author2 author = new Author2("Alex", "Theedom");
// act // act
String result = new ObjectMapper().writeValueAsString(author); String result = new ObjectMapper().writeValueAsString(author);