This commit is contained in:
Tomasz Lelek 2017-02-04 17:15:56 +01:00
commit 842dd43b21
81 changed files with 6798 additions and 558 deletions

1
.gitignore vendored
View File

@ -28,3 +28,4 @@ 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,11 @@
package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
public class Application {
public static void main(String[] args) throws TTransportException {
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,36 @@
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;
import org.apache.thrift.transport.TTransportException;
public class CrossPlatformServiceServer {
private TServer server;
public void start() throws TTransportException {
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.");
}
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,40 @@
package com.baeldung.thrift;
import org.apache.thrift.transport.TTransportException;
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(() -> {
try {
server.start();
} catch (TTransportException e) {
e.printStackTrace();
}
}).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

@ -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,51 @@
package com.baeldung.concurrent.priorityblockingqueue;
import org.junit.Test;
import java.util.ArrayList;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.util.Lists.newArrayList;
public class PriorityBlockingQueueUnitTest {
@Test
public void givenUnorderedValues_whenPolling_thenShouldOrderQueue() throws InterruptedException {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
ArrayList<Integer> polledElements = new ArrayList<>();
queue.add(1);
queue.add(5);
queue.add(2);
queue.add(3);
queue.add(4);
queue.drainTo(polledElements);
assertThat(polledElements).containsExactly(1, 2, 3, 4, 5);
}
@Test
public void whenPollingEmptyQueue_thenShouldBlockThread() throws InterruptedException {
PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>();
final Thread thread = new Thread(() -> {
System.out.println("Polling...");
while (true) {
try {
Integer poll = queue.take();
System.out.println("Polled: " + poll);
} catch (InterruptedException e) {}
}
});
thread.start();
Thread.sleep(TimeUnit.SECONDS.toMillis(5));
System.out.println("Adding to queue");
queue.addAll(newArrayList(1, 5, 6, 1, 2, 6, 7));
Thread.sleep(TimeUnit.SECONDS.toMillis(1));
}
}

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 ThreadPoolInParallelStreamTest {
@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>
@ -93,6 +94,7 @@
<module>rest-assured</module> <module>rest-assured</module>
<module>rest-testing</module> <module>rest-testing</module>
<module>resteasy</module> <module>resteasy</module>
<module>rxjava</module>
<module>selenium-junit-testng</module> <module>selenium-junit-testng</module>
<module>solr-fulltext-search</module> <module>solr-fulltext-search</module>
@ -138,7 +140,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

@ -1,44 +1,16 @@
package com.baelding.rxjava; package com.baelding.rxjava;
import rx.Observable; import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers; import rx.schedulers.Schedulers;
public class ColdObservableBackPressure { public class ColdObservableBackpressure {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
Observable.range(1, 1_000_000) Observable.range(1, 1_000_000)
.observeOn(Schedulers.computation()) .observeOn(Schedulers.computation())
.subscribe(ComputeFunction::compute); .subscribe(ComputeFunction::compute);
Thread.sleep(10_000); Thread.sleep(10_000);
// Observable.range(1, 1_000_000) //implementation of reactive pull backpressure on cold observable
// .subscribe(new Subscriber<Integer>() {
// @Override
// public void onStart() {
// request(1);
// }
//
// public void onNext(Integer v) {
// compute(v);
//
// request(1);
// }
//
// @Override
// public void onError(Throwable ex) {
// ex.printStackTrace();
// }
//
// @Override
// public void onCompleted() {
// System.out.println("Done!");
// }
// });
} }
} }

View File

@ -1,6 +1,5 @@
package com.baelding.rxjava; package com.baelding.rxjava;
import rx.Observable; import rx.Observable;
import java.util.List; import java.util.List;
@ -33,7 +32,6 @@ public class ComputeFunction {
} }
} }
public static void compute(Long v) { public static void compute(Long v) {
try { try {
System.out.println("compute integer v: " + v); System.out.println("compute integer v: " + v);

View File

@ -3,14 +3,11 @@ package com.baelding.rxjava;
import rx.schedulers.Schedulers; import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject; import rx.subjects.PublishSubject;
public class HotObservableBackPressureBatching { public class HotObservableBackpressureBatching {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
PublishSubject<Integer> source = PublishSubject.<Integer>create(); PublishSubject<Integer> source = PublishSubject.<Integer>create();
source.window(500) source.window(500).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace);
.observeOn(Schedulers.computation())
.subscribe(ComputeFunction::compute, Throwable::printStackTrace);
for (int i = 0; i < 1_000_000; i++) { for (int i = 0; i < 1_000_000; i++) {
source.onNext(i); source.onNext(i);

View File

@ -3,16 +3,11 @@ package com.baelding.rxjava;
import rx.schedulers.Schedulers; import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject; import rx.subjects.PublishSubject;
public class HotObservableBackpressureBuffering {
public class HotObservableBackPressureBuffering {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
PublishSubject<Integer> source = PublishSubject.<Integer>create(); PublishSubject<Integer> source = PublishSubject.<Integer>create();
source source.buffer(1024).observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace);
.buffer(1024)
.observeOn(Schedulers.computation())
.subscribe(ComputeFunction::compute, Throwable::printStackTrace);
for (int i = 0; i < 1_000_000; i++) { for (int i = 0; i < 1_000_000; i++) {
source.onNext(i); source.onNext(i);

View File

@ -5,15 +5,13 @@ import rx.subjects.PublishSubject;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class HotObservableBackPressureSkipping { public class HotObservableBackpressureSkipping {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
PublishSubject<Integer> source = PublishSubject.<Integer>create(); PublishSubject<Integer> source = PublishSubject.<Integer>create();
source.sample(100, TimeUnit.MILLISECONDS) source.sample(100, TimeUnit.MILLISECONDS)
// .throttleFirst(100, TimeUnit.MILLISECONDS) // .throttleFirst(100, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation()) .observeOn(Schedulers.computation()).subscribe(ComputeFunction::compute, Throwable::printStackTrace);
.subscribe(ComputeFunction::compute, Throwable::printStackTrace);
for (int i = 0; i < 1_000_000; i++) { for (int i = 0; i < 1_000_000; i++) {
source.onNext(i); source.onNext(i);

View File

@ -1,28 +0,0 @@
package com.baelding.rxjava;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.schedulers.Schedulers;
public class HotObservableOnBackPressure {
public static void main(String[] args) throws InterruptedException {
Observable.range(1, 1_000_000)
.onBackpressureBuffer(16, () -> {
},
BackpressureOverflow.ON_OVERFLOW_DROP_OLDEST)
.observeOn(Schedulers.computation())
.subscribe(e -> {
}, Throwable::printStackTrace);
Observable.range(1, 1_000_000)
.onBackpressureDrop()
.observeOn(Schedulers.computation())
.doOnNext(ComputeFunction::compute)
.subscribe(v -> {
}, Throwable::printStackTrace);
Thread.sleep(10_000);
}
}

View File

@ -4,7 +4,7 @@ package com.baelding.rxjava;
import rx.schedulers.Schedulers; import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject; import rx.subjects.PublishSubject;
public class HotObservableWithoutBackPressure { public class HotObservableWithoutBackpressure {
public static void main(String[] args) throws InterruptedException { public static void main(String[] args) throws InterruptedException {
PublishSubject<Integer> source = PublishSubject.<Integer>create(); PublishSubject<Integer> source = PublishSubject.<Integer>create();

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

@ -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 ApologizeService {
private final Translator translator;
private final String message;
@Autowired
public ApologizeService(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 FarewellService {
private final Translator translator;
public FarewellService(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 GreetingService {
@Autowired
private Translator translator;
public String greet() {
return translator.translate("hello");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.lombok;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
public class ThankingService {
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 ApologizeServiceAutowiringTest {
private final static String TRANSLATED = "TRANSLATED";
@Autowired
private ApologizeService apologizeService;
@Autowired
private Translator translator;
@Test
public void apologizeWithTranslatedMessage() {
when(translator.translate("sorry")).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizeService.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 ApologizeServiceTest {
private final static String MESSAGE = "MESSAGE";
private final static String TRANSLATED = "TRANSLATED";
@Test
public void apologizeWithCustomTranslatedMessage() {
Translator translator = mock(Translator.class);
ApologizeService apologizeService = new ApologizeService(translator, MESSAGE);
when(translator.translate(MESSAGE)).thenReturn(TRANSLATED);
assertEquals(TRANSLATED, apologizeService.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 FarewellService farewellService;
@Autowired
private Translator translator;
@Test
public void sayByeWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("bye")).thenReturn(translated);
assertEquals(translated, farewellService.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 FarewellServiceTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void sayByeWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("bye")).thenReturn(TRANSLATED);
FarewellService farewellService = new FarewellService(translator);
assertEquals(TRANSLATED, farewellService.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 GreetingServiceTest {
@Autowired
private GreetingService greetingService;
@Autowired
private Translator translator;
@Test
public void greetWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("hello")).thenReturn(translated);
assertEquals(translated, greetingService.greet());
}
@Test(expected = NullPointerException.class)
public void throwWhenInstantiated() {
GreetingService greetingService = new GreetingService();
greetingService.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 ThankingServiceAutowiringTest {
@Autowired
private ThankingService thankingService;
@Autowired
private Translator translator;
@Test
public void thankWithTranslatedMessage() {
String translated = "translated";
when(translator.translate("thank you")).thenReturn(translated);
assertEquals(translated, thankingService.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 ThankingServiceTest {
private final static String TRANSLATED = "TRANSLATED";
@Test
public void thankWithTranslatedMessage() {
Translator translator = mock(Translator.class);
when(translator.translate("thank you")).thenReturn(TRANSLATED);
ThankingService thankingService = new ThankingService(translator);
assertEquals(TRANSLATED, thankingService.thank());
}
}

View File

@ -7,32 +7,31 @@ import org.hibernate.service.ServiceRegistry;
public class HibernateAnnotationUtil { public class HibernateAnnotationUtil {
private static SessionFactory sessionFactory; private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() { private static SessionFactory buildSessionFactory() {
try { try {
// Create the SessionFactory from hibernate-annotation.cfg.xml // Create the SessionFactory from hibernate-annotation.cfg.xml
Configuration configuration = new Configuration(); Configuration configuration = new Configuration();
configuration.configure("hibernate-annotation.cfg.xml"); configuration.configure("hibernate-annotation.cfg.xml");
System.out.println("Hibernate Annotation Configuration loaded"); System.out.println("Hibernate Annotation Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate Annotation serviceRegistry created"); System.out.println("Hibernate Annotation serviceRegistry created");
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory; return sessionFactory;
} } catch (Throwable ex) {
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex); System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace(); ex.printStackTrace();
throw new ExceptionInInitializerError(ex); throw new ExceptionInInitializerError(ex);
} }
} }
public static SessionFactory getSessionFactory() { public static SessionFactory getSessionFactory() {
if(sessionFactory == null) sessionFactory = buildSessionFactory(); if (sessionFactory == null)
sessionFactory = buildSessionFactory();
return sessionFactory; return sessionFactory;
} }
} }

View File

@ -13,48 +13,49 @@ import com.baeldung.hibernate.oneToMany.model.Items;
public class HibernateOneToManyAnnotationMain { public class HibernateOneToManyAnnotationMain {
public static void main(String[] args) { public static void main(String[] args) {
Cart cart = new Cart(); Cart cart = new Cart();
cart.setName("MyCart"); cart.setName("MyCart");
Items item1 = new Items("I10", 10, 1, cart); Items item1 = new Items("I10", 10, 1, cart);
Items item2 = new Items("I20", 20, 2, cart); Items item2 = new Items("I20", 20, 2, cart);
Set<Items> itemsSet = new HashSet<Items>(); Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1); itemsSet.add(item2); itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet); cart.setItems(itemsSet);
cart.setTotal(10*1 + 20*2); cart.setTotal(10 * 1 + 20 * 2);
SessionFactory sessionFactory = null; SessionFactory sessionFactory = null;
Session session = null; Session session = null;
Transaction tx = null; Transaction tx = null;
try{ try {
//Get Session // Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory(); sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession(); session = sessionFactory.getCurrentSession();
System.out.println("Session created"); System.out.println("Session created");
//start transaction // start transaction
tx = session.beginTransaction(); tx = session.beginTransaction();
//Save the Model object // Save the Model object
session.save(cart); session.save(cart);
session.save(item1); session.save(item1);
session.save(item2); session.save(item2);
//Commit transaction // Commit transaction
tx.commit(); tx.commit();
System.out.println("Cart ID="+cart.getId()); System.out.println("Cart ID=" + cart.getId());
System.out.println("item1 ID="+item1.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
System.out.println("item2 ID="+item2.getId()+", Foreign Key Cart ID="+item1.getCart().getId()); System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId());
}catch(Exception e){ } catch (Exception e) {
System.out.println("Exception occured. "+e.getMessage()); System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace(); e.printStackTrace();
}finally{ } finally {
if(!sessionFactory.isClosed()){ if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory"); System.out.println("Closing SessionFactory");
sessionFactory.close(); sessionFactory.close();
} }
} }
} }
} }

View File

@ -11,46 +11,53 @@ import javax.persistence.OneToMany;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="CART") @Table(name = "CART")
public class Cart { public class Cart {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cart_id") @Column(name = "cart_id")
private long id; private long id;
@Column(name="total") @Column(name = "total")
private double total; private double total;
@Column(name="name") @Column(name = "name")
private String name; private String name;
@OneToMany(mappedBy="cart") @OneToMany(mappedBy = "cart")
private Set<Items> items; private Set<Items> items;
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) {
this.id = id; public void setId(long id) {
} this.id = id;
public double getTotal() { }
return total;
} public double getTotal() {
public void setTotal(double total) { return total;
this.total = total; }
}
public String getName() { public void setTotal(double total) {
return name; this.total = total;
} }
public void setName(String name) {
this.name = name; public String getName() {
} return name;
public Set<Items> getItems() { }
return items;
} public void setName(String name) {
public void setItems(Set<Items> items) { this.name = name;
this.items = items; }
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
} }

View File

@ -10,65 +10,76 @@ import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
@Entity @Entity
@Table(name="ITEMS") @Table(name = "ITEMS")
public class Items { public class Items {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id") @Column(name = "id")
private long id; private long id;
@Column(name="item_id") @Column(name = "item_id")
private String itemId; private String itemId;
@Column(name="item_total") @Column(name = "item_total")
private double itemTotal; private double itemTotal;
@Column(name="quantity") @Column(name = "quantity")
private int quantity; private int quantity;
@ManyToOne @ManyToOne
@JoinColumn(name="cart_id", nullable=false) @JoinColumn(name = "cart_id", nullable = false)
private Cart cart; private Cart cart;
//Hibernate requires no-args constructor // Hibernate requires no-args constructor
public Items(){} public Items() {
}
public Items(String itemId, double total, int qty, Cart c){ public Items(String itemId, double total, int qty, Cart c) {
this.itemId=itemId; this.itemId = itemId;
this.itemTotal=total; this.itemTotal = total;
this.quantity=qty; this.quantity = qty;
this.cart=c; this.cart = c;
} }
public String getItemId() {
return itemId; public String getItemId() {
} return itemId;
public void setItemId(String itemId) { }
this.itemId = itemId;
} public void setItemId(String itemId) {
public double getItemTotal() { this.itemId = itemId;
return itemTotal; }
}
public void setItemTotal(double itemTotal) { public double getItemTotal() {
this.itemTotal = itemTotal; return itemTotal;
} }
public int getQuantity() {
return quantity; public void setItemTotal(double itemTotal) {
} this.itemTotal = itemTotal;
public void setQuantity(int quantity) { }
this.quantity = quantity;
} public int getQuantity() {
public Cart getCart() { return quantity;
return cart; }
}
public void setCart(Cart cart) { public void setQuantity(int quantity) {
this.cart = cart; this.quantity = quantity;
} }
public long getId() {
return id; public Cart getCart() {
} return cart;
public void setId(long id) { }
this.id = id;
} public void setCart(Cart cart) {
this.cart = cart;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
} }

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

@ -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,40 +1,97 @@
package com.baeldung.hibernate.oneToMany.main; package com.baeldung.hibernate.oneToMany.main;
import org.junit.After; import static org.junit.Assert.assertNotNull;
import org.junit.AfterClass; import static org.junit.Assert.assertNull;
import java.util.HashSet;
import java.util.Set;
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;
import static org.junit.Assert.*;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Items;
//@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateOneToManyAnnotationMainTest { public class HibernateOneToManyAnnotationMainTest {
private static SessionFactory sessionFactory;
private Session session;
public HibernateOneToManyAnnotationMainTest() { public HibernateOneToManyAnnotationMainTest() {
} }
@BeforeClass @BeforeClass
public static void setUpClass() { 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")
@AfterClass .setProperty("hibernate.connection.password", "").setProperty("hibernate.hbm2ddl.auto", "update");
public static void tearDownClass() { 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 givenSession_checkIfDatabaseIsEmpty() {
System.out.println("main"); Cart cart = (Cart) session.get(Cart.class, new Long(1));
String[] args = null; assertNull(cart);
HibernateOneToManyAnnotationMain.main(args);
fail("The test failed."); }
@Test
public void testAddItemsToCart() {
Cart cart = new Cart();
Set<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
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 givenSession_checkIfDatabaseIsPopulated_afterCommit() {
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();
cart = (Cart) session.get(Cart.class, new Long(1));
assertNotNull(cart);
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

@ -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,82 @@
package com.baeldung.excel;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@Service
public class JExcelHelper {
public Map<Integer, ArrayList<String>> readJExcel(String fileLocation) throws IOException, BiffException {
Map<Integer, ArrayList<String>> data = new HashMap<>();
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<>());
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>