commit
						681d8c49f8
					
				
							
								
								
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @ -27,3 +27,5 @@ target/ | ||||
| 
 | ||||
| spring-openid/src/main/resources/application.properties | ||||
| .recommenders/ | ||||
| /spring-hibernate4/nbproject/ | ||||
| spring-security-openid/src/main/resources/application.properties | ||||
|  | ||||
| @ -18,9 +18,7 @@ public class Dijkstra { | ||||
|         while (unsettledNodes.size() != 0) { | ||||
|             Node currentNode = getLowestDistanceNode(unsettledNodes); | ||||
|             unsettledNodes.remove(currentNode); | ||||
|             for (Entry<Node, Integer> adjacencyPair : currentNode | ||||
|               .getAdjacentNodes() | ||||
|               .entrySet()) { | ||||
|             for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) { | ||||
|                 Node adjacentNode = adjacencyPair.getKey(); | ||||
|                 Integer edgeWeigh = adjacencyPair.getValue(); | ||||
| 
 | ||||
|  | ||||
| @ -55,29 +55,19 @@ public class DijkstraAlgorithmTest { | ||||
|         for (Node node : graph.getNodes()) { | ||||
|             switch (node.getName()) { | ||||
|             case "B": | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeB)); | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeB)); | ||||
|                 break; | ||||
|             case "C": | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeC)); | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeC)); | ||||
|                 break; | ||||
|             case "D": | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeD)); | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeD)); | ||||
|                 break; | ||||
|             case "E": | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeE)); | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeE)); | ||||
|                 break; | ||||
|             case "F": | ||||
|                 assertTrue(node | ||||
|                   .getShortestPath() | ||||
|                   .equals(shortestPathForNodeF)); | ||||
|                 assertTrue(node.getShortestPath().equals(shortestPathForNodeF)); | ||||
|                 break; | ||||
|             } | ||||
|         } | ||||
|  | ||||
| @ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor { | ||||
| 
 | ||||
|             Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation); | ||||
| 
 | ||||
|             Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream() | ||||
|                     .collect(Collectors.partitioningBy(element -> | ||||
|                             ((ExecutableType) element.asType()).getParameterTypes().size() == 1 | ||||
|                                     && element.getSimpleName().toString().startsWith("set"))); | ||||
|             Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set"))); | ||||
| 
 | ||||
|             List<Element> setters = annotatedMethods.get(true); | ||||
|             List<Element> otherMethods = annotatedMethods.get(false); | ||||
| 
 | ||||
|             otherMethods.forEach(element -> | ||||
|                     processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, | ||||
|                             "@BuilderProperty must be applied to a setXxx method with a single argument", element)); | ||||
|             otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element)); | ||||
| 
 | ||||
|             if (setters.isEmpty()) { | ||||
|                 continue; | ||||
| @ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor { | ||||
| 
 | ||||
|             String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString(); | ||||
| 
 | ||||
|             Map<String, String> setterMap = setters.stream().collect(Collectors.toMap( | ||||
|                     setter -> setter.getSimpleName().toString(), | ||||
|                     setter -> ((ExecutableType) setter.asType()) | ||||
|                             .getParameterTypes().get(0).toString() | ||||
|             )); | ||||
|             Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString())); | ||||
| 
 | ||||
|             try { | ||||
|                 writeBuilderFile(className, setterMap); | ||||
|  | ||||
| @ -9,10 +9,7 @@ public class PersonBuilderTest { | ||||
|     @Test | ||||
|     public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() { | ||||
| 
 | ||||
|         Person person = new PersonBuilder() | ||||
|                 .setAge(25) | ||||
|                 .setName("John") | ||||
|                 .build(); | ||||
|         Person person = new PersonBuilder().setAge(25).setName("John").build(); | ||||
| 
 | ||||
|         assertEquals(25, person.getAge()); | ||||
|         assertEquals("John", person.getName()); | ||||
|  | ||||
| @ -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
											
										
									
								
							| @ -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
									
								
							
							
						
						
									
										68
									
								
								apache-thrift/pom.xml
									
									
									
									
									
										Normal 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> | ||||
| @ -0,0 +1,9 @@ | ||||
| package com.baeldung.thrift; | ||||
| 
 | ||||
| public class Application { | ||||
| 
 | ||||
|     public static void main(String[] args) { | ||||
|         CrossPlatformServiceServer server = new CrossPlatformServiceServer(); | ||||
|         server.start(); | ||||
|     } | ||||
| } | ||||
| @ -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; | ||||
|     } | ||||
| } | ||||
| @ -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; | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,39 @@ | ||||
| package com.baeldung.thrift; | ||||
| 
 | ||||
| import com.baeldung.thrift.impl.CrossPlatformService; | ||||
| 
 | ||||
| import org.apache.thrift.server.TServer; | ||||
| import org.apache.thrift.server.TSimpleServer; | ||||
| import org.apache.thrift.transport.TServerSocket; | ||||
| import org.apache.thrift.transport.TServerTransport; | ||||
| 
 | ||||
| public class CrossPlatformServiceServer { | ||||
| 
 | ||||
|     private TServer server; | ||||
| 
 | ||||
|     public void start() { | ||||
|         try { | ||||
|             TServerTransport serverTransport = new TServerSocket(9090); | ||||
|             server = new TSimpleServer(new TServer.Args(serverTransport) | ||||
|                 .processor(new CrossPlatformService.Processor<>(new CrossPlatformServiceImpl()))); | ||||
| 
 | ||||
|             System.out.print("Starting the server... "); | ||||
| 
 | ||||
|             server.serve(); | ||||
| 
 | ||||
|             System.out.println("done."); | ||||
|         } catch (Exception e) { | ||||
|             e.printStackTrace(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     public void stop() { | ||||
|         if (server != null && server.isServing()) { | ||||
|             System.out.print("Stopping the server... "); | ||||
| 
 | ||||
|             server.stop(); | ||||
| 
 | ||||
|             System.out.println("done."); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -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) | ||||
| } | ||||
| @ -0,0 +1,33 @@ | ||||
| package com.baeldung.thrift; | ||||
| 
 | ||||
| import org.junit.After; | ||||
| import org.junit.Assert; | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class CrossPlatformServiceTest { | ||||
| 
 | ||||
|     private CrossPlatformServiceServer server = new CrossPlatformServiceServer(); | ||||
| 
 | ||||
|     @Before | ||||
|     public void setUp() { | ||||
|         new Thread(() -> server.start()).start(); | ||||
|         try { | ||||
|             // wait for the server start up | ||||
|             Thread.sleep(1000); | ||||
|         } catch (InterruptedException e) { | ||||
|             e.printStackTrace(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     @After | ||||
|     public void tearDown() { | ||||
|         server.stop(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void ping() { | ||||
|         CrossPlatformServiceClient client = new CrossPlatformServiceClient(); | ||||
|         Assert.assertTrue(client.ping()); | ||||
|     } | ||||
| } | ||||
| @ -38,8 +38,7 @@ public class AssertJCoreTest { | ||||
|     public void whenCheckingForElement_thenContains() throws Exception { | ||||
|         List<String> list = Arrays.asList("1", "2", "3"); | ||||
| 
 | ||||
|         assertThat(list) | ||||
|                 .contains("1"); | ||||
|         assertThat(list).contains("1"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -50,12 +49,7 @@ public class AssertJCoreTest { | ||||
|         assertThat(list).startsWith("1"); | ||||
|         assertThat(list).doesNotContainNull(); | ||||
| 
 | ||||
|         assertThat(list) | ||||
|                 .isNotEmpty() | ||||
|                 .contains("1") | ||||
|                 .startsWith("1") | ||||
|                 .doesNotContainNull() | ||||
|                 .containsSequence("2", "3"); | ||||
|         assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -67,11 +61,7 @@ public class AssertJCoreTest { | ||||
|     public void whenCheckingCharacter_thenIsUnicode() throws Exception { | ||||
|         char someCharacter = 'c'; | ||||
| 
 | ||||
|         assertThat(someCharacter) | ||||
|                 .isNotEqualTo('a') | ||||
|                 .inUnicode() | ||||
|                 .isGreaterThanOrEqualTo('b') | ||||
|                 .isLowerCase(); | ||||
|         assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -94,11 +84,7 @@ public class AssertJCoreTest { | ||||
|         final File someFile = File.createTempFile("aaa", "bbb"); | ||||
|         someFile.deleteOnExit(); | ||||
| 
 | ||||
|         assertThat(someFile) | ||||
|                 .exists() | ||||
|                 .isFile() | ||||
|                 .canRead() | ||||
|                 .canWrite(); | ||||
|         assertThat(someFile).exists().isFile().canRead().canWrite(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -113,20 +99,14 @@ public class AssertJCoreTest { | ||||
|     public void whenGivenMap_then() throws Exception { | ||||
|         Map<Integer, String> map = Maps.newHashMap(2, "a"); | ||||
| 
 | ||||
|         assertThat(map) | ||||
|                 .isNotEmpty() | ||||
|                 .containsKey(2) | ||||
|                 .doesNotContainKeys(10) | ||||
|                 .contains(entry(2, "a")); | ||||
|         assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGivenException_then() throws Exception { | ||||
|         Exception ex = new Exception("abc"); | ||||
| 
 | ||||
|         assertThat(ex) | ||||
|                 .hasNoCause() | ||||
|                 .hasMessageEndingWith("c"); | ||||
|         assertThat(ex).hasNoCause().hasMessageEndingWith("c"); | ||||
|     } | ||||
| 
 | ||||
|     @Ignore // IN ORDER TO TEST, REMOVE THIS LINE | ||||
| @ -134,8 +114,6 @@ public class AssertJCoreTest { | ||||
|     public void whenRunningAssertion_thenDescribed() throws Exception { | ||||
|         Person person = new Person("Alex", 34); | ||||
| 
 | ||||
|         assertThat(person.getAge()) | ||||
|                 .as("%s's age should be equal to 100") | ||||
|                 .isEqualTo(100); | ||||
|         assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -26,9 +26,7 @@ public class AssertJGuavaTest { | ||||
|         final File temp1 = File.createTempFile("bael", "dung1"); | ||||
|         final File temp2 = File.createTempFile("bael", "dung2"); | ||||
| 
 | ||||
|         assertThat(Files.asByteSource(temp1)) | ||||
|                 .hasSize(0) | ||||
|                 .hasSameContentAs(Files.asByteSource(temp2)); | ||||
|         assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -37,11 +35,7 @@ public class AssertJGuavaTest { | ||||
|         mmap.put(1, "one"); | ||||
|         mmap.put(1, "1"); | ||||
| 
 | ||||
|         assertThat(mmap) | ||||
|                 .hasSize(2) | ||||
|                 .containsKeys(1) | ||||
|                 .contains(entry(1, "one")) | ||||
|                 .contains(entry(1, "1")); | ||||
|         assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -62,31 +56,21 @@ public class AssertJGuavaTest { | ||||
|         mmap2.put(1, "one"); | ||||
|         mmap2.put(1, "1"); | ||||
| 
 | ||||
|         assertThat(mmap1) | ||||
|                 .containsAllEntriesOf(mmap2) | ||||
|                 .containsAllEntriesOf(mmap1_clone) | ||||
|                 .hasSameEntriesAs(mmap1_clone); | ||||
|         assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception { | ||||
|         final Optional<String> something = Optional.of("something"); | ||||
| 
 | ||||
|         assertThat(something) | ||||
|                 .isPresent() | ||||
|                 .extractingValue() | ||||
|                 .isEqualTo("something"); | ||||
|         assertThat(something).isPresent().extractingValue().isEqualTo("something"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception { | ||||
|         final Range<String> range = Range.openClosed("a", "g"); | ||||
| 
 | ||||
|         assertThat(range) | ||||
|                 .hasOpenedLowerBound() | ||||
|                 .isNotEmpty() | ||||
|                 .hasClosedUpperBound() | ||||
|                 .contains("b"); | ||||
|         assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -96,10 +80,7 @@ public class AssertJGuavaTest { | ||||
|         map.put(Range.closed(0, 60), "F"); | ||||
|         map.put(Range.closed(61, 70), "D"); | ||||
| 
 | ||||
|         assertThat(map) | ||||
|                 .isNotEmpty() | ||||
|                 .containsKeys(0) | ||||
|                 .contains(MapEntry.entry(34, "F")); | ||||
|         assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -109,13 +90,7 @@ public class AssertJGuavaTest { | ||||
|         table.put(1, "A", "PRESENT"); | ||||
|         table.put(1, "B", "ABSENT"); | ||||
| 
 | ||||
|         assertThat(table) | ||||
|                 .hasRowCount(1) | ||||
|                 .containsValues("ABSENT") | ||||
|                 .containsCell(1, "B", "ABSENT"); | ||||
|         assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT"); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -20,20 +20,14 @@ public class AssertJJava8Test { | ||||
|     public void givenOptional_shouldAssert() throws Exception { | ||||
|         final Optional<String> givenOptional = Optional.of("something"); | ||||
| 
 | ||||
|         assertThat(givenOptional) | ||||
|           .isPresent() | ||||
|           .hasValue("something"); | ||||
|         assertThat(givenOptional).isPresent().hasValue("something"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenPredicate_shouldAssert() throws Exception { | ||||
|         final Predicate<String> predicate = s -> s.length() > 4; | ||||
| 
 | ||||
|         assertThat(predicate) | ||||
|           .accepts("aaaaa", "bbbbb") | ||||
|           .rejects("a", "b") | ||||
|           .acceptsAll(asList("aaaaa", "bbbbb")) | ||||
|           .rejectsAll(asList("a", "b")); | ||||
|         assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
| @ -41,74 +35,58 @@ public class AssertJJava8Test { | ||||
|         final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8); | ||||
|         final LocalDate todayDate = LocalDate.now(); | ||||
| 
 | ||||
|         assertThat(givenLocalDate) | ||||
|           .isBefore(LocalDate.of(2020, 7, 8)) | ||||
|           .isAfterOrEqualTo(LocalDate.of(1989, 7, 8)); | ||||
|         assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8)); | ||||
| 
 | ||||
|         assertThat(todayDate) | ||||
|           .isAfter(LocalDate.of(1989, 7, 8)) | ||||
|           .isToday(); | ||||
|         assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalDateTime_shouldAssert() throws Exception { | ||||
|         final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0); | ||||
| 
 | ||||
|         assertThat(givenLocalDate) | ||||
|           .isBefore(LocalDateTime.of(2020, 7, 8, 11, 2)); | ||||
|         assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenLocalTime_shouldAssert() throws Exception { | ||||
|         final LocalTime givenLocalTime = LocalTime.of(12, 15); | ||||
| 
 | ||||
|         assertThat(givenLocalTime) | ||||
|           .isAfter(LocalTime.of(1, 0)) | ||||
|           .hasSameHourAs(LocalTime.of(12, 0)); | ||||
|         assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenList_shouldAssertFlatExtracting() throws Exception { | ||||
|         final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); | ||||
| 
 | ||||
|         assertThat(givenList) | ||||
|           .flatExtracting(LocalDate::getYear) | ||||
|           .contains(2015); | ||||
|         assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception { | ||||
|         final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); | ||||
| 
 | ||||
|         assertThat(givenList) | ||||
|           .flatExtracting(LocalDate::isLeapYear) | ||||
|           .contains(true); | ||||
|         assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenList_shouldAssertFlatExtractingClass() throws Exception { | ||||
|         final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); | ||||
| 
 | ||||
|         assertThat(givenList) | ||||
|           .flatExtracting(Object::getClass) | ||||
|           .contains(LocalDate.class); | ||||
|         assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenList_shouldAssertMultipleFlatExtracting() throws Exception { | ||||
|         final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6)); | ||||
| 
 | ||||
|         assertThat(givenList) | ||||
|           .flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth) | ||||
|           .contains(2015, 6); | ||||
|         assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenString_shouldSatisfy() throws Exception { | ||||
|         final String givenString = "someString"; | ||||
| 
 | ||||
|         assertThat(givenString) | ||||
|           .satisfies(s -> { | ||||
|         assertThat(givenString).satisfies(s -> { | ||||
|             assertThat(s).isNotEmpty(); | ||||
|             assertThat(s).hasSize(10); | ||||
|         }); | ||||
| @ -118,15 +96,13 @@ public class AssertJJava8Test { | ||||
|     public void givenString_shouldMatch() throws Exception { | ||||
|         final String emptyString = ""; | ||||
| 
 | ||||
|         assertThat(emptyString) | ||||
|           .matches(String::isEmpty); | ||||
|         assertThat(emptyString).matches(String::isEmpty); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception { | ||||
|         final List<String> givenList = Arrays.asList(""); | ||||
| 
 | ||||
|         assertThat(givenList) | ||||
|           .hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); | ||||
|         assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty()); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -1,18 +1,20 @@ | ||||
| package com.baeldung.autovalue; | ||||
| 
 | ||||
| public final class ImmutableMoney { | ||||
|     private final long amount; | ||||
|     private final String currency; | ||||
| 
 | ||||
|     public ImmutableMoney(long amount, String currency) { | ||||
|         this.amount = amount; | ||||
|         this.currency = currency; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public int hashCode() { | ||||
|         final int prime = 31; | ||||
|         int result = 1; | ||||
|         result = prime * result + (int) (amount ^ (amount >>> 32)); | ||||
| 		result = prime * result | ||||
| 				+ ((currency == null) ? 0 : currency.hashCode()); | ||||
|         result = prime * result + ((currency == null) ? 0 : currency.hashCode()); | ||||
|         return result; | ||||
|     } | ||||
| 
 | ||||
| @ -45,8 +47,7 @@ public final class ImmutableMoney { | ||||
| 
 | ||||
|     @Override | ||||
|     public String toString() { | ||||
| 		return "ImmutableMoney [amount=" + amount + ", currency=" + currency | ||||
| 				+ "]"; | ||||
|         return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]"; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -3,8 +3,7 @@ package com.baeldung.autovalue; | ||||
| public class MutableMoney { | ||||
|     @Override | ||||
|     public String toString() { | ||||
| 		return "MutableMoney [amount=" + amount + ", currency=" + currency | ||||
| 				+ "]"; | ||||
|         return "MutableMoney [amount=" + amount + ", currency=" + currency + "]"; | ||||
|     } | ||||
| 
 | ||||
|     public long getAmount() { | ||||
|  | ||||
| @ -32,24 +32,28 @@ public class MoneyUnitTest { | ||||
|         AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); | ||||
|         assertTrue(m1.equals(m2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() { | ||||
|         AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000); | ||||
|         AutoValueMoney m2 = AutoValueMoney.create("USD", 5000); | ||||
|         assertFalse(m1.equals(m2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() { | ||||
|         AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); | ||||
|         AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); | ||||
|         assertTrue(m1.equals(m2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() { | ||||
|         AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); | ||||
|         AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build(); | ||||
|         assertFalse(m1.equals(m2)); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() { | ||||
|         AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build(); | ||||
|  | ||||
| @ -57,7 +57,6 @@ | ||||
|                 <configuration> | ||||
|                     <source>1.9</source> | ||||
|                     <target>1.9</target> | ||||
|                     <verbose>true</verbose> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
| 
 | ||||
| @ -72,6 +71,9 @@ | ||||
|     </build> | ||||
| 
 | ||||
|     <properties> | ||||
|         <!-- project build encoding --> | ||||
|         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | ||||
|      | ||||
|         <!-- logging --> | ||||
|         <org.slf4j.version>1.7.21</org.slf4j.version> | ||||
| 
 | ||||
|  | ||||
| @ -8,7 +8,6 @@ import java.time.Duration; | ||||
| import java.time.Instant; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| 
 | ||||
| public class ProcessUtils { | ||||
| 
 | ||||
|     public static String getClassPath() { | ||||
|  | ||||
| @ -8,7 +8,6 @@ public class ServiceMain { | ||||
|         ProcessHandle thisProcess = ProcessHandle.current(); | ||||
|         long pid = thisProcess.getPid(); | ||||
| 
 | ||||
|          | ||||
|         Optional<String[]> opArgs = Optional.ofNullable(args); | ||||
|         String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command")); | ||||
| 
 | ||||
|  | ||||
| @ -19,10 +19,7 @@ public class Java9OptionalsStreamTest { | ||||
|     public void filterOutPresentOptionalsWithFilter() { | ||||
|         assertEquals(4, listOfOptionals.size()); | ||||
| 
 | ||||
|         List<String> filteredList = listOfOptionals.stream() | ||||
|           .filter(Optional::isPresent) | ||||
|           .map(Optional::get) | ||||
|           .collect(Collectors.toList()); | ||||
|         List<String> filteredList = listOfOptionals.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); | ||||
| 
 | ||||
|         assertEquals(2, filteredList.size()); | ||||
|         assertEquals("foo", filteredList.get(0)); | ||||
| @ -33,9 +30,7 @@ public class Java9OptionalsStreamTest { | ||||
|     public void filterOutPresentOptionalsWithFlatMap() { | ||||
|         assertEquals(4, listOfOptionals.size()); | ||||
| 
 | ||||
|         List<String> filteredList = listOfOptionals.stream() | ||||
|           .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) | ||||
|           .collect(Collectors.toList()); | ||||
|         List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()).collect(Collectors.toList()); | ||||
|         assertEquals(2, filteredList.size()); | ||||
| 
 | ||||
|         assertEquals("foo", filteredList.get(0)); | ||||
| @ -46,9 +41,7 @@ public class Java9OptionalsStreamTest { | ||||
|     public void filterOutPresentOptionalsWithFlatMap2() { | ||||
|         assertEquals(4, listOfOptionals.size()); | ||||
| 
 | ||||
|         List<String> filteredList = listOfOptionals.stream() | ||||
|           .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) | ||||
|           .collect(Collectors.toList()); | ||||
|         List<String> filteredList = listOfOptionals.stream().flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)).collect(Collectors.toList()); | ||||
|         assertEquals(2, filteredList.size()); | ||||
| 
 | ||||
|         assertEquals("foo", filteredList.get(0)); | ||||
| @ -59,9 +52,7 @@ public class Java9OptionalsStreamTest { | ||||
|     public void filterOutPresentOptionalsWithJava9() { | ||||
|         assertEquals(4, listOfOptionals.size()); | ||||
| 
 | ||||
|         List<String> filteredList = listOfOptionals.stream() | ||||
|           .flatMap(Optional::stream) | ||||
|           .collect(Collectors.toList()); | ||||
|         List<String> filteredList = listOfOptionals.stream().flatMap(Optional::stream).collect(Collectors.toList()); | ||||
| 
 | ||||
|         assertEquals(2, filteredList.size()); | ||||
|         assertEquals("foo", filteredList.get(0)); | ||||
|  | ||||
| @ -13,7 +13,6 @@ import org.junit.Test; | ||||
| 
 | ||||
| public class MultiResultionImageTest { | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void baseMultiResImageTest() { | ||||
|         int baseIndex = 1; | ||||
| @ -38,10 +37,8 @@ public class MultiResultionImageTest { | ||||
|         return 8 * (i + 1); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     private static BufferedImage createImage(int i) { | ||||
|         return new BufferedImage(getSize(i), getSize(i), | ||||
|                 BufferedImage.TYPE_INT_RGB); | ||||
|         return new BufferedImage(getSize(i), getSize(i), BufferedImage.TYPE_INT_RGB); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
|  | ||||
| @ -1,7 +1,5 @@ | ||||
| package com.baeldung.java9.httpclient; | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
| import static java.net.HttpURLConnection.HTTP_OK; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| @ -117,7 +115,9 @@ public class SimpleHttpRequestsTest { | ||||
|             sb.append(k).append(":"); | ||||
|             List<String> l = hMap.get(k); | ||||
|             if (l != null) { | ||||
|                l.forEach( s -> { sb.append(s).append(","); } ); | ||||
|                 l.forEach(s -> { | ||||
|                     sb.append(s).append(","); | ||||
|                 }); | ||||
|             } | ||||
|             sb.append("\n"); | ||||
|         } | ||||
|  | ||||
| @ -57,7 +57,6 @@ public class TryWithResourcesTest { | ||||
|         assertEquals("Expected and Actual does not match", 5, closeCount); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     static class CloseableException extends Exception implements AutoCloseable { | ||||
|         @Override | ||||
|         public void close() { | ||||
| @ -66,5 +65,3 @@ public class TryWithResourcesTest { | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| 
 | ||||
| 
 | ||||
|  | ||||
| @ -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)); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -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); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -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()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,61 @@ | ||||
| package com.baeldung.java9.language.stream; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.*; | ||||
| import java.util.stream.Collectors; | ||||
| import java.util.function.Function; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| public class CollectorImprovementTest { | ||||
|     @Test | ||||
|     public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() { | ||||
|         List<Integer> numbers = List.of(1, 2, 3, 5, 5); | ||||
| 
 | ||||
|         Map<Integer, Long> result = numbers.stream().filter(val -> val > 3).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); | ||||
| 
 | ||||
|         assertEquals(1, result.size()); | ||||
| 
 | ||||
|         result = numbers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.filtering(val -> val > 3, Collectors.counting()))); | ||||
| 
 | ||||
|         assertEquals(4, result.size()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() { | ||||
|         Blog blog1 = new Blog("1", "Nice", "Very Nice"); | ||||
|         Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better"); | ||||
|         List<Blog> blogs = List.of(blog1, blog2); | ||||
| 
 | ||||
|         Map<String, List<List<String>>> authorComments1 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.mapping(Blog::getComments, Collectors.toList()))); | ||||
| 
 | ||||
|         assertEquals(2, authorComments1.size()); | ||||
|         assertEquals(2, authorComments1.get("1").get(0).size()); | ||||
|         assertEquals(3, authorComments1.get("2").get(0).size()); | ||||
| 
 | ||||
|         Map<String, List<String>> authorComments2 = blogs.stream().collect(Collectors.groupingBy(Blog::getAuthorName, Collectors.flatMapping(blog -> blog.getComments().stream(), Collectors.toList()))); | ||||
| 
 | ||||
|         assertEquals(2, authorComments2.size()); | ||||
|         assertEquals(2, authorComments2.get("1").size()); | ||||
|         assertEquals(3, authorComments2.get("2").size()); | ||||
|     } | ||||
| } | ||||
| 
 | ||||
| class Blog { | ||||
|     private String authorName; | ||||
|     private List<String> comments; | ||||
| 
 | ||||
|     public Blog(String authorName, String... comments) { | ||||
|         this.authorName = authorName; | ||||
|         this.comments = List.of(comments); | ||||
|     } | ||||
| 
 | ||||
|     public String getAuthorName() { | ||||
|         return this.authorName; | ||||
|     } | ||||
| 
 | ||||
|     public List<String> getComments() { | ||||
|         return this.comments; | ||||
|     } | ||||
| } | ||||
| @ -17,16 +17,11 @@ public class StreamFeaturesTest { | ||||
|     public static class TakeAndDropWhileTest { | ||||
| 
 | ||||
|         public Stream<String> getStreamAfterTakeWhileOperation() { | ||||
|             return Stream | ||||
|                     .iterate("", s -> s + "s") | ||||
|                     .takeWhile(s -> s.length() < 10); | ||||
|             return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10); | ||||
|         } | ||||
| 
 | ||||
|         public Stream<String> getStreamAfterDropWhileOperation() { | ||||
|             return Stream | ||||
|                     .iterate("", s -> s + "s") | ||||
|                     .takeWhile(s -> s.length() < 10) | ||||
|                     .dropWhile(s -> !s.contains("sssss")); | ||||
|             return Stream.iterate("", s -> s + "s").takeWhile(s -> s.length() < 10).dropWhile(s -> !s.contains("sssss")); | ||||
|         } | ||||
| 
 | ||||
|         @Test | ||||
| @ -75,19 +70,19 @@ public class StreamFeaturesTest { | ||||
|     public static class OfNullableTest { | ||||
| 
 | ||||
|         private List<String> collection = Arrays.asList("A", "B", "C"); | ||||
|         private Map<String, Integer> map = new HashMap<>() {{ | ||||
|         private Map<String, Integer> map = new HashMap<>() { | ||||
|             { | ||||
|                 put("A", 10); | ||||
|                 put("C", 30); | ||||
|         }}; | ||||
|             } | ||||
|         }; | ||||
| 
 | ||||
|         private Stream<Integer> getStreamWithOfNullable() { | ||||
|             return collection.stream() | ||||
|                     .flatMap(s -> Stream.ofNullable(map.get(s))); | ||||
|             return collection.stream().flatMap(s -> Stream.ofNullable(map.get(s))); | ||||
|         } | ||||
| 
 | ||||
|         private Stream<Integer> getStream() { | ||||
|             return collection.stream() | ||||
|                             .flatMap(s -> { | ||||
|             return collection.stream().flatMap(s -> { | ||||
|                 Integer temp = map.get(s); | ||||
|                 return temp != null ? Stream.of(temp) : Stream.empty(); | ||||
|             }); | ||||
| @ -107,10 +102,7 @@ public class StreamFeaturesTest { | ||||
|         @Test | ||||
|         public void testOfNullable() { | ||||
| 
 | ||||
|             assertEquals( | ||||
|                     testOfNullableFrom(getStream()), | ||||
|                     testOfNullableFrom(getStreamWithOfNullable()) | ||||
|             ); | ||||
|             assertEquals(testOfNullableFrom(getStream()), testOfNullableFrom(getStreamWithOfNullable())); | ||||
| 
 | ||||
|         } | ||||
| 
 | ||||
|  | ||||
| @ -22,7 +22,6 @@ import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class ProcessApi { | ||||
| 
 | ||||
| 
 | ||||
|     @Before | ||||
|     public void init() { | ||||
| 
 | ||||
|  | ||||
| @ -54,3 +54,6 @@ | ||||
| - [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) | ||||
| - [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) | ||||
|  | ||||
| @ -64,11 +64,6 @@ | ||||
|             <version>${grep4j.version}</version> | ||||
|         </dependency> | ||||
|          | ||||
|         <dependency> | ||||
|             <groupId>com.lmax</groupId> | ||||
|             <artifactId>disruptor</artifactId> | ||||
|             <version>${disruptor.version}</version> | ||||
|         </dependency> | ||||
|         <!-- web --> | ||||
| 
 | ||||
|         <!-- marshalling --> | ||||
| @ -369,7 +364,6 @@ | ||||
|         <unix4j.version>0.4</unix4j.version> | ||||
|         <grep4j.version>1.8.7</grep4j.version> | ||||
|         <lombok.version>1.16.12</lombok.version> | ||||
|         <disruptor.version>3.3.6</disruptor.version> | ||||
| 
 | ||||
|         <!-- testing --> | ||||
|         <org.hamcrest.version>1.3</org.hamcrest.version> | ||||
|  | ||||
| @ -15,8 +15,7 @@ public class RunAlgorithm { | ||||
|         int decision = in.nextInt(); | ||||
|         switch (decision) { | ||||
|         case 1: | ||||
| 			System.out.println( | ||||
| 					"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); | ||||
|             System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995)); | ||||
|             break; | ||||
|         case 2: | ||||
|             SlopeOne.slopeOne(3); | ||||
|  | ||||
| @ -12,8 +12,7 @@ import lombok.Data; | ||||
| @Data | ||||
| public class InputData { | ||||
| 
 | ||||
| 	protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), | ||||
| 			new Item("Snacks")); | ||||
|     protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks")); | ||||
| 
 | ||||
|     public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) { | ||||
|         Map<User, HashMap<Item, Double>> data = new HashMap<>(); | ||||
|  | ||||
| @ -23,8 +23,7 @@ public class LogWithChain { | ||||
|         try { | ||||
|             howIsManager(); | ||||
|         } catch (ManagerUpsetException e) { | ||||
|             throw new TeamLeadUpsetException( | ||||
|                     "Team lead is not in good mood", e); | ||||
|             throw new TeamLeadUpsetException("Team lead is not in good mood", e); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -36,9 +35,7 @@ public class LogWithChain { | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private static void howIsGirlFriendOfManager() | ||||
|             throws GirlFriendOfManagerUpsetException { | ||||
|         throw new GirlFriendOfManagerUpsetException( | ||||
|                 "Girl friend of manager is in bad mood"); | ||||
|     private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException { | ||||
|         throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -25,8 +25,7 @@ public class LogWithoutChain { | ||||
|             howIsManager(); | ||||
|         } catch (ManagerUpsetException e) { | ||||
|             e.printStackTrace(); | ||||
|             throw new TeamLeadUpsetException( | ||||
|                     "Team lead is not in good mood"); | ||||
|             throw new TeamLeadUpsetException("Team lead is not in good mood"); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| @ -39,9 +38,7 @@ public class LogWithoutChain { | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private static void howIsGirlFriendOfManager() | ||||
|             throws GirlFriendOfManagerUpsetException { | ||||
|         throw new GirlFriendOfManagerUpsetException( | ||||
|                 "Girl friend of manager is in bad mood"); | ||||
|     private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException { | ||||
|         throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood"); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -0,0 +1,24 @@ | ||||
| package com.baeldung.concurrent.blockingqueue; | ||||
| 
 | ||||
| import java.util.concurrent.BlockingQueue; | ||||
| import java.util.concurrent.LinkedBlockingQueue; | ||||
| 
 | ||||
| public class BlockingQueueUsage { | ||||
|     public static void main(String[] args) { | ||||
|         int BOUND = 10; | ||||
|         int N_PRODUCERS = 4; | ||||
|         int N_CONSUMERS = Runtime.getRuntime().availableProcessors(); | ||||
|         int poisonPill = Integer.MAX_VALUE; | ||||
|         int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS; | ||||
| 
 | ||||
|         BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(BOUND); | ||||
| 
 | ||||
|         for (int i = 0; i < N_PRODUCERS; i++) { | ||||
|             new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start(); | ||||
|         } | ||||
| 
 | ||||
|         for (int j = 0; j < N_CONSUMERS; j++) { | ||||
|             new Thread(new NumbersConsumer(queue, poisonPill)).start(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,28 @@ | ||||
| package com.baeldung.concurrent.blockingqueue; | ||||
| 
 | ||||
| import java.util.concurrent.BlockingQueue; | ||||
| 
 | ||||
| public class NumbersConsumer implements Runnable { | ||||
|     private final BlockingQueue<Integer> queue; | ||||
|     private final int poisonPill; | ||||
| 
 | ||||
|     public NumbersConsumer(BlockingQueue<Integer> queue, int poisonPill) { | ||||
|         this.queue = queue; | ||||
|         this.poisonPill = poisonPill; | ||||
|     } | ||||
| 
 | ||||
|     public void run() { | ||||
|         try { | ||||
|             while (true) { | ||||
|                 Integer number = queue.take(); | ||||
|                 if (number.equals(poisonPill)) { | ||||
|                     return; | ||||
|                 } | ||||
|                 String result = number.toString(); | ||||
|                 System.out.println(Thread.currentThread().getName() + " result: " + result); | ||||
|             } | ||||
|         } catch (InterruptedException e) { | ||||
|             Thread.currentThread().interrupt(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,34 @@ | ||||
| package com.baeldung.concurrent.blockingqueue; | ||||
| 
 | ||||
| import java.util.concurrent.BlockingQueue; | ||||
| import java.util.concurrent.ThreadLocalRandom; | ||||
| 
 | ||||
| public class NumbersProducer implements Runnable { | ||||
| 
 | ||||
|     private final BlockingQueue<Integer> numbersQueue; | ||||
|     private final int poisonPill; | ||||
|     private final int poisonPillPerProducer; | ||||
| 
 | ||||
|     public NumbersProducer(BlockingQueue<Integer> numbersQueue, int poisonPill, int poisonPillPerProducer) { | ||||
|         this.numbersQueue = numbersQueue; | ||||
|         this.poisonPill = poisonPill; | ||||
|         this.poisonPillPerProducer = poisonPillPerProducer; | ||||
|     } | ||||
| 
 | ||||
|     public void run() { | ||||
|         try { | ||||
|             generateNumbers(); | ||||
|         } catch (InterruptedException e) { | ||||
|             Thread.currentThread().interrupt(); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private void generateNumbers() throws InterruptedException { | ||||
|         for (int i = 0; i < 100; i++) { | ||||
|             numbersQueue.put(ThreadLocalRandom.current().nextInt(100)); | ||||
|         } | ||||
|         for (int j = 0; j < poisonPillPerProducer; j++) { | ||||
|             numbersQueue.put(poisonPill); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,23 @@ | ||||
| package com.baeldung.concurrent.countdownlatch; | ||||
| 
 | ||||
| import java.util.List; | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| 
 | ||||
| public class BrokenWorker implements Runnable { | ||||
|     private final List<String> outputScraper; | ||||
|     private final CountDownLatch countDownLatch; | ||||
| 
 | ||||
|     public BrokenWorker(final List<String> outputScraper, final CountDownLatch countDownLatch) { | ||||
|         this.outputScraper = outputScraper; | ||||
|         this.countDownLatch = countDownLatch; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void run() { | ||||
|         if (true) { | ||||
|             throw new RuntimeException("Oh dear"); | ||||
|         } | ||||
|         countDownLatch.countDown(); | ||||
|         outputScraper.add("Counted down"); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,34 @@ | ||||
| package com.baeldung.concurrent.countdownlatch; | ||||
| 
 | ||||
| import java.util.List; | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| 
 | ||||
| public class WaitingWorker implements Runnable { | ||||
| 
 | ||||
|     private final List<String> outputScraper; | ||||
|     private final CountDownLatch readyThreadCounter; | ||||
|     private final CountDownLatch callingThreadBlocker; | ||||
|     private final CountDownLatch completedThreadCounter; | ||||
| 
 | ||||
|     public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) { | ||||
| 
 | ||||
|         this.outputScraper = outputScraper; | ||||
|         this.readyThreadCounter = readyThreadCounter; | ||||
|         this.callingThreadBlocker = callingThreadBlocker; | ||||
|         this.completedThreadCounter = completedThreadCounter; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void run() { | ||||
|         // Mark this thread as read / started | ||||
|         readyThreadCounter.countDown(); | ||||
|         try { | ||||
|             callingThreadBlocker.await(); | ||||
|             outputScraper.add("Counted down"); | ||||
|         } catch (InterruptedException e) { | ||||
|             e.printStackTrace(); | ||||
|         } finally { | ||||
|             completedThreadCounter.countDown(); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,22 @@ | ||||
| package com.baeldung.concurrent.countdownlatch; | ||||
| 
 | ||||
| import java.util.List; | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| 
 | ||||
| public class Worker implements Runnable { | ||||
|     private final List<String> outputScraper; | ||||
|     private final CountDownLatch countDownLatch; | ||||
| 
 | ||||
|     public Worker(final List<String> outputScraper, final CountDownLatch countDownLatch) { | ||||
|         this.outputScraper = outputScraper; | ||||
|         this.countDownLatch = countDownLatch; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void run() { | ||||
|         // Do some work | ||||
|         System.out.println("Doing some logic"); | ||||
|         outputScraper.add("Counted down"); | ||||
|         countDownLatch.countDown(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,26 @@ | ||||
| package com.baeldung.concurrent.future; | ||||
| 
 | ||||
| import java.util.concurrent.RecursiveTask; | ||||
| 
 | ||||
| public class FactorialSquareCalculator extends RecursiveTask<Integer> { | ||||
|     private static final long serialVersionUID = 1L; | ||||
| 
 | ||||
|     final private Integer n; | ||||
| 
 | ||||
|     public FactorialSquareCalculator(Integer n) { | ||||
|         this.n = n; | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     protected Integer compute() { | ||||
|         if (n <= 1) { | ||||
|             return n; | ||||
|         } | ||||
| 
 | ||||
|         FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1); | ||||
| 
 | ||||
|         calculator.fork(); | ||||
| 
 | ||||
|         return n * n + calculator.join(); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,20 @@ | ||||
| package com.baeldung.concurrent.future; | ||||
| 
 | ||||
| import java.util.concurrent.ExecutorService; | ||||
| import java.util.concurrent.Future; | ||||
| 
 | ||||
| public class SquareCalculator { | ||||
| 
 | ||||
|     private final ExecutorService executor; | ||||
| 
 | ||||
|     public SquareCalculator(ExecutorService executor) { | ||||
|         this.executor = executor; | ||||
|     } | ||||
| 
 | ||||
|     public Future<Integer> calculate(Integer input) { | ||||
|         return executor.submit(() -> { | ||||
|             Thread.sleep(1000); | ||||
|             return input * input; | ||||
|         });         | ||||
|     } | ||||
| } | ||||
| @ -11,12 +11,10 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> { | ||||
|     private static final long serialVersionUID = 1L; | ||||
|     private static final int MAX_ENTRIES = 5; | ||||
| 
 | ||||
| 
 | ||||
|     public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { | ||||
|         super(initialCapacity, loadFactor, accessOrder); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     @Override | ||||
|     protected boolean removeEldestEntry(Map.Entry eldest) { | ||||
|         return size() > MAX_ENTRIES; | ||||
|  | ||||
| @ -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); | ||||
|     } | ||||
| } | ||||
| @ -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); | ||||
| } | ||||
| 
 | ||||
| } | ||||
| @ -42,116 +42,80 @@ public class Java8CollectorsUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToList_shouldCollectToList() throws Exception { | ||||
|         final List<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(toList()); | ||||
|         final List<String> result = givenList.stream().collect(toList()); | ||||
| 
 | ||||
|         assertThat(result).containsAll(givenList); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToList_shouldCollectToSet() throws Exception { | ||||
|         final Set<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(toSet()); | ||||
|         final Set<String> result = givenList.stream().collect(toSet()); | ||||
| 
 | ||||
|         assertThat(result).containsAll(givenList); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToCollection_shouldCollectToCollection() throws Exception { | ||||
|         final List<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(toCollection(LinkedList::new)); | ||||
|         final List<String> result = givenList.stream().collect(toCollection(LinkedList::new)); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsAll(givenList) | ||||
|           .isInstanceOf(LinkedList.class); | ||||
|         assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception { | ||||
|         assertThatThrownBy(() -> { | ||||
|             givenList | ||||
|               .stream() | ||||
|               .collect(toCollection(ImmutableList::of)); | ||||
|             givenList.stream().collect(toCollection(ImmutableList::of)); | ||||
|         }).isInstanceOf(UnsupportedOperationException.class); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToMap_shouldCollectToMap() throws Exception { | ||||
|         final Map<String, Integer> result = givenList | ||||
|           .stream() | ||||
|           .collect(toMap(Function.identity(), String::length)); | ||||
|         final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length)); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsEntry("a", 1) | ||||
|           .containsEntry("bb", 2) | ||||
|           .containsEntry("ccc", 3) | ||||
|           .containsEntry("dd", 2); | ||||
|         assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception { | ||||
|         final Map<String, Integer> result = givenList | ||||
|           .stream() | ||||
|           .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); | ||||
|         final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1)); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsEntry("a", 1) | ||||
|           .containsEntry("bb", 2) | ||||
|           .containsEntry("ccc", 3) | ||||
|           .containsEntry("dd", 2); | ||||
|         assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCollectingAndThen_shouldCollect() throws Exception { | ||||
|         final List<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(collectingAndThen(toList(), ImmutableList::copyOf)); | ||||
|         final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf)); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsAll(givenList) | ||||
|           .isInstanceOf(ImmutableList.class); | ||||
|         assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenJoining_shouldJoin() throws Exception { | ||||
|         final String result = givenList | ||||
|           .stream() | ||||
|           .collect(joining()); | ||||
|         final String result = givenList.stream().collect(joining()); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo("abbcccdd"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception { | ||||
|         final String result = givenList | ||||
|           .stream() | ||||
|           .collect(joining(" ")); | ||||
|         final String result = givenList.stream().collect(joining(" ")); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo("a bb ccc dd"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception { | ||||
|         final String result = givenList | ||||
|           .stream() | ||||
|           .collect(joining(" ", "PRE-", "-POST")); | ||||
|         final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST")); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo("PRE-a bb ccc dd-POST"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenPartitioningBy_shouldPartition() throws Exception { | ||||
|         final Map<Boolean, List<String>> result = givenList | ||||
|           .stream() | ||||
|           .collect(partitioningBy(s -> s.length() > 2)); | ||||
|         final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2)); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsKeys(true, false) | ||||
|           .satisfies(booleanListMap -> { | ||||
|         assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> { | ||||
|             assertThat(booleanListMap.get(true)).contains("ccc"); | ||||
| 
 | ||||
|             assertThat(booleanListMap.get(false)).contains("a", "bb", "dd"); | ||||
| @ -160,18 +124,14 @@ public class Java8CollectorsUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCounting_shouldCount() throws Exception { | ||||
|         final Long result = givenList | ||||
|           .stream() | ||||
|           .collect(counting()); | ||||
|         final Long result = givenList.stream().collect(counting()); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo(4); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSummarizing_shouldSummarize() throws Exception { | ||||
|         final DoubleSummaryStatistics result = givenList | ||||
|           .stream() | ||||
|           .collect(summarizingDouble(String::length)); | ||||
|         final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length)); | ||||
| 
 | ||||
|         assertThat(result.getAverage()).isEqualTo(2); | ||||
|         assertThat(result.getCount()).isEqualTo(4); | ||||
| @ -182,55 +142,37 @@ public class Java8CollectorsUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenAveraging_shouldAverage() throws Exception { | ||||
|         final Double result = givenList | ||||
|           .stream() | ||||
|           .collect(averagingDouble(String::length)); | ||||
|         final Double result = givenList.stream().collect(averagingDouble(String::length)); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo(2); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenSumming_shouldSum() throws Exception { | ||||
|         final Double result = givenList | ||||
|           .stream() | ||||
|           .filter(i -> true) | ||||
|           .collect(summingDouble(String::length)); | ||||
|         final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length)); | ||||
| 
 | ||||
|         assertThat(result).isEqualTo(8); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenMaxingBy_shouldMaxBy() throws Exception { | ||||
|         final Optional<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(maxBy(Comparator.naturalOrder())); | ||||
|         final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder())); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .isPresent() | ||||
|           .hasValue("dd"); | ||||
|         assertThat(result).isPresent().hasValue("dd"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenGroupingBy_shouldGroupBy() throws Exception { | ||||
|         final Map<Integer, Set<String>> result = givenList | ||||
|           .stream() | ||||
|           .collect(groupingBy(String::length, toSet())); | ||||
|         final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet())); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .containsEntry(1, newHashSet("a")) | ||||
|           .containsEntry(2, newHashSet("bb", "dd")) | ||||
|           .containsEntry(3, newHashSet("ccc")); | ||||
|         assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCreatingCustomCollector_shouldCollect() throws Exception { | ||||
|         final ImmutableSet<String> result = givenList | ||||
|           .stream() | ||||
|           .collect(toImmutableSet()); | ||||
|         final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet()); | ||||
| 
 | ||||
|         assertThat(result) | ||||
|           .isInstanceOf(ImmutableSet.class) | ||||
|           .contains("a", "bb", "ccc", "dd"); | ||||
|         assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd"); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -0,0 +1,70 @@ | ||||
| package com.baeldung.concurrent.countdownlatch; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
| import java.util.concurrent.CountDownLatch; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.stream.Stream; | ||||
| 
 | ||||
| import static java.util.stream.Collectors.toList; | ||||
| import static org.assertj.core.api.Assertions.assertThat; | ||||
| 
 | ||||
| public class CountdownLatchExampleTest { | ||||
|     @Test | ||||
|     public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException { | ||||
|         // Given | ||||
|         List<String> outputScraper = Collections.synchronizedList(new ArrayList<>()); | ||||
|         CountDownLatch countDownLatch = new CountDownLatch(5); | ||||
|         List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList()); | ||||
| 
 | ||||
|         // When | ||||
|         workers.forEach(Thread::start); | ||||
|         countDownLatch.await(); // Block until workers finish | ||||
|         outputScraper.add("Latch released"); | ||||
| 
 | ||||
|         // Then | ||||
|         outputScraper.forEach(Object::toString); | ||||
|         assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released"); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws InterruptedException { | ||||
|         // Given | ||||
|         List<String> outputScraper = Collections.synchronizedList(new ArrayList<>()); | ||||
|         CountDownLatch countDownLatch = new CountDownLatch(5); | ||||
|         List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList()); | ||||
| 
 | ||||
|         // When | ||||
|         workers.forEach(Thread::start); | ||||
|         final boolean result = countDownLatch.await(3L, TimeUnit.SECONDS); | ||||
| 
 | ||||
|         // Then | ||||
|         assertThat(result).isFalse(); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws InterruptedException { | ||||
|         // Given | ||||
|         List<String> outputScraper = Collections.synchronizedList(new ArrayList<>()); | ||||
|         CountDownLatch readyThreadCounter = new CountDownLatch(5); | ||||
|         CountDownLatch callingThreadBlocker = new CountDownLatch(1); | ||||
|         CountDownLatch completedThreadCounter = new CountDownLatch(5); | ||||
|         List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList()); | ||||
| 
 | ||||
|         // When | ||||
|         workers.forEach(Thread::start); | ||||
|         readyThreadCounter.await(); // Block until workers start | ||||
|         outputScraper.add("Workers ready"); | ||||
|         callingThreadBlocker.countDown(); // Start workers | ||||
|         completedThreadCounter.await(); // Block until workers finish | ||||
|         outputScraper.add("Workers complete"); | ||||
| 
 | ||||
|         // Then | ||||
|         outputScraper.forEach(Object::toString); | ||||
|         assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete"); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,22 @@ | ||||
| package com.baeldung.concurrent.future; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| 
 | ||||
| import java.util.concurrent.ForkJoinPool; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| public class FactorialSquareCalculatorUnitTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCalculatesFactorialSquare_thenReturnCorrectValue() { | ||||
|         ForkJoinPool forkJoinPool = new ForkJoinPool(); | ||||
| 
 | ||||
|         FactorialSquareCalculator calculator = new FactorialSquareCalculator(10); | ||||
| 
 | ||||
|         forkJoinPool.execute(calculator); | ||||
| 
 | ||||
|         assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,94 @@ | ||||
| package com.baeldung.concurrent.future; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| import java.util.concurrent.CancellationException; | ||||
| import java.util.concurrent.ExecutionException; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.Future; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.concurrent.TimeoutException; | ||||
| 
 | ||||
| import org.junit.After; | ||||
| import org.junit.Before; | ||||
| import org.junit.Rule; | ||||
| import org.junit.Test; | ||||
| import org.junit.rules.TestName; | ||||
| 
 | ||||
| public class SquareCalculatorUnitTest { | ||||
| 
 | ||||
|     @Rule | ||||
|     public TestName name = new TestName(); | ||||
| 
 | ||||
|     private long start; | ||||
| 
 | ||||
|     private SquareCalculator squareCalculator; | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenExecutorIsSingleThreaded_whenTwoExecutionsAreTriggered_thenRunInSequence() throws InterruptedException, ExecutionException { | ||||
|         squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); | ||||
| 
 | ||||
|         Future<Integer> result1 = squareCalculator.calculate(4); | ||||
|         Future<Integer> result2 = squareCalculator.calculate(1000); | ||||
| 
 | ||||
|         while (!result1.isDone() || !result2.isDone()) { | ||||
|             System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
| 
 | ||||
|             Thread.sleep(300); | ||||
|         } | ||||
| 
 | ||||
|         assertEquals(16, result1.get().intValue()); | ||||
|         assertEquals(1000000, result2.get().intValue()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = TimeoutException.class) | ||||
|     public void whenGetWithTimeoutLowerThanExecutionTime_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException { | ||||
|         squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); | ||||
| 
 | ||||
|         Future<Integer> result = squareCalculator.calculate(4); | ||||
| 
 | ||||
|         result.get(500, TimeUnit.MILLISECONDS); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenExecutorIsMultiThreaded_whenTwoExecutionsAreTriggered_thenRunInParallel() throws InterruptedException, ExecutionException { | ||||
|         squareCalculator = new SquareCalculator(Executors.newFixedThreadPool(2)); | ||||
| 
 | ||||
|         Future<Integer> result1 = squareCalculator.calculate(4); | ||||
|         Future<Integer> result2 = squareCalculator.calculate(1000); | ||||
| 
 | ||||
|         while (!result1.isDone() || !result2.isDone()) { | ||||
|             System.out.println(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done")); | ||||
| 
 | ||||
|             Thread.sleep(300); | ||||
|         } | ||||
| 
 | ||||
|         assertEquals(16, result1.get().intValue()); | ||||
|         assertEquals(1000000, result2.get().intValue()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = CancellationException.class) | ||||
|     public void whenCancelFutureAndCallGet_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException { | ||||
|         squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor()); | ||||
| 
 | ||||
|         Future<Integer> result = squareCalculator.calculate(4); | ||||
| 
 | ||||
|         boolean canceled = result.cancel(true); | ||||
| 
 | ||||
|         assertTrue("Future was canceled", canceled); | ||||
|         assertTrue("Future was canceled", result.isCancelled()); | ||||
| 
 | ||||
|         result.get(); | ||||
|     } | ||||
| 
 | ||||
|     @Before | ||||
|     public void start() { | ||||
|         start = System.currentTimeMillis(); | ||||
|     } | ||||
| 
 | ||||
|     @After | ||||
|     public void end() { | ||||
|         System.out.println(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,57 @@ | ||||
| package com.baeldung.concurrent.priorityblockingqueue; | ||||
| 
 | ||||
| import org.assertj.core.api.Assertions; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.concurrent.PriorityBlockingQueue; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| import java.util.stream.IntStream; | ||||
| 
 | ||||
| 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); | ||||
| 
 | ||||
|         polledElements.add(queue.poll()); | ||||
|         polledElements.add(queue.poll()); | ||||
|         polledElements.add(queue.poll()); | ||||
|         polledElements.add(queue.poll()); | ||||
|         polledElements.add(queue.poll()); | ||||
| 
 | ||||
|         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)); | ||||
|     } | ||||
| } | ||||
| @ -0,0 +1,76 @@ | ||||
| package com.baeldung.java.concurrentmap; | ||||
| 
 | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.Map; | ||||
| import java.util.concurrent.ConcurrentHashMap; | ||||
| import java.util.concurrent.ExecutorService; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertNotEquals; | ||||
| 
 | ||||
| public class ConcurrentMapAggregateStatusTest { | ||||
| 
 | ||||
|     private ExecutorService executorService; | ||||
|     private Map<String, Integer> concurrentMap; | ||||
|     private List<Integer> mapSizes; | ||||
|     private int MAX_SIZE = 100000; | ||||
| 
 | ||||
|     @Before | ||||
|     public void init() { | ||||
|         executorService = Executors.newFixedThreadPool(2); | ||||
|         concurrentMap = new ConcurrentHashMap<>(); | ||||
|         mapSizes = new ArrayList<>(MAX_SIZE); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentMap_whenSizeWithoutConcurrentUpdates_thenCorrect() throws InterruptedException { | ||||
|         Runnable collectMapSizes = () -> { | ||||
|             for (int i = 0; i < MAX_SIZE; i++) { | ||||
|                 concurrentMap.put(String.valueOf(i), i); | ||||
|                 mapSizes.add(concurrentMap.size()); | ||||
|             } | ||||
|         }; | ||||
|         Runnable retrieveMapData = () -> { | ||||
|             for (int i = 0; i < MAX_SIZE; i++) { | ||||
|                 concurrentMap.get(String.valueOf(i)); | ||||
|             } | ||||
|         }; | ||||
|         executorService.execute(retrieveMapData); | ||||
|         executorService.execute(collectMapSizes); | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(1, TimeUnit.MINUTES); | ||||
| 
 | ||||
|         for (int i = 1; i <= MAX_SIZE; i++) { | ||||
|             assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue()); | ||||
|         } | ||||
|         assertEquals(MAX_SIZE, concurrentMap.size()); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentMap_whenUpdatingAndGetSize_thenError() throws InterruptedException { | ||||
|         Runnable collectMapSizes = () -> { | ||||
|             for (int i = 0; i < MAX_SIZE; i++) { | ||||
|                 mapSizes.add(concurrentMap.size()); | ||||
|             } | ||||
|         }; | ||||
|         Runnable updateMapData = () -> { | ||||
|             for (int i = 0; i < MAX_SIZE; i++) { | ||||
|                 concurrentMap.put(String.valueOf(i), i); | ||||
|             } | ||||
|         }; | ||||
|         executorService.execute(updateMapData); | ||||
|         executorService.execute(collectMapSizes); | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(1, TimeUnit.MINUTES); | ||||
| 
 | ||||
|         assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue()); | ||||
|         assertEquals(MAX_SIZE, concurrentMap.size()); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,160 @@ | ||||
| package com.baeldung.java.concurrentmap; | ||||
| 
 | ||||
| import org.junit.Before; | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| import java.util.concurrent.ConcurrentHashMap; | ||||
| import java.util.concurrent.ConcurrentMap; | ||||
| 
 | ||||
| import static org.junit.Assert.assertNull; | ||||
| 
 | ||||
| public class ConcurrentMapNullKeyValueTest { | ||||
| 
 | ||||
|     ConcurrentMap<String, Object> concurrentMap; | ||||
| 
 | ||||
|     @Before | ||||
|     public void setup() { | ||||
|         concurrentMap = new ConcurrentHashMap<>(); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenGetWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.get(null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenGetOrDefaultWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.getOrDefault(null, new Object()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenPutWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.put(null, new Object()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenPutNullValue_thenThrowsNPE() { | ||||
|         concurrentMap.put("test", null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMapAndKeyAbsent_whenPutWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.putIfAbsent(null, new Object()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMapAndMapWithNullKey_whenPutNullKeyMap_thenThrowsNPE() { | ||||
|         Map<String, Object> nullKeyMap = new HashMap<>(); | ||||
|         nullKeyMap.put(null, new Object()); | ||||
|         concurrentMap.putAll(nullKeyMap); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMapAndMapWithNullValue_whenPutNullValueMap_thenThrowsNPE() { | ||||
|         Map<String, Object> nullValueMap = new HashMap<>(); | ||||
|         nullValueMap.put("test", null); | ||||
|         concurrentMap.putAll(nullValueMap); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceNullKeyWithValues_thenThrowsNPE() { | ||||
|         concurrentMap.replace(null, new Object(), new Object()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceWithNullNewValue_thenThrowsNPE() { | ||||
|         Object o = new Object(); | ||||
|         concurrentMap.replace("test", o, null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceOldNullValue_thenThrowsNPE() { | ||||
|         Object o = new Object(); | ||||
|         concurrentMap.replace("test", null, o); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceWithNullValue_thenThrowsNPE() { | ||||
|         concurrentMap.replace("test", null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.replace(null, "test"); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenReplaceAllMappingNull_thenThrowsNPE() { | ||||
|         concurrentMap.put("test", new Object()); | ||||
|         concurrentMap.replaceAll((s, o) -> null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenRemoveNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.remove(null); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenRemoveNullKeyWithValue_thenThrowsNPE() { | ||||
|         concurrentMap.remove(null, new Object()); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenMergeNullKeyWithValue_thenThrowsNPE() { | ||||
|         concurrentMap.merge(null, new Object(), (o, o2) -> o2); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenMergeKeyWithNullValue_thenThrowsNPE() { | ||||
|         concurrentMap.put("test", new Object()); | ||||
|         concurrentMap.merge("test", null, (o, o2) -> o2); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMapAndAssumeKeyAbsent_whenComputeWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.computeIfAbsent(null, s -> s); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMapAndAssumeKeyPresent_whenComputeWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.computeIfPresent(null, (s, o) -> o); | ||||
|     } | ||||
| 
 | ||||
|     @Test(expected = NullPointerException.class) | ||||
|     public void givenConcurrentHashMap_whenComputeWithNullKey_thenThrowsNPE() { | ||||
|         concurrentMap.compute(null, (s, o) -> o); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentHashMap_whenMergeKeyRemappingNull_thenRemovesMapping() { | ||||
|         Object oldValue = new Object(); | ||||
|         concurrentMap.put("test", oldValue); | ||||
|         concurrentMap.merge("test", new Object(), (o, o2) -> null); | ||||
|         assertNull(concurrentMap.get("test")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentHashMapAndKeyAbsent_whenComputeWithKeyRemappingNull_thenRemainsAbsent() { | ||||
|         concurrentMap.computeIfPresent("test", (s, o) -> null); | ||||
|         assertNull(concurrentMap.get("test")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenKeyPresent_whenComputeIfPresentRemappingNull_thenMappingRemoved() { | ||||
|         Object oldValue = new Object(); | ||||
|         concurrentMap.put("test", oldValue); | ||||
|         concurrentMap.computeIfPresent("test", (s, o) -> null); | ||||
|         assertNull(concurrentMap.get("test")); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenKeyPresent_whenComputeRemappingNull_thenMappingRemoved() { | ||||
|         Object oldValue = new Object(); | ||||
|         concurrentMap.put("test", oldValue); | ||||
|         concurrentMap.compute("test", (s, o) -> null); | ||||
|         assertNull(concurrentMap.get("test")); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,95 @@ | ||||
| package com.baeldung.java.concurrentmap; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Collections; | ||||
| import java.util.HashMap; | ||||
| import java.util.Hashtable; | ||||
| import java.util.Map; | ||||
| import java.util.concurrent.*; | ||||
| 
 | ||||
| import static org.junit.Assert.assertEquals; | ||||
| import static org.junit.Assert.assertTrue; | ||||
| 
 | ||||
| public class ConcurrentMapPerformanceTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenMaps_whenGetPut500KTimes_thenConcurrentMapFaster() throws Exception { | ||||
|         Map<String, Object> hashtable = new Hashtable<>(); | ||||
|         Map<String, Object> synchronizedHashMap = Collections.synchronizedMap(new HashMap<>()); | ||||
|         Map<String, Object> concurrentHashMap = new ConcurrentHashMap<>(); | ||||
| 
 | ||||
|         long hashtableAvgRuntime = timeElapseForGetPut(hashtable); | ||||
|         long syncHashMapAvgRuntime = timeElapseForGetPut(synchronizedHashMap); | ||||
|         long concurrentHashMapAvgRuntime = timeElapseForGetPut(concurrentHashMap); | ||||
| 
 | ||||
|         System.out.println(String.format("Hashtable: %s, syncHashMap: %s, ConcurrentHashMap: %s", hashtableAvgRuntime, syncHashMapAvgRuntime, concurrentHashMapAvgRuntime)); | ||||
| 
 | ||||
|         assertTrue(hashtableAvgRuntime > concurrentHashMapAvgRuntime); | ||||
|         assertTrue(syncHashMapAvgRuntime > concurrentHashMapAvgRuntime); | ||||
| 
 | ||||
|     } | ||||
| 
 | ||||
|     private long timeElapseForGetPut(Map<String, Object> map) throws InterruptedException { | ||||
|         ExecutorService executorService = Executors.newFixedThreadPool(4); | ||||
|         long startTime = System.nanoTime(); | ||||
|         for (int i = 0; i < 4; i++) { | ||||
|             executorService.execute(() -> { | ||||
|                 for (int j = 0; j < 500_000; j++) { | ||||
|                     int value = ThreadLocalRandom.current().nextInt(10000); | ||||
|                     String key = String.valueOf(value); | ||||
|                     map.put(key, value); | ||||
|                     map.get(key); | ||||
|                 } | ||||
|             }); | ||||
|         } | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(1, TimeUnit.MINUTES); | ||||
|         return (System.nanoTime() - startTime) / 500_000; | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentMap_whenKeyWithSameHashCode_thenPerformanceDegrades() throws InterruptedException { | ||||
|         class SameHash { | ||||
|             @Override | ||||
|             public int hashCode() { | ||||
|                 return 1; | ||||
|             } | ||||
|         } | ||||
|         int executeTimes = 5000; | ||||
| 
 | ||||
|         Map<SameHash, Integer> mapOfSameHash = new ConcurrentHashMap<>(); | ||||
|         ExecutorService executorService = Executors.newFixedThreadPool(2); | ||||
|         long sameHashStartTime = System.currentTimeMillis(); | ||||
|         for (int i = 0; i < 2; i++) { | ||||
|             executorService.execute(() -> { | ||||
|                 for (int j = 0; j < executeTimes; j++) { | ||||
|                     mapOfSameHash.put(new SameHash(), 1); | ||||
|                 } | ||||
|             }); | ||||
|         } | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(5, TimeUnit.SECONDS); | ||||
| 
 | ||||
|         long mapOfSameHashDuration = System.currentTimeMillis() - sameHashStartTime; | ||||
|         Map<Object, Integer> mapOfDefaultHash = new ConcurrentHashMap<>(); | ||||
|         executorService = Executors.newFixedThreadPool(2); | ||||
|         long defaultHashStartTime = System.currentTimeMillis(); | ||||
|         for (int i = 0; i < 2; i++) { | ||||
|             executorService.execute(() -> { | ||||
|                 for (int j = 0; j < executeTimes; j++) { | ||||
|                     mapOfDefaultHash.put(new Object(), 1); | ||||
|                 } | ||||
|             }); | ||||
|         } | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(5, TimeUnit.SECONDS); | ||||
| 
 | ||||
|         long mapOfDefaultHashDuration = System.currentTimeMillis() - defaultHashStartTime; | ||||
|         assertEquals(executeTimes * 2, mapOfDefaultHash.size()); | ||||
|         assertEquals(executeTimes * 2, mapOfSameHash.size()); | ||||
|         System.out.println(String.format("same-hash: %s, default-hash: %s", mapOfSameHashDuration, mapOfDefaultHashDuration)); | ||||
|         assertTrue("same hashCode() should greatly degrade performance", mapOfSameHashDuration > mapOfDefaultHashDuration * 10); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,79 @@ | ||||
| package com.baeldung.java.concurrentmap; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Iterator; | ||||
| import java.util.NavigableMap; | ||||
| import java.util.TreeMap; | ||||
| import java.util.concurrent.*; | ||||
| import java.util.concurrent.atomic.AtomicInteger; | ||||
| 
 | ||||
| import static org.testng.Assert.*; | ||||
| 
 | ||||
| public class ConcurrentNavigableMapTests { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { | ||||
|         NavigableMap<Integer, String> skipListMap = new ConcurrentSkipListMap<>(); | ||||
| 
 | ||||
|         updateMapConcurrently(skipListMap, 4); | ||||
| 
 | ||||
|         Iterator<Integer> skipListIter = skipListMap | ||||
|           .keySet() | ||||
|           .iterator(); | ||||
|         int previous = skipListIter.next(); | ||||
|         while (skipListIter.hasNext()) { | ||||
|             int current = skipListIter.next(); | ||||
|             assertTrue(previous < current); | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
|     private void updateMapConcurrently(NavigableMap<Integer, String> navigableMap, int concurrencyLevel) throws InterruptedException { | ||||
|         ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); | ||||
|         for (int i = 0; i < concurrencyLevel; i++) { | ||||
|             executorService.execute(() -> { | ||||
|                 ThreadLocalRandom random = ThreadLocalRandom.current(); | ||||
|                 for (int j = 0; j < 10000; j++) { | ||||
|                     navigableMap.put(random.nextInt(), "test"); | ||||
|                 } | ||||
|             }); | ||||
|         } | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(1, TimeUnit.MINUTES); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenSkipListMap_whenNavConcurrently_thenCountCorrect() throws InterruptedException { | ||||
|         NavigableMap<Integer, Integer> skipListMap = new ConcurrentSkipListMap<>(); | ||||
|         int count = countMapElementByPollingFirstEntry(skipListMap, 10000, 4); | ||||
|         assertEquals(10000 * 4, count); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTreeMap_whenNavConcurrently_thenCountError() throws InterruptedException { | ||||
|         NavigableMap<Integer, Integer> treeMap = new TreeMap<>(); | ||||
|         int count = countMapElementByPollingFirstEntry(treeMap, 10000, 4); | ||||
|         assertNotEquals(10000 * 4, count); | ||||
|     } | ||||
| 
 | ||||
|     private int countMapElementByPollingFirstEntry(NavigableMap<Integer, Integer> navigableMap, int elementCount, int concurrencyLevel) throws InterruptedException { | ||||
|         for (int i = 0; i < elementCount * concurrencyLevel; i++) { | ||||
|             navigableMap.put(i, i); | ||||
|         } | ||||
|         AtomicInteger counter = new AtomicInteger(0); | ||||
|         ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); | ||||
|         for (int j = 0; j < concurrencyLevel; j++) { | ||||
|             executorService.execute(() -> { | ||||
|                 for (int i = 0; i < elementCount; i++) { | ||||
|                     if (navigableMap.pollFirstEntry() != null) { | ||||
|                         counter.incrementAndGet(); | ||||
|                     } | ||||
|                 } | ||||
|             }); | ||||
|         } | ||||
|         executorService.shutdown(); | ||||
|         executorService.awaitTermination(1, TimeUnit.MINUTES); | ||||
|         return counter.get(); | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -0,0 +1,60 @@ | ||||
| package com.baeldung.java.concurrentmap; | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.*; | ||||
| import java.util.concurrent.ConcurrentHashMap; | ||||
| import java.util.concurrent.ExecutorService; | ||||
| import java.util.concurrent.Executors; | ||||
| import java.util.concurrent.TimeUnit; | ||||
| 
 | ||||
| import static org.junit.Assert.*; | ||||
| 
 | ||||
| public class ConcurretMapMemoryConsistencyTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception { | ||||
|         Map<String, Integer> map = new ConcurrentHashMap<>(); | ||||
|         List<Integer> sumList = parallelSum100(map, 1000); | ||||
|         assertEquals(1, sumList.stream().distinct().count()); | ||||
|         long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); | ||||
|         assertEquals(0, wrongResultCount); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenHashtable_whenSumParallel_thenCorrect() throws Exception { | ||||
|         Map<String, Integer> map = new Hashtable<>(); | ||||
|         List<Integer> sumList = parallelSum100(map, 1000); | ||||
|         assertEquals(1, sumList.stream().distinct().count()); | ||||
|         long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); | ||||
|         assertEquals(0, wrongResultCount); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenHashMap_whenSumParallel_thenError() throws Exception { | ||||
|         Map<String, Integer> map = new HashMap<>(); | ||||
|         List<Integer> sumList = parallelSum100(map, 100); | ||||
|         assertNotEquals(1, sumList.stream().distinct().count()); | ||||
|         long wrongResultCount = sumList.stream().filter(num -> num != 100).count(); | ||||
|         assertTrue(wrongResultCount > 0); | ||||
|     } | ||||
| 
 | ||||
|     private List<Integer> parallelSum100(Map<String, Integer> map, int executionTimes) throws InterruptedException { | ||||
|         List<Integer> sumList = new ArrayList<>(1000); | ||||
|         for (int i = 0; i < executionTimes; i++) { | ||||
|             map.put("test", 0); | ||||
|             ExecutorService executorService = Executors.newFixedThreadPool(4); | ||||
|             for (int j = 0; j < 10; j++) { | ||||
|                 executorService.execute(() -> { | ||||
|                     for (int k = 0; k < 10; k++) | ||||
|                         map.computeIfPresent("test", (key, value) -> value + 1); | ||||
|                 }); | ||||
|             } | ||||
|             executorService.shutdown(); | ||||
|             executorService.awaitTermination(5, TimeUnit.SECONDS); | ||||
|             sumList.add(map.get("test")); | ||||
|         } | ||||
|         return sumList; | ||||
|     } | ||||
| 
 | ||||
| } | ||||
| @ -24,8 +24,7 @@ public class IterableStreamConversionTest { | ||||
|     public void whenConvertedToList_thenCorrect() { | ||||
|         Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream"); | ||||
| 
 | ||||
|         List<String> result = StreamSupport.stream(iterable.spliterator(), false) | ||||
|           .map(String::toUpperCase).collect(Collectors.toList()); | ||||
|         List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList()); | ||||
| 
 | ||||
|         assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM")); | ||||
|     } | ||||
|  | ||||
| @ -201,8 +201,6 @@ public class MapTest { | ||||
|         assertEquals("val1", rtnVal); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| 
 | ||||
|     @Test | ||||
|     public void whenCallsEqualsOnCollision_thenCorrect() { | ||||
|         HashMap<MyKey, String> map = new HashMap<>(); | ||||
| @ -311,13 +309,7 @@ public class MapTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenTreeMap_whenOrdersEntriesByComparator_thenCorrect() { | ||||
|         TreeMap<Integer, String> map = new TreeMap<>(new Comparator<Integer>() { | ||||
| 
 | ||||
|             @Override | ||||
|             public int compare(Integer o1, Integer o2) { | ||||
|                 return o2 - o1; | ||||
|             } | ||||
|         }); | ||||
|         TreeMap<Integer, String> map = new TreeMap<>(Comparator.reverseOrder()); | ||||
|         map.put(3, "val"); | ||||
|         map.put(2, "val"); | ||||
|         map.put(1, "val"); | ||||
|  | ||||
| @ -1,6 +1,5 @@ | ||||
| package com.baeldung.java8; | ||||
| 
 | ||||
| 
 | ||||
| import org.junit.Test; | ||||
| 
 | ||||
| import java.util.Arrays; | ||||
| @ -25,6 +24,15 @@ public class Java8FindAnyFindFirstTest { | ||||
|         assertThat(result.get(), anyOf(is("A"), is("B"), is("C"), is("D"))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception { | ||||
|         List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); | ||||
|         Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny(); | ||||
| 
 | ||||
|         assertTrue(result.isPresent()); | ||||
|         assertThat(result.get(), anyOf(is(1), is(2), is(3))); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|     public void createStream_whenFindFirstResultIsPresent_thenCorrect() { | ||||
| 
 | ||||
|  | ||||
| @ -56,9 +56,7 @@ public class NashornTest { | ||||
|         Map<String, Object> map = (Map<String, Object>) obj; | ||||
| 
 | ||||
|         Assert.assertEquals("hello", map.get("greet")); | ||||
|         Assert.assertTrue(List.class.isAssignableFrom(map | ||||
|           .get("primes") | ||||
|           .getClass())); | ||||
|         Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass())); | ||||
|     } | ||||
| 
 | ||||
|     @Test | ||||
|  | ||||
| @ -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()); | ||||
|     } | ||||
| } | ||||
| @ -9,7 +9,8 @@ public class Person implements CouchbaseEntity { | ||||
|     private String name; | ||||
|     private String homeTown; | ||||
| 
 | ||||
|     Person() {} | ||||
|     Person() { | ||||
|     } | ||||
| 
 | ||||
|     public Person(Builder b) { | ||||
|         this.id = b.id; | ||||
|  | ||||
| @ -13,9 +13,7 @@ import com.baeldung.couchbase.async.service.BucketService; | ||||
| public class PersonCrudService extends AbstractCrudService<Person> { | ||||
| 
 | ||||
|     @Autowired | ||||
|     public PersonCrudService( | ||||
|       @Qualifier("TutorialBucketService") BucketService bucketService, | ||||
|       PersonDocumentConverter converter) { | ||||
|     public PersonCrudService(@Qualifier("TutorialBucketService") BucketService bucketService, PersonDocumentConverter converter) { | ||||
|         super(bucketService, converter); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> { | ||||
| 
 | ||||
|     @Override | ||||
|     public JsonDocument toDocument(Person p) { | ||||
|         JsonObject content = JsonObject.empty() | ||||
|                 .put("type", "Person") | ||||
|                 .put("name", p.getName()) | ||||
|                 .put("homeTown", p.getHomeTown()); | ||||
|         JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); | ||||
|         return JsonDocument.create(p.getId(), content); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -21,8 +21,7 @@ public class RegistrationService { | ||||
|     public Person findRegistrant(String id) { | ||||
|         try { | ||||
|             return crud.read(id); | ||||
|         } | ||||
|         catch(CouchbaseException e) { | ||||
|         } catch (CouchbaseException e) { | ||||
|             return crud.readFromReplica(id); | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @ -73,9 +73,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements | ||||
|     @Override | ||||
|     public List<T> readBulk(Iterable<String> ids) { | ||||
|         final AsyncBucket asyncBucket = bucket.async(); | ||||
|         Observable<JsonDocument> asyncOperation = Observable | ||||
|                 .from(ids) | ||||
|                 .flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|         Observable<JsonDocument> asyncOperation = Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|             public Observable<JsonDocument> call(String key) { | ||||
|                 return asyncBucket.get(key); | ||||
|             } | ||||
| @ -83,8 +81,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements | ||||
| 
 | ||||
|         final List<T> items = new ArrayList<T>(); | ||||
|         try { | ||||
|             asyncOperation.toBlocking() | ||||
|             .forEach(new Action1<JsonDocument>() { | ||||
|             asyncOperation.toBlocking().forEach(new Action1<JsonDocument>() { | ||||
|                 public void call(JsonDocument doc) { | ||||
|                     T item = converter.fromDocument(doc); | ||||
|                     items.add(item); | ||||
| @ -100,9 +97,7 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements | ||||
|     @Override | ||||
|     public void createBulk(Iterable<T> items) { | ||||
|         final AsyncBucket asyncBucket = bucket.async(); | ||||
|         Observable | ||||
|         .from(items) | ||||
|         .flatMap(new Func1<T, Observable<JsonDocument>>() { | ||||
|         Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() { | ||||
|             @SuppressWarnings("unchecked") | ||||
|             @Override | ||||
|             public Observable<JsonDocument> call(final T t) { | ||||
| @ -110,62 +105,34 @@ public abstract class AbstractCrudService<T extends CouchbaseEntity> implements | ||||
|                     t.setId(UUID.randomUUID().toString()); | ||||
|                 } | ||||
|                 JsonDocument doc = converter.toDocument(t); | ||||
|                 return asyncBucket.insert(doc) | ||||
|                         .retryWhen(RetryBuilder | ||||
|                                 .anyOf(BackpressureException.class) | ||||
|                                 .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) | ||||
|                                 .max(10) | ||||
|                                 .build()); | ||||
|                 return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); | ||||
|             } | ||||
|         }) | ||||
|         .last() | ||||
|         .toBlocking() | ||||
|         .single(); | ||||
|         }).last().toBlocking().single(); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void updateBulk(Iterable<T> items) { | ||||
|         final AsyncBucket asyncBucket = bucket.async(); | ||||
|         Observable | ||||
|         .from(items) | ||||
|         .flatMap(new Func1<T, Observable<JsonDocument>>() { | ||||
|         Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() { | ||||
|             @SuppressWarnings("unchecked") | ||||
|             @Override | ||||
|             public Observable<JsonDocument> call(final T t) { | ||||
|                 JsonDocument doc = converter.toDocument(t); | ||||
|                 return asyncBucket.upsert(doc) | ||||
|                         .retryWhen(RetryBuilder | ||||
|                                 .anyOf(BackpressureException.class) | ||||
|                                 .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) | ||||
|                                 .max(10) | ||||
|                                 .build()); | ||||
|                 return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); | ||||
|             } | ||||
|         }) | ||||
|         .last() | ||||
|         .toBlocking() | ||||
|         .single(); | ||||
|         }).last().toBlocking().single(); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|     public void deleteBulk(Iterable<String> ids) { | ||||
|         final AsyncBucket asyncBucket = bucket.async(); | ||||
|         Observable | ||||
|         .from(ids) | ||||
|         .flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|         Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|             @SuppressWarnings("unchecked") | ||||
|             @Override | ||||
|             public Observable<JsonDocument> call(String key) { | ||||
|                 return asyncBucket.remove(key) | ||||
|                         .retryWhen(RetryBuilder | ||||
|                                 .anyOf(BackpressureException.class) | ||||
|                                 .delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)) | ||||
|                                 .max(10) | ||||
|                                 .build()); | ||||
|                 return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build()); | ||||
|             } | ||||
|         }) | ||||
|         .last() | ||||
|         .toBlocking() | ||||
|         .single(); | ||||
|         }).last().toBlocking().single(); | ||||
|     } | ||||
| 
 | ||||
|     @Override | ||||
|  | ||||
| @ -20,10 +20,7 @@ public class CodeSnippets { | ||||
|     } | ||||
| 
 | ||||
|     static Cluster loadClusterWithCustomEnvironment() { | ||||
|         CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder() | ||||
|                 .connectTimeout(10000) | ||||
|                 .kvTimeout(3000) | ||||
|                 .build();         | ||||
|         CouchbaseEnvironment env = DefaultCouchbaseEnvironment.builder().connectTimeout(10000).kvTimeout(3000).build(); | ||||
|         return CouchbaseCluster.create(env, "localhost"); | ||||
|     } | ||||
| 
 | ||||
| @ -36,12 +33,7 @@ public class CodeSnippets { | ||||
|     } | ||||
| 
 | ||||
|     static JsonDocument insertExample(Bucket bucket) { | ||||
|         JsonObject content = JsonObject.empty() | ||||
|                 .put("name", "John Doe") | ||||
|                 .put("type", "Person") | ||||
|                 .put("email", "john.doe@mydomain.com") | ||||
|                 .put("homeTown", "Chicago") | ||||
|                 ; | ||||
|         JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago"); | ||||
|         String id = UUID.randomUUID().toString(); | ||||
|         JsonDocument document = JsonDocument.create(id, content); | ||||
|         JsonDocument inserted = bucket.insert(document); | ||||
| @ -72,8 +64,7 @@ public class CodeSnippets { | ||||
|     static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { | ||||
|         try { | ||||
|             return bucket.get(id); | ||||
|         } | ||||
|         catch(CouchbaseException e) { | ||||
|         } catch (CouchbaseException e) { | ||||
|             List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST); | ||||
|             if (!list.isEmpty()) { | ||||
|                 return list.get(0); | ||||
|  | ||||
| @ -7,7 +7,8 @@ public class Person { | ||||
|     private String name; | ||||
|     private String homeTown; | ||||
| 
 | ||||
|     Person() {} | ||||
|     Person() { | ||||
|     } | ||||
| 
 | ||||
|     public Person(Builder b) { | ||||
|         this.id = b.id; | ||||
|  | ||||
| @ -11,10 +11,7 @@ public class PersonDocumentConverter implements JsonDocumentConverter<Person> { | ||||
| 
 | ||||
|     @Override | ||||
|     public JsonDocument toDocument(Person p) { | ||||
|         JsonObject content = JsonObject.empty() | ||||
|                 .put("type", "Person") | ||||
|                 .put("name", p.getName()) | ||||
|                 .put("homeTown", p.getHomeTown()); | ||||
|         JsonObject content = JsonObject.empty().put("type", "Person").put("name", p.getName()).put("homeTown", p.getHomeTown()); | ||||
|         return JsonDocument.create(p.getId(), content); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -21,8 +21,7 @@ public class RegistrationService { | ||||
|     public Person findRegistrant(String id) { | ||||
|         try { | ||||
|             return crud.read(id); | ||||
|         } | ||||
|         catch(CouchbaseException e) { | ||||
|         } catch (CouchbaseException e) { | ||||
|             return crud.readFromReplica(id); | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @ -59,9 +59,7 @@ public class ClusterServiceImpl implements ClusterService { | ||||
| 
 | ||||
|     @Override | ||||
|     public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) { | ||||
|         Observable<JsonDocument> asyncBulkGet = Observable | ||||
|                 .from(keys) | ||||
|                 .flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|         Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() { | ||||
|             public Observable<JsonDocument> call(String key) { | ||||
|                 return asyncBucket.get(key); | ||||
|             } | ||||
| @ -69,8 +67,7 @@ public class ClusterServiceImpl implements ClusterService { | ||||
| 
 | ||||
|         final List<JsonDocument> docs = new ArrayList<>(); | ||||
|         try { | ||||
|             asyncBulkGet.toBlocking() | ||||
|             .forEach(new Action1<JsonDocument>() { | ||||
|             asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() { | ||||
|                 public void call(JsonDocument doc) { | ||||
|                     docs.add(doc); | ||||
|                 } | ||||
|  | ||||
| @ -207,17 +207,10 @@ public class PersonCrudServiceIntegrationTest extends AsyncIntegrationTest { | ||||
|     } | ||||
| 
 | ||||
|     private Person randomPerson() { | ||||
|         return Person.Builder.newInstance() | ||||
|           .name(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .homeTown(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .build(); | ||||
|         return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); | ||||
|     } | ||||
| 
 | ||||
|     private Person randomPersonWithId() { | ||||
|         return Person.Builder.newInstance() | ||||
|           .id(UUID.randomUUID().toString()) | ||||
|           .name(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .homeTown(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .build(); | ||||
|         return Person.Builder.newInstance().id(UUID.randomUUID().toString()).name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -66,17 +66,10 @@ public class PersonCrudServiceIntegrationTest extends IntegrationTest { | ||||
|     } | ||||
| 
 | ||||
|     private Person buildClarkKent() { | ||||
|         return Person.Builder.newInstance() | ||||
|           .id(CLARK_KENT_ID) | ||||
|           .name(CLARK_KENT) | ||||
|           .homeTown(SMALLVILLE) | ||||
|           .build(); | ||||
|         return Person.Builder.newInstance().id(CLARK_KENT_ID).name(CLARK_KENT).homeTown(SMALLVILLE).build(); | ||||
|     } | ||||
| 
 | ||||
|     private Person randomPerson() { | ||||
|         return Person.Builder.newInstance() | ||||
|           .name(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .homeTown(RandomStringUtils.randomAlphabetic(10)) | ||||
|           .build(); | ||||
|         return Person.Builder.newInstance().name(RandomStringUtils.randomAlphabetic(10)).homeTown(RandomStringUtils.randomAlphabetic(10)).build(); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -35,9 +35,6 @@ public abstract class MemberRepository extends AbstractEntityRepository<Member, | ||||
| 
 | ||||
|     public List<Member> findAllOrderedByNameWithQueryDSL() { | ||||
|         final QMember member = QMember.member; | ||||
|         return jpaQuery() | ||||
|                 .from(member) | ||||
|                 .orderBy(member.email.asc()) | ||||
|                 .list(member); | ||||
|         return jpaQuery().from(member).orderBy(member.email.asc()).list(member); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -64,7 +64,6 @@ public class MemberRegistration { | ||||
|         } | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
|     public void register(Member member) throws Exception { | ||||
|         log.info("Registering " + member.getName()); | ||||
|         validateMember(member); | ||||
|  | ||||
| @ -41,27 +41,13 @@ import org.junit.runner.RunWith; | ||||
| public class MemberRegistrationTest { | ||||
|     @Deployment | ||||
|     public static Archive<?> createTestArchive() { | ||||
|         File[] files = Maven.resolver().loadPomFromFile("pom.xml") | ||||
|                 .importRuntimeDependencies().resolve().withTransitivity().asFile(); | ||||
|         File[] files = Maven.resolver().loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile(); | ||||
| 
 | ||||
|         return ShrinkWrap.create(WebArchive.class, "test.war") | ||||
|                 .addClasses( | ||||
|                         EntityManagerProducer.class, | ||||
|                         Member.class, | ||||
|                         MemberRegistration.class, | ||||
|                         MemberRepository.class, | ||||
|                         Resources.class, | ||||
|                         QueryDslRepositoryExtension.class, | ||||
|                         QueryDslSupport.class, | ||||
|                         SecondaryPersistenceUnit.class, | ||||
|                         SecondaryEntityManagerProducer.class, | ||||
|                         SecondaryEntityManagerResolver.class) | ||||
|                 .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml") | ||||
|                 .addAsResource("META-INF/apache-deltaspike.properties") | ||||
|                 .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") | ||||
|                 .addAsWebInfResource("test-ds.xml") | ||||
|                 .addAsWebInfResource("test-secondary-ds.xml") | ||||
|                 .addAsLibraries(files); | ||||
|                 .addClasses(EntityManagerProducer.class, Member.class, MemberRegistration.class, MemberRepository.class, Resources.class, QueryDslRepositoryExtension.class, QueryDslSupport.class, SecondaryPersistenceUnit.class, | ||||
|                         SecondaryEntityManagerProducer.class, SecondaryEntityManagerResolver.class) | ||||
|                 .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml").addAsResource("META-INF/apache-deltaspike.properties").addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml").addAsWebInfResource("test-ds.xml") | ||||
|                 .addAsWebInfResource("test-secondary-ds.xml").addAsLibraries(files); | ||||
|     } | ||||
| 
 | ||||
|     @Inject | ||||
|  | ||||
							
								
								
									
										0
									
								
								disruptor/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								disruptor/README.md
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										251
									
								
								disruptor/pom.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										251
									
								
								disruptor/pom.xml
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,251 @@ | ||||
| <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>disruptor</artifactId> | ||||
|     <version>0.1.0-SNAPSHOT</version> | ||||
|     <packaging>jar</packaging> | ||||
| 
 | ||||
|     <name>disruptor</name> | ||||
| 
 | ||||
|     <dependencies> | ||||
| 
 | ||||
|         <!-- utils --> | ||||
|         <dependency> | ||||
|             <groupId>org.apache.commons</groupId> | ||||
|             <artifactId>commons-lang3</artifactId> | ||||
|             <version>${commons-lang3.version}</version> | ||||
|         </dependency> | ||||
|          | ||||
|         <dependency> | ||||
|             <groupId>com.lmax</groupId> | ||||
|             <artifactId>disruptor</artifactId> | ||||
|             <version>${disruptor.version}</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <!-- logging --> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.slf4j</groupId> | ||||
|             <artifactId>slf4j-api</artifactId> | ||||
|             <version>${org.slf4j.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>ch.qos.logback</groupId> | ||||
|             <artifactId>logback-classic</artifactId> | ||||
|             <version>${logback.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.slf4j</groupId> | ||||
|             <artifactId>jcl-over-slf4j</artifactId> | ||||
|             <version>${org.slf4j.version}</version> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.slf4j</groupId> | ||||
|             <artifactId>log4j-over-slf4j</artifactId> | ||||
|             <version>${org.slf4j.version}</version> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <!-- test scoped --> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.hamcrest</groupId> | ||||
|             <artifactId>hamcrest-all</artifactId> | ||||
|             <version>1.3</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>junit</groupId> | ||||
|             <artifactId>junit</artifactId> | ||||
|             <version>${junit.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.hamcrest</groupId> | ||||
|             <artifactId>hamcrest-core</artifactId> | ||||
|             <version>${org.hamcrest.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|         <dependency> | ||||
|             <groupId>org.hamcrest</groupId> | ||||
|             <artifactId>hamcrest-library</artifactId> | ||||
|             <version>${org.hamcrest.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
|         <finalName>disruptor</finalName> | ||||
|         <resources> | ||||
|             <resource> | ||||
|                 <directory>src/main/resources</directory> | ||||
|                 <filtering>true</filtering> | ||||
|             </resource> | ||||
|         </resources> | ||||
| 
 | ||||
|         <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.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-surefire-plugin</artifactId> | ||||
|                 <version>${maven-surefire-plugin.version}</version> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-dependency-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <id>copy-dependencies</id> | ||||
|                         <phase>prepare-package</phase> | ||||
|                         <goals> | ||||
|                             <goal>copy-dependencies</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <outputDirectory>${project.build.directory}/libs</outputDirectory> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-jar-plugin</artifactId> | ||||
|                 <configuration> | ||||
|                     <archive> | ||||
|                         <manifest> | ||||
|                             <addClasspath>true</addClasspath> | ||||
|                             <classpathPrefix>libs/</classpathPrefix> | ||||
|                             <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> | ||||
|                         </manifest> | ||||
|                     </archive> | ||||
|                 </configuration> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-assembly-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <phase>package</phase> | ||||
|                         <goals> | ||||
|                             <goal>single</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <archive> | ||||
|                                 <manifest> | ||||
|                                     <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> | ||||
|                                 </manifest> | ||||
|                             </archive> | ||||
|                             <descriptorRefs> | ||||
|                                 <descriptorRef>jar-with-dependencies</descriptorRef> | ||||
|                             </descriptorRefs> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>org.apache.maven.plugins</groupId> | ||||
|                 <artifactId>maven-shade-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <goals> | ||||
|                             <goal>shade</goal> | ||||
|                         </goals> | ||||
|                         <configuration> | ||||
|                             <shadedArtifactAttached>true</shadedArtifactAttached> | ||||
|                             <transformers> | ||||
|                                 <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> | ||||
|                                     <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> | ||||
|                                 </transformer> | ||||
|                             </transformers> | ||||
|                         </configuration> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|             <plugin> | ||||
|                 <groupId>com.jolira</groupId> | ||||
|                 <artifactId>onejar-maven-plugin</artifactId> | ||||
|                 <executions> | ||||
|                     <execution> | ||||
|                         <configuration> | ||||
|                             <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> | ||||
|                             <attachToBuild>true</attachToBuild> | ||||
|                             <filename>${project.build.finalName}-onejar.${project.packaging}</filename> | ||||
|                         </configuration> | ||||
|                         <goals> | ||||
|                             <goal>one-jar</goal> | ||||
|                         </goals> | ||||
|                     </execution> | ||||
|                 </executions> | ||||
|             </plugin> | ||||
| 
 | ||||
|         </plugins> | ||||
| 
 | ||||
|     </build> | ||||
| 
 | ||||
|     <profiles> | ||||
|         <profile> | ||||
|             <id>integration</id> | ||||
|             <build> | ||||
|                 <plugins> | ||||
|                     <plugin> | ||||
|                         <groupId>org.apache.maven.plugins</groupId> | ||||
|                         <artifactId>maven-surefire-plugin</artifactId> | ||||
|                         <executions> | ||||
|                             <execution> | ||||
|                                 <phase>integration-test</phase> | ||||
|                                 <goals> | ||||
|                                     <goal>test</goal> | ||||
|                                 </goals> | ||||
|                             </execution> | ||||
|                         </executions> | ||||
|                         <configuration> | ||||
|                             <systemPropertyVariables> | ||||
|                                 <test.mime>json</test.mime> | ||||
|                             </systemPropertyVariables> | ||||
|                         </configuration> | ||||
|                     </plugin> | ||||
|                 </plugins> | ||||
|             </build> | ||||
|         </profile> | ||||
|     </profiles> | ||||
| 
 | ||||
|     <properties> | ||||
|         <!-- logging --> | ||||
|         <org.slf4j.version>1.7.21</org.slf4j.version> | ||||
|         <logback.version>1.1.7</logback.version> | ||||
| 
 | ||||
|         <!-- util --> | ||||
|         <commons-lang3.version>3.5</commons-lang3.version> | ||||
|         <disruptor.version>3.3.6</disruptor.version> | ||||
| 
 | ||||
|         <!-- testing --> | ||||
|         <org.hamcrest.version>1.3</org.hamcrest.version> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <mockito.version>1.10.19</mockito.version> | ||||
|         <testng.version>6.10</testng.version> | ||||
|         <assertj.version>3.6.1</assertj.version> | ||||
| 
 | ||||
|         <!-- maven plugins --> | ||||
|         <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> | ||||
|         <maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version> | ||||
| 
 | ||||
|     </properties> | ||||
| 
 | ||||
| </project> | ||||
| @ -11,16 +11,9 @@ import lombok.Getter; | ||||
| 
 | ||||
| @Getter | ||||
| public class BookControllerFeignClientBuilder { | ||||
|     private BookClient bookClient = createClient(BookClient.class, | ||||
|       "http://localhost:8081/api/books"); | ||||
|     private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books"); | ||||
| 
 | ||||
|     private static <T> T createClient(Class<T> type, String uri) { | ||||
|         return Feign.builder() | ||||
|           .client(new OkHttpClient()) | ||||
|           .encoder(new GsonEncoder()) | ||||
|           .decoder(new GsonDecoder()) | ||||
|           .logger(new Slf4jLogger(type)) | ||||
|           .logLevel(Logger.Level.FULL) | ||||
|           .target(type, uri); | ||||
|         return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @ -31,9 +31,7 @@ public class BookClientTest { | ||||
| 
 | ||||
|     @Test | ||||
|     public void givenBookClient_shouldRunSuccessfully() throws Exception { | ||||
|         List<Book> books = bookClient.findAll().stream() | ||||
|           .map(BookResource::getBook) | ||||
|           .collect(Collectors.toList()); | ||||
|         List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList()); | ||||
|         assertTrue(books.size() > 2); | ||||
|         log.info("{}", books); | ||||
|     } | ||||
|  | ||||
| @ -57,6 +57,12 @@ | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
| 
 | ||||
|         <dependency> | ||||
|             <groupId>org.assertj</groupId> | ||||
|             <artifactId>assertj-core</artifactId> | ||||
|             <version>${assertj.version}</version> | ||||
|             <scope>test</scope> | ||||
|         </dependency> | ||||
|     </dependencies> | ||||
| 
 | ||||
|     <build> | ||||
| @ -100,6 +106,7 @@ | ||||
|         <org.hamcrest.version>1.3</org.hamcrest.version> | ||||
|         <junit.version>4.12</junit.version> | ||||
|         <mockito.version>1.10.19</mockito.version> | ||||
|         <assertj.version>3.6.1</assertj.version> | ||||
| 
 | ||||
|         <!-- maven plugins --> | ||||
|         <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> | ||||
|  | ||||
							
								
								
									
										18
									
								
								guava/src/test/java/org/baeldung/guava/CustomEvent.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								guava/src/test/java/org/baeldung/guava/CustomEvent.java
									
									
									
									
									
										Normal 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; | ||||
|     } | ||||
| } | ||||
							
								
								
									
										22
									
								
								guava/src/test/java/org/baeldung/guava/EventBusWrapper.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								guava/src/test/java/org/baeldung/guava/EventBusWrapper.java
									
									
									
									
									
										Normal 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); | ||||
|     } | ||||
| 
 | ||||
| 
 | ||||
| } | ||||
							
								
								
									
										33
									
								
								guava/src/test/java/org/baeldung/guava/EventListener.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								guava/src/test/java/org/baeldung/guava/EventListener.java
									
									
									
									
									
										Normal 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; | ||||
|     } | ||||
| } | ||||
| @ -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()); | ||||
|     } | ||||
| } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user