Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#.Util' - 80 code snippet(s) found

 Sample 1. Get all elements greater than 2, sort them and then push them to a new set, using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Set the predicate or the condition for filtering the elements.

Predicate<Integer> moreThan2Pred = (p) -> (p > 1);

// Use Filter to refine the element set, sort to Sort and Collectors.toSet to get a set out of Stream.

intSet = intSet.stream().filter(moreThan2Pred).sorted().collect(Collectors.toSet());

System.out.println(intSet); // Prints [2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter   sort  java.util.hashset  java.util.stream.Collectors


 Sample 2. Combine two Summaries and Generate a new Summary using Lambda Expression

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();
Set<Integer> intSet2 = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);
intSet2.add(1);
intSet2.add(2);
intSet2.add(3);
intSet2.add(4);

// Use the stream and collectors to Summarize all Integer elements

IntSummaryStatistics summary = intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)));

summary.combine(intSet2.stream().collect(Collectors.summarizingInt(p->((Integer)p))));

System.out.println(summary); // Prints IntSummaryStatistics{count=8, sum=20, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt   summary.combine  java.util.hashset  java.util.stream.Collectors  java.util.IntSummaryStatistics


 Sample 3. Code to find email ids in a string using Pattern.

String text="vivek boy goy vivek@tech.com viv@ek.com sdjs@adjk";
Pattern regex = Pattern.compile("[@]");
Matcher regexMatcher = regex.matcher(text);
int i =0;
int width = 0;
while (regexMatcher.find()) {
if((regexMatcher.start()-10 > 0) && (regexMatcher.end()+10 < text.length())){
width=10;
String[] substr=text.substring(regexMatcher.start()-width,regexMatcher.end()+width).split(" ");
for(int j=0;j<substr.length;j++){
if(substr[j].contains("@") && (substr[j].contains(".com") || substr[j].contains(".net"))){
System.out.println(substr[j]);
}
}
} else {
width=0;
}
}

   Like      Feedback     regex  pattern  string  regexMatcher.find  java.util.regex.Matcher  java.util.regex.Pattern


 Sample 4. Enum with a method to get the constant having specific member element.

public enum JavaFramework {
SPRING("Spring","Web"),
STRUTS("Struts","Web"),
JSF("JSF","View"),
CRUNCH("Apache Crunch","BigData");


public String name;
public String type;

JavaFramework(String name, String type){
this.name = name;
this.type = type;
}

static public List<JavaFramework> getByType(String type) {
List<JavaFramework> frameworks = new ArrayList();
for(JavaFramework framework: JavaFramework.values()){
if(framework.type.equalsIgnoreCase(type)){
frameworks.add(framework);
}
}

return frameworks;
}
}

   Like      Feedback     enum  java.util.list


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Scheduling task using java.util.timer

static {
timer.schedule(new ScheduledTask(), 60000, 60000);
}

private static class Schedule extends TimerTask {
@Override public void run() {
//doSomething();
}
}

   Like      Feedback     java.util.timer  java.util.TimerTask  scheduling task  java.lang  Override


 Sample 6. Convert Time in milliseconds to Days

TimeUnit.DAYS.convert(timeinMs, TimeUnit.MILLISECONDS)

   Like      Feedback     convert time in ms to days  TimeUnit  java.util.concurrent.TimeUnit


 Sample 7. Usage of LinkedHashMap


Map<String,String> linkedhashmap = new LinkedHashMap();
linkedhashmap.put("United States", "Washington");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("South Africa", "Pretoria");
linkedhashmap.put("South Africa", "Cape Town");
linkedhashmap.put("South Africa", "Bloemfontein");

System.out.println(linkedhashmap); // Duplicates not allowed as it's a Map, Insertion Order as its linked Map

   Like      Feedback     LinkedHashMap  Map  HashMap  java.util  collections framework


 Sample 8. Code Sample / Example / Snippet of java.util.zip.DeflaterOutputStream

    private byte[] deflate(byte[] b) throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

DeflaterOutputStream dos = new DeflaterOutputStream(baos);

dos.write(b);

dos.close();

return baos.toByteArray();

}


   Like      Feedback      java.util.zip.DeflaterOutputStream


 Sample 9. Code Sample / Example / Snippet of java.util.zip.GZIPInputStream

  private static CSVReader openCsv(File file) throws IOException {

final Reader fileReader;

if (file.getName().endsWith(".gz")) {

final GZIPInputStream inputStream =

new GZIPInputStream(new FileInputStream(file));

fileReader = new InputStreamReader(inputStream);

} else {

fileReader = new FileReader(file);

}

return new CSVReader(fileReader);

}


   Like      Feedback      java.util.zip.GZIPInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Code Sample / Example / Snippet of java.util.Properties

    public Connection createConnection() throws SQLException {

final Properties info = new Properties();

for (Map.Entry<String, String> entry : map.entrySet()) {

info.setProperty(entry.getKey(), entry.getValue());

}

Connection connection =

DriverManager.getConnection("jdbc:calcite:", info);

for (ConnectionPostProcessor postProcessor : postProcessors) {

connection = postProcessor.apply(connection);

}

return connection;

}


   Like      Feedback      java.util.Properties


 Sample 11. Code Sample / Example / Snippet of java.util.jar.JarOutputStream

    private File createBundle(String symbolicName, String version) throws IOException {

File tmpFile = File.createTempFile("tmpbundle-", "jar");

tmpFile.deleteOnExit();

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

if (symbolicName != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, symbolicName);

}

if (version != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);

}

JarOutputStream target = new JarOutputStream(new FileOutputStream(tmpFile), manifest);

target.close();

return tmpFile;

}


   Like      Feedback      java.util.jar.JarOutputStream


 Sample 12. Java Code to get all images url from html code.

regex = Pattern.compile("[http]");
regexMatcher = regex.matcher(htmlParseData.getHtml());
List tr=htmlParseData.getOutgoingUrls();
imgUrlCounter=0;
for(i=0;i<tr.size();i++){
if(tr.get(i).toString().contains(".jpg") || tr.get(i).toString().contains(".jpeg") || tr.get(i).toString().contains(".gif") || tr.get(i).toString().contains(".bmp")){
url = new URL(tr.get(i).toString());
Image image = new ImageIcon(url).getImage();
}
}

   Like      Feedback     regex  pattern  regex.matcher  html  java.util.regex.pattern  regular expressions


 Sample 13. Usage of HashMap

Map<Integer,String> indexedInfo = new HashMap();
indexedInfo.put(1,"Spain");
indexedInfo.put(2,"Denmark");
indexedInfo.put(3,"China");

   Like      Feedback     hashmap  map  collections  java.util.hashmap


 Sample 14. Sort a List using Collections.sort and comparator

Collections.sort(listClassInfo,new Comparator<ClassInfoBean>(){
public int compare(ClassInfoBean s1,ClassInfoBean s2){
if(s1.name.compareTo(s2.name) < 0){
return -1;
} else {
return 1;
}

}});

   Like      Feedback     sorting   sort   Collections.sort   sort a list   comparator   compare method  java.util.Collections


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. ArrayList of Optional Integers

List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();

// Add Elements

intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));

   Like      Feedback     optional  java 8   list   arraylist   list of optional integers   arraylist of optional  java.util.Optional


 Sample 16. Get current time using GregorianCalendar

Calendar calendar = new GregorianCalendar();
float currentTime = calendar.get( Calendar.HOUR_OF_DAY ) + ((float)calendar.get( Calendar.MINUTE )/100);

   Like      Feedback     GregorianCalendar  Calendar.HOUR_OF_DAY  Calendar.MINUTE  Calendar.java.util.Calendar


 Sample 17. Initialize java.util.date using java.util.Calendar

Date currentDate = Calendar.getInstance().getTime();

   Like      Feedback     calendar  java.util.calendar  java.util  date  java.util.date  Calendar.getTime


 Sample 18. Method to get Date after n days using Calendar

Date getDateAfterDays(int numberOfDays){
   Calendar futureDate = Calendar.getInstance();
   futureDate.setTime(new Date()); // Set Current Date
   futureDate.add(Calendar.DATE, numberOfDays); // Add n days to current Date

   return new Date(futureDate.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.date  calendar.settime  calendar.gettimeinmillis


 Sample 19. Get Date and Time after few Hours

Date getDateTimeAfterNHours(int numberOfHours){
   Calendar futureTime = Calendar.getInstance();
   futureTime.setTime(new Date()); // Set Current Date
   futureTime.add(Calendar.HOUR, numberOfDays); // Add n hours to current Date and Time

   return new Date(futureTime.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.hour  calendar.settime  calendar.gettimeinmillis


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Time Taken to call a method or service

Date date1 = new Date();

// Call Service or Method

Date date2 = new Date();
System.out.println(TimeUnit.SECONDS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Seconds
System.out.println(TimeUnit.MINUTES.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Minutes
System.out.println(TimeUnit.HOURS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Hours

   Like      Feedback     Difference between 2 dates  Time to call a method  TimeUnit  Date.java.util.Date


 Sample 21. Internal Implementation of ArrayList#removeIf

@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);

int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}

// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}

return anyToRemove;
}

   Like      Feedback     Internal Implementation of ArrayList#removeIf  java.util.function.Predicate  java.util.Objects  java.util.Objects  java.util.ConcurrentModificationException.ConcurrentModificationException


 Sample 22. Usage of org.joda.time.DateMidnight

DateMidnight currentDate = new DateMidnight();
DateMidnight dateafterAMonth = currentDate.plusMonths(1);
Date javaSedateAfterAMonth = dateafterAMonth.toDate();

   Like      Feedback     org.joda.time.DateMidnight  java.util.Date  Date  Add month to Date


 Sample 23. Usage of TreeMap

Map<String,String> treemap = new TreeMap();
treemap.put("United States", "Washington");
treemap.put("Canada", "Ottawa");
treemap.put("Canada", "Ottawa");
treemap.put("South Africa", "Pretoria");
treemap.put("South Africa", "Cape Town");
treemap.put("South Africa", "Bloemfontein");

System.out.println(treemap); // Duplicate Not allowed as it's a Map, Ordered by Keys as it's a TreeMap

   Like      Feedback     TreeMap  Map  java.util


 Sample 24. Get the Date object using the TimeZone

TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET);
Date expectedZone = createCalendar(zone, 20051231, 0).getTime();

   Like      Feedback     TimeZone  java.util.TimeZone  Date  Calendar


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Usage of Java Collections Stack

Stack<INodeDirectory> directories = new Stack<INodeDirectory>();
for(directories.push((INodeDirectory)inode); !directories.isEmpty(); ) {
   INodeDirectory d = directories.pop();
}

   Like      Feedback     stack  collections  java.util


 Sample 26. Code Sample / Example / Snippet of org.apache.hadoop.util.Daemon

  public static void main(String[] argv) throws Exception {

StringUtils.startupShutdownMessage(SecondaryNameNode.class, argv, LOG);

Configuration tconf = new Configuration();

if (argv.length >= 1) {

SecondaryNameNode secondary = new SecondaryNameNode(tconf);

int ret = secondary.processArgs(argv);

System.exit(ret);

}



Daemon checkpointThread = new Daemon(new SecondaryNameNode(tconf));

checkpointThread.start();

}


   Like      Feedback      org.apache.hadoop.util.Daemon


 Sample 27. Code Sample / Example / Snippet of org.apache.hadoop.util.DataChecksum

  private static BlockMetadataHeader readHeader(short version, DataInputStream in) 

throws IOException {

DataChecksum checksum = DataChecksum.newDataChecksum(in);

return new BlockMetadataHeader(version, checksum);

}


   Like      Feedback      org.apache.hadoop.util.DataChecksum


 Sample 28. Code Sample / Example / Snippet of org.apache.hadoop.util.Shell.ShellCommandExecutor

    public void runScript(List<String> args, File dir) throws IOException {

ShellCommandExecutor shexec =

new ShellCommandExecutor(args.toArray(new String[0]), dir);

shexec.execute();

int exitCode = shexec.getExitCode();

if (exitCode != 0) {

throw new IOException("Task debug script exit with nonzero status of "

+ exitCode + ".");

}

}


   Like      Feedback      org.apache.hadoop.util.Shell.ShellCommandExecutor


 Sample 29. Code Sample / Example / Snippet of org.apache.hadoop.util.MergeSort

  public RawKeyValueIterator sort() {

MergeSort m = new MergeSort(this);

int count = super.count;

if (count == 0) return null;

int [] pointers = super.pointers;

int [] pointersCopy = new int[count];

System.arraycopy(pointers, 0, pointersCopy, 0, count);

m.mergeSort(pointers, pointersCopy, 0, count);

return new MRSortResultIterator(super.keyValBuffer, pointersCopy,

super.startOffsets, super.keyLengths, super.valueLengths);

}


   Like      Feedback      org.apache.hadoop.util.MergeSort


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Code Sample / Example / Snippet of java.util.StringTokenizer

  public static List<String> getNamedOutputsList(JobConf conf) {

List<String> names = new ArrayList<String>();

StringTokenizer st = new StringTokenizer(conf.get(NAMED_OUTPUTS, ""), " ");

while (st.hasMoreTokens()) {

names.add(st.nextToken());

}

return names;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 31. Code Sample / Example / Snippet of java.util.Calendar

    public static double year()

{

Calendar cal = Calendar.getInstance();

return cal.get(Calendar.YEAR);

}


   Like      Feedback      java.util.Calendar


 Sample 32. Code Sample / Example / Snippet of java.util.EventListener

    private void readObject(ObjectInputStream s)

throws IOException, ClassNotFoundException {

listenerList = NULL_ARRAY;

s.defaultReadObject();

Object listenerTypeOrNull;



while (null != (listenerTypeOrNull = s.readObject())) {

ClassLoader cl = Thread.currentThread().getContextClassLoader();

EventListener l = (EventListener)s.readObject();

String name = (String) listenerTypeOrNull;

ReflectUtil.checkPackageAccess(name);

add((Class<EventListener>)Class.forName(name, true, cl), l);

}

}




   Like      Feedback      java.util.EventListener


 Sample 33. Code Sample / Example / Snippet of java.util.Map

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

Map map = (Map) operand;

String host = (String) map.get("host");

String database = (String) map.get("database");

return new MongoSchema(host, database);

}


   Like      Feedback      java.util.Map


 Sample 34. Code Sample / Example / Snippet of java.util.Random

  public Enumerable<Object[]> scan(DataContext root) {

final Random random = seed >= 0 ? new Random(seed) : new Random();

final Maze maze = new Maze(width, height);

final PrintWriter pw = new PrintWriter(System.out);

maze.layout(random, pw);

if (Maze.DEBUG) {

maze.print(pw, true);

}

return new AbstractEnumerable<Object[]>() {

public Enumerator<Object[]> enumerator() {

final Set<Integer> solutionSet;

if (solution) {

solutionSet = maze.solve(0, 0);

} else {

solutionSet = null;

}

return Linq4j.transform(maze.enumerator(solutionSet),

new Function1<String, Object[]>() {

public Object[] apply(String s) {

return new Object[] {s};

}

});

}

};

}


   Like      Feedback      java.util.Random


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Code Sample / Example / Snippet of java.util.TimeZone

  private static final FastDateFormat TIME_FORMAT_TIMESTAMP;



static {

TimeZone gmt = TimeZone.getTimeZone("GMT");

TIME_FORMAT_DATE = FastDateFormat.getInstance("yyyy-MM-dd", gmt);

TIME_FORMAT_TIME = FastDateFormat.getInstance("HH:mm:ss", gmt);

TIME_FORMAT_TIMESTAMP =

FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", gmt);

}


   Like      Feedback      java.util.TimeZone


 Sample 36. Code Sample / Example / Snippet of java.util.Calendar

  private SparkHandlerImpl() {

classServer = new HttpServer(CLASS_DIR);



classServer.start();

System.setProperty("spark.repl.class.uri", classServer.uri());



final Calendar calendar = Calendar.getInstance();

classId = new AtomicInteger(

calendar.get(Calendar.HOUR_OF_DAY) * 10000

+ calendar.get(Calendar.MINUTE) * 100

+ calendar.get(Calendar.SECOND));

}


   Like      Feedback      java.util.Calendar


 Sample 37. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Spacer

    public MapType(SqlParserPos pos) {

super(pos, Op.MAP_TYPE);

this.keyType = new ScalarType(pos, "int");

this.valueType = new ScalarType(pos, "int");

}

}



static class UnParser {

final StringBuilder buf = new StringBuilder();

final Spacer spacer = new Spacer(0);


   Like      Feedback      org.apache.calcite.avatica.util.Spacer


 Sample 38. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Quoting

  private static final ThreadLocal<boolean[]> LINUXIFY =

new ThreadLocal<boolean[]>() {

@Override protected boolean[] initialValue() {

return new boolean[] {true};

}

};



Quoting quoting = Quoting.DOUBLE_QUOTE;


   Like      Feedback      org.apache.calcite.avatica.util.Quoting


 Sample 39. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.Casing

  private static final ThreadLocal<boolean[]> LINUXIFY =

new ThreadLocal<boolean[]>() {

@Override protected boolean[] initialValue() {

return new boolean[] {true};

}

};



Quoting quoting = Quoting.DOUBLE_QUOTE;

Casing unquotedCasing = Casing.TO_UPPER;


   Like      Feedback      org.apache.calcite.avatica.util.Casing


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Code Sample / Example / Snippet of java.util.regex.Matcher

    private void defineVariables(String line) {

Matcher varDefn = matchesVarDefn.matcher(line);

if (varDefn.lookingAt()) {

String var = varDefn.group(1);

String val = varDefn.group(2);

vars.define(var, val);

} else {

String[] words = splitWords.split(line);

for (String var : words) {

String value = System.getenv(var);

vars.define(var, value);

}

}

}


   Like      Feedback      java.util.regex.Matcher


 Sample 41. Code Sample / Example / Snippet of java.util.StringTokenizer

    private List<String> tokenize(String s) {

List<String> result = new ArrayList<>();

StringTokenizer tokenizer = new StringTokenizer(s);

while (tokenizer.hasMoreTokens()) {

result.add(tokenizer.nextToken());

}

return result;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 42. Code Sample / Example / Snippet of org.apache.calcite.util.JsonBuilder

    public final AssertThat withMaterializations(String model,

Function<JsonBuilder, List<Object>> materializations) {

final JsonBuilder builder = new JsonBuilder();

final List<Object> list = materializations.apply(builder);

final String buf =

"materializations: " + builder.toJsonString(list);

final String model2;

if (model.contains("defaultSchema: 'foodmart'")) {

model2 = model.replace("]",

", { name: 'mat', "

+ buf

+ "} "

+ "]");

} else if (model.contains("type: ")) {

model2 = model.replace("type: ",

buf + ", "

+ "type: ");

} else {

throw new AssertionError("do not know where to splice");

}

return withModel(model2);

}


   Like      Feedback      org.apache.calcite.util.JsonBuilder


 Sample 43. Code Sample / Example / Snippet of java.util.Collection

      public Void apply(ResultSet resultSet) {

++executeCount;

try {

final Collection result =

CalciteAssert.toStringList(resultSet,

ordered ? new ArrayList<String>() : new TreeSet<String>());

if (executeCount == 1) {

expected = result;

} else {

if (!expected.equals(result)) {

assertThat(newlineList(result), equalTo(newlineList(expected)));

fail("oops");

}

}

return null;

} catch (SQLException e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      java.util.Collection


 Sample 44. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.TimeUnitRange

  private void checkTimestampString(String s, long d) {

assertThat(unixTimestampToString(d), equalTo(s));

assertThat(timestampStringToUnixDate(s), equalTo(d));

}



@Test public void testIntervalYearMonthToString() {

TimeUnitRange range = TimeUnitRange.YEAR_TO_MONTH;

assertEquals("+0-00", intervalYearMonthToString(0, range));

assertEquals("+1-00", intervalYearMonthToString(12, range));

assertEquals("+1-01", intervalYearMonthToString(13, range));

assertEquals("-1-01", intervalYearMonthToString(-13, range));

}


   Like      Feedback      org.apache.calcite.avatica.util.TimeUnitRange


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.ByteString

  private void thereAndBack(byte[] bytes) {

final ByteString byteString = new ByteString(bytes);

final byte[] bytes2 = byteString.getBytes();

assertThat(bytes, equalTo(bytes2));



final String base64String = byteString.toBase64String();

final ByteString byteString1 = ByteString.ofBase64(base64String);

assertThat(byteString, equalTo(byteString1));

}


   Like      Feedback      org.apache.calcite.avatica.util.ByteString


 Sample 46. Code Sample / Example / Snippet of org.apache.hc.core5.util.ByteArrayBuffer

    public void testConstructor() throws Exception {

final ByteArrayBuffer buffer = new ByteArrayBuffer(16);

Assert.assertEquals(16, buffer.capacity());

Assert.assertEquals(0, buffer.length());

Assert.assertNotNull(buffer.buffer());

Assert.assertEquals(16, buffer.buffer().length);

try {

new ByteArrayBuffer(-1);

Assert.fail("IllegalArgumentException should have been thrown");

} catch (final IllegalArgumentException ex) {

}

}


   Like      Feedback      org.apache.hc.core5.util.ByteArrayBuffer


 Sample 47. Code Sample / Example / Snippet of java.util.BitSet

    public static BitSet INIT_BITSET(final int ... b) {

final BitSet bitset = new BitSet();

for (final int aB : b) {

bitset.set(aB);

}

return bitset;

}


   Like      Feedback      java.util.BitSet


 Sample 48. Usage of org.springframework.security.web.util.matcher.RequestMatcher

RequestMatcher matcher = new RegexRequestMatcher("(.*/(html|php|htm)/.*)", RequestMethod.GET.name());
registry.addInterceptor(new MyInterceptor(matcher));

   Like      Feedback     rg.springframework.security.web.util.matcher.RequestMatche


 Sample 49. Code Sample / Example / Snippet of java.util.List

    private static List convertArrayToList(Object array)

{

int len = Array.getLength(array);

List list = new ArrayList(len);

for (int i = 0; i < len; i++)

{

list.add(Array.get(array, i));

}

return list;

}


   Like      Feedback      java.util.List


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Code Sample / Example / Snippet of java.util.regex.Pattern

    private long getStoreId(File storeFile) {

Pattern p = Pattern.compile(m_name + "-(\d+)");

Matcher m = p.matcher(storeFile.getName());

if (m.find()) {

return Long.parseLong(m.group(1));

}

throw new RuntimeException("Invalid store file name: " + storeFile.getName());

}




   Like      Feedback      java.util.regex.Pattern


 Sample 51. Code Sample / Example / Snippet of java.util.concurrent.ScheduledExecutorService

    public void postEvent(final String topic, Map<String, String> payload) {

final Map<String, String> eventPayload = new HashMap<>(payload);

for (final EventListener listener : m_listeners) {

ScheduledExecutorService executor = getExecutorService();

if (executor.isShutdown()) {

logWarning("Cannot post event, executor is shut down!");

return;

}

executor.submit(new Runnable() {

@Override

public void run() {

try {

listener.handle(topic, eventPayload);

}

catch (Exception e) {

logWarning("Exception while posting event", e);

}

}

});

}

}


   Like      Feedback      java.util.concurrent.ScheduledExecutorService


 Sample 52. Code Sample / Example / Snippet of java.util.concurrent.locks.Lock

    public int getDeploymentVersionLimit() {

Lock lock = m_lock.readLock();

lock.lock();

try {

return m_deploymentVersionLimit;

}

finally {

lock.unlock();

}

}


   Like      Feedback      java.util.concurrent.locks.Lock


 Sample 53. Code Sample / Example / Snippet of java.util.Iterator

    public void validateRangeIterators() {

SortedRangeSet srs1 = new SortedRangeSet("1-10");

Iterator i1 = srs1.rangeIterator();

assert i1.hasNext() : "We should have one Range instance in our iterator.";

assert ((Range) i1.next()).toRepresentation().equals("1-10");

assert !i1.hasNext() : "There should be only one instance in our iterator.";

SortedRangeSet srs2 = new SortedRangeSet("1-5,8,10-15");

Iterator i2 = srs2.rangeIterator();

assert i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& !i2.hasNext() : "There should be exactly three Range instances in our iterator.";

SortedRangeSet srs3 = new SortedRangeSet("");

assert !srs3.iterator().hasNext() : "Iterator should be empty.";

}


   Like      Feedback      java.util.Iterator


 Sample 54. Code Sample / Example / Snippet of java.util.Set

    public Set getExtendList() {

Set set = new HashSet();

for (Iterator i = requirements.iterator(); i.hasNext();) {

RequirementImpl impl = (RequirementImpl) i.next();

if (impl.isExtend())

set.add(impl);

}

return set;

}


   Like      Feedback      java.util.Set


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 55. Code Sample / Example / Snippet of java.util.Random

    private File createRandomFileWithContent() throws IOException {

OutputStream fileOut = null;

File file = null;

try {

file = FileUtils.createTempFile(null);

fileOut = new FileOutputStream(file);

byte[] byteArray = new byte[12345];

Random randomContentCreator = new Random();

randomContentCreator.nextBytes(byteArray);

fileOut.write(byteArray);



return file;

}

finally {

try {

if (fileOut != null) {

fileOut.close();

}

}

catch (IOException e) {

throw e;

}

}

}


   Like      Feedback      java.util.Random


 Sample 56. Code Sample / Example / Snippet of java.util.StringTokenizer

	public LowestID(String representation) {

try {

StringTokenizer st = new StringTokenizer(representation, ",");

m_targetID = Codec.decode(st.nextToken());

m_storeID = Long.parseLong(st.nextToken());

m_lowestID = Long.parseLong(st.nextToken());

}

catch (NoSuchElementException e) {

throw new IllegalArgumentException("Could not create lowest ID object from: " + representation);

}

}


   Like      Feedback      java.util.StringTokenizer


 Sample 57. Code Sample / Example / Snippet of static org.apache.ace.test.utils.TestUtils.UNIT

public class WorkspaceManagerImplTest {

@SuppressWarnings("serial")

@Test(groups = { UNIT })

public void testPropertyGetter() {

WorkspaceManagerImpl s = new WorkspaceManagerImpl();

Assert.assertEquals(s.getProperty(new Properties() {{ put("key", "value"); }}, "key", "notused"), "value");

Assert.assertEquals(s.getProperty(new Properties() {{ put("unusedkey", "value"); }}, "key", "default"), "default");

Assert.assertEquals(s.getProperty(null, "key", "default"), "default");

}

}


   Like      Feedback      static org.apache.ace.test.utils.TestUtils.UNIT


 Sample 58. Code Sample / Example / Snippet of java.util.concurrent.CountDownLatch

    public void testTooLongTask() throws Exception {

final CountDownLatch latch = new CountDownLatch(5);



Executer executer = new Executer(new Runnable() {

public void run() {

try {

Thread.sleep(20);

latch.countDown();

}

catch (InterruptedException e) {

e.printStackTrace();

}

}

});

executer.start(10);

assert latch.await(1, TimeUnit.SECONDS);

}


   Like      Feedback      java.util.concurrent.CountDownLatch


 Sample 59. Code Sample / Example / Snippet of java.util.Calendar

    private static Calendar getToday() {

Calendar cal = Calendar.getInstance();

cal.set(Calendar.HOUR_OF_DAY, 12);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

return cal;

}


   Like      Feedback      java.util.Calendar


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 60. Code Sample / Example / Snippet of static org.apache.ace.test.utils.Util.dictionary

	protected void configureProvisionedServices() throws Exception {

m_echoServlet = new EchoServlet();



Dictionary<String, String> dictionary = new Hashtable<>();

dictionary.put(HttpConstants.ENDPOINT, "/echoServlet");

m_echoServletService = m_dependencyManager.createComponent()

.setImplementation(m_echoServlet)

.setInterface(Servlet.class.getName(), dictionary);



m_mockHttp = new MockHttpService();

m_mockHttpService = m_dependencyManager.createComponent()

.setImplementation(m_mockHttp)

.setInterface(HttpService.class.getName(), null);

}


   Like      Feedback      static org.apache.ace.test.utils.Util.dictionary


 Sample 61. Code Sample / Example / Snippet of static org.apache.ace.it.repository.Utils.get

    public void testEmptyRepository() throws Exception {

Repository mock = new MockDeploymentRepository("", null, null);

TestUtils.configureObject(m_backend, Repository.class, mock);



List<String> versions = m_backend.getVersions(TARGET);

assert versions.size() == 0 : "From an empty repository, we should get 0 versions, but we get "

+ versions.size();

}


   Like      Feedback      static org.apache.ace.it.repository.Utils.get


 Sample 62. Code Sample / Example / Snippet of java.util.concurrent.Semaphore

    private void removeRepository(String instanceName) throws IOException, InterruptedException, InvalidSyntaxException {

Configuration[] configs = listConfigurations("(factory.instance.pid=" + instanceName + ")");

if ((configs != null) && (configs.length > 0)) {

final Semaphore sem = new Semaphore(0);

ServiceTracker<Object, Object> tracker = new ServiceTracker<Object, Object>(m_bundleContext, m_bundleContext.createFilter("(factory.instance.pid=" + instanceName + ")"), null) {

@Override

public void removedService(ServiceReference<Object> reference, Object service) {

super.removedService(reference, service);

sem.release();

}

};

tracker.open();



try {

configs[0].delete();



if (!sem.tryAcquire(1, TimeUnit.SECONDS)) {

throw new IOException("Instance did not get removed in time.");

}

}

finally {

tracker.close();

}

}

}


   Like      Feedback      java.util.concurrent.Semaphore


 Sample 63. Code Sample / Example / Snippet of java.util.jar.Manifest

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Manifest


 Sample 64. Code Sample / Example / Snippet of java.util.jar.Attributes

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Attributes


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 65. Code Sample / Example / Snippet of java.util.Properties

    public void init(BundleContext context, DependencyManager manager) throws Exception {

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(DeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(DEPLOYMENT_PID))

.add(createServiceDependency().setService(StreamGenerator.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProvider.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProcessor.class).setRequired(false).setCallbacks("addProcessor", "removeProcessor"))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(AgentDeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(AGENT_PID))

.add(createServiceDependency().setService(ConnectionFactory.class).setRequired(true))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);



Properties props = new Properties();

props.put("pattern", "/*");

manager.add(createComponent()

.setInterface(Filter.class.getName(), null)

.setImplementation(OverloadedFilter.class)

);

}


   Like      Feedback      java.util.Properties


 Sample 66. Code Sample / Example / Snippet of java.util.concurrent.ExecutorService

    public void hundredStreamsConcurrently() throws Exception {

ExecutorService e = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {

e.execute(new Runnable() {

public void run() {

for (int i = 0; i < 10; i++) {

try {

isJarInputStreamReadable();

}

catch (Exception e) {

m_failure = e;

}

}

}

});

}

e.shutdown();

e.awaitTermination(10, TimeUnit.SECONDS);



assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();

}




   Like      Feedback      java.util.concurrent.ExecutorService


 Sample 67. Code Sample / Example / Snippet of java.util.Timer

    public void shutdown(long delay) {

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

try {

m_context.getBundle(0).stop();

}

catch (BundleException e) {

e.printStackTrace();

}

}

}, delay);

}


   Like      Feedback      java.util.Timer


 Sample 68. Code Sample / Example / Snippet of org.apache.ace.client.rest.util.WebResource

    public static WebResource createEntity(Client c, WebResource work, String type, String data) throws IOException {

WebResource entity = work.path(type);

try {

entity.post(data);

throw new IOException("Could not create " + type + " with data " + data);

}

catch (WebResourceException e2) {

return c.resource(e2.getResponse().getLocation());

}

}


   Like      Feedback      org.apache.ace.client.rest.util.WebResource


 Sample 69. Code Sample / Example / Snippet of org.apache.felix.framework.util.VersionRange

    private boolean checkOSVersions(String currentOSVersion, String[] osversions)

throws BundleException

{

for (int i = 0; (osversions != null) && (i < osversions.length); i++)

{

try

{

VersionRange range = VersionRange.parse(osversions[i]);

if (range.isInRange(new Version(currentOSVersion)))

{

return true;

}

}

catch (Exception ex)

{

throw new BundleException(

"Error evaluating osversion: " + osversions[i], ex);

}

}

return false;

}


   Like      Feedback      org.apache.felix.framework.util.VersionRange


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 70. Code Sample / Example / Snippet of java.util.Vector

    private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";



String propertiesFile = DEFAULT_PROPERTIES_FILE;

String broker = "tcp://localhost:61616";

String connectID = "QueueMonitor";

String username = "QueueMonitor";

String password = "QueueMonitor";

String browseQueues = "Q1,Q2,Q3";

String textFontName = "Dialog";

String textFontStyle = "PLAIN";

String textFontSize = "12";

String title = "QueueMonitor";



JTextArea textArea = new JTextArea();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton browseButton = new JButton("Browse Queues");



Vector theQueues = new Vector();


   Like      Feedback      java.util.Vector


 Sample 71. Code Sample / Example / Snippet of org.apache.bcel.util.SyntheticRepository

    private JavaClass getClassFrom(final String where, final String clazzname)

throws ClassNotFoundException

{

final SyntheticRepository repos = createRepos(where);

return repos.loadClass(clazzname);

}


   Like      Feedback      org.apache.bcel.util.SyntheticRepository


 Sample 72. Code Sample / Example / Snippet of org.apache.bcel.util.BCELifier

    public void test() throws Exception {

final OutputStream os = new ByteArrayOutputStream();

final JavaClass java_class = BCELifier.getJavaClass("Java8Example");

assertNotNull(java_class);

final BCELifier bcelifier = new BCELifier(java_class, os);

bcelifier.start();

}


   Like      Feedback      org.apache.bcel.util.BCELifier


 Sample 73. Code Sample / Example / Snippet of org.apache.bcel.util.InstructionFinder

    public void testSearch() {

final InstructionList il = new InstructionList();

il.append(new ILOAD(1));

il.append(new ILOAD(2));

il.append(new IADD());

il.append(new ISTORE(3));

final InstructionFinder finder = new InstructionFinder(il);



final Iterator<?> it = finder.search("ILOAD IADD", il.getInstructionHandles()[0], null );

final InstructionHandle[] ihs = (InstructionHandle[])it.next();

assertEquals(2, ihs.length);

assertEquals(ihs[0].getInstruction(), new ILOAD(2));

assertEquals(ihs[1].getInstruction(), new IADD());

}


   Like      Feedback      org.apache.bcel.util.InstructionFinder


 Sample 74. Code Sample / Example / Snippet of org.apache.bcel.util.ClassPath

    public static ClassPath.ClassFile lookupClassFile( final String class_name ) {

try {

final ClassPath path = repository.getClassPath();

if (path == null) {

return null;

}

return path.getClassFile(class_name);

} catch (final IOException e) {

return null;

}

}


   Like      Feedback      org.apache.bcel.util.ClassPath


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 75. Code Sample / Example / Snippet of org.apache.bcel.util.ClassQueue

    public JavaClass[] getAllInterfaces() throws ClassNotFoundException {

final ClassQueue queue = new ClassQueue();

final Set<JavaClass> allInterfaces = new TreeSet<>();

queue.enqueue(this);

while (!queue.empty()) {

final JavaClass clazz = queue.dequeue();

final JavaClass souper = clazz.getSuperClass();

final JavaClass[] _interfaces = clazz.getInterfaces();

if (clazz.isInterface()) {

allInterfaces.add(clazz);

} else {

if (souper != null) {

queue.enqueue(souper);

}

}

for (final JavaClass _interface : _interfaces) {

queue.enqueue(_interface);

}

}

return allInterfaces.toArray(new JavaClass[allInterfaces.size()]);

}


   Like      Feedback      org.apache.bcel.util.ClassQueue


 Sample 76. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BitInputStream

    public void testClearBitCache() throws IOException {

final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);

assertEquals(0x08, bis.readBits(4));

bis.clearBitCache();

assertEquals(0, bis.readBits(1));

bis.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BitInputStream


 Sample 77. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BoundedInputStream

    public void writeTo(final ZipArchiveOutputStream target) throws IOException {

backingStore.closeForWriting();

final InputStream data = backingStore.getInputStream();

for (final CompressedEntry compressedEntry : items) {

final BoundedInputStream rawStream = new BoundedInputStream(data, compressedEntry.compressedSize);

target.addRawArchiveEntry(compressedEntry.transferToArchiveEntry(), rawStream);

rawStream.close();

}

data.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BoundedInputStream


 Sample 78. Code Sample / Example / Snippet of org.apache.commons.compress.utils.CountingOutputStream

    public void output() throws Exception {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final CountingOutputStream o = new CountingOutputStream(bos);

o.write(1);

assertEquals(1, o.getBytesWritten());

o.write(new byte[] { 2, 3 });

assertEquals(3, o.getBytesWritten());

o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);

assertEquals(4, o.getBytesWritten());

o.count(-1);

assertEquals(4, o.getBytesWritten());

o.count(-2);

assertEquals(2, o.getBytesWritten());

o.close();

assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());

}


   Like      Feedback      org.apache.commons.compress.utils.CountingOutputStream


 Sample 79. Usage of java.util.stream.Stream

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(4, 5);

Stream.of(list1, list1)
.flatMap(list -> list.stream())
.forEach(System.out::println);

   Like      Feedback     Stream.flatMap  System.out::println


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 80. Usage of java.util.function.BiPredicate

BiPredicate<String, String> predicate = (s1, s2) -> (s1.equals(s2));

System.out.println(predicate.test("BUGGY", "BREAD"));

   Like      Feedback     BiPredicate  Java 8 BiPredicate



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner