Translate

четвер, 28 лютого 2013 р.

HighLoad FileDistributor: Part 1 - FileCacheAdapter


On previous meetup we discussed theoretical issue: How to develop application which allows to download few dozens small files from server, write some logs about it and execute http call if download was successful?
Actually task is quite easy but... we have few restrictions
1) We have only one Tomcat (means no cluster)
2) Expected number of downloads about 10 000 000  per day

So together we decided
1) Put files in cache
2) Execute async call to remote server
Pretty simple.

So I started implementing solution. First question was how to put file in cache. I didn't find any implemented  solution and only one article.
Below my version of caching files
 
Lets analyze step by step how it works. Fetching file from cache
public InputStream getFile(String fileName) throws IOException {
    StringBuilder lookupFile = new StringBuilder(filePath);
    lookupFile.append("\\");
    lookupFile.append(fileName);
    Path filePath = Paths.get(lookupFile.toString());
    boolean isExist = Files.exists(filePath);
    if (!isExist) {
      log.debug("File with fileName: {} was removed!", fileName);
      remove(fileName);
      return null;
    }
    long lastModified = Files.getLastModifiedTime(filePath).toMillis();
    FileStamp fileStamp = get(fileName);
    if (fileStamp != null && fileStamp.getLastModified() == lastModified) {
      return new ByteArrayInputStream(fileStamp.getContent());
    }
    updateFile(fileName);
    return getFile(fileName);
  }

I use new NIO API just to avoid file lock. As you see I check if file is present on filesystem and return null if there is no such file.
Then I check if file was modified and updated cache if it is needed.

Next method, actually three methods are responsible for inserting file in cache

private void updateFile(String fileName) throws IOException{
    remove(fileName);
    putFile(fileName);
  }

  public void putFile(String fileName) throws IOException {
    tryWriteLockOnKey(fileName, 2000L);
    try {
      if (get(fileName) != null) {
        return;
      }
      StringBuilder lookupFile = new StringBuilder(filePath);
      lookupFile.append(fileName);
      Path filePath = Paths.get(lookupFile.toString());
      byte[] fileContent = getFileContent(filePath);
      long lastModified = Files.getLastModifiedTime(filePath).toMillis();
      FileStamp fileStamp = new FileStamp(fileName, lastModified, fileContent);
      put(fileName, fileStamp);
    } finally {
      releaseWriteLockOnKey(fileName);
    }
  }

  private byte[] getFileContent(Path path) throws IOException {
    byte[] fileContent = Files.readAllBytes(path);
    return fileContent;
  }

Just to avoid parallel cache updating I lock cache record
tryWriteLockOnKey(fileName, 2000L);
In the next part will be described async call to remote server

JavaRanch Game -Test


JavaRanch Game -Test

Test you knowledge !!!



Java EE 7 Survey Results


Оракл опублікував результати опитування, яке він проводивв в кінці минулого року.

Ось тут можна скачати статистику і результати:
http://java.net/attachments/lists/javaee-spec/jsr342-experts/2012-12/46/survey_summary.pdf

А тут саме представлення результатів:
http://java.net/projects/javaee-spec/lists/jsr342-experts/archive/2012-12/message/46



понеділок, 25 лютого 2013 р.

четвер, 21 лютого 2013 р.

BookReview: MapReduce Design Patterns


As you know we take part in O'Reilly review program.
Several weeks ago I received for review "MapReduce Design Patterns" by Donald Miner, Adam Shook.  Actually it was my first experience with mapreduce and especially with hadoop. Hence it force me to read some articles

conclusion 1) This book is not for dummies but...

I've spent some time (not much really) to pick up some basic knowledge about mapreduce and hadoop afterwards it was much easier to understand. Book is well written and easy to read, I would even say that examples are too extensive.

conclusion 2) Good choice if you need  to implement something and don't have enough of knowledge.

All patterns in the book are grouped by such types: Summarization, Filtering, Data Organization, Join, Metapatterns and Input/Output patterns. The materials are well-structured, so it speeds up reading. I really like it 'cause from time to time I need to recall something without parsing the whole book

conclusion 3) book is well organized.

Last chapter is called "Final thoughts and the Future of Design patterns" and it was most interesting chapter for me, but  I will not reveal it so you'll enjoy reading it too))





середу, 20 лютого 2013 р.

JDK 8 Early Access


Oracle дозволив скачувати пре релізи JDK 8 і для випробування нових можливостей Java 8 вам вже не потрібно власноруч компілювати OpenJDK.

Скачати можна тут: http://jdk8.java.net/

Також Oracle активно займається латанням дир в безпеці і в лютому вже вийшло по 2 обновлення Java7 u13, u15  і Java6 u39, u41


ПС. Цікаво куди пропали проміжні версії J6u40 i J7u14 :) ?


понеділок, 18 лютого 2013 р.

Best Best Practices Ever


  1. Write programs for people, not computers.
    1. a program should not require its readers to hold more than a handful of facts in memory at once
    2. names should be consistent, distinctive and meaningful
    3. code style and formatting should be consistent
    4. all aspects of software development should be broken down into tasks roughly an hour long
  2. Automate repetitive tasks.
    1. rely on the computer to repeat tasks
    2. save recent commands in a file for re-use
    3. use a build tool to automate scientific workflows
  3. Use the computer to record history.
    1. software tools should be  used to track computational work automatically


пʼятницю, 15 лютого 2013 р.

середу, 13 лютого 2013 р.

Scaling Scalability: Evolving Twitter Analytics


За остані 2а роки хадупівський кластер виріс від 30 до 4000 машин. Хочете дізнатися the best practice, що використовуються в Twitter для обробки мільйонів твітів щодня? тоді вам сюди:
http://www.infoq.com/presentations/Twitter-Analytics

Фото з нашої 18 зустрічі




вівторок, 12 лютого 2013 р.

Java 8: New Date and Time API


У восьмі версії джави з'явиться нове апі для роботи з датами. Новинка буде основана на базі відомої бібліотеки Joda. Більше можна почитати тут

JDay Lviv is coming


В червні JUG  планує провести Java конференцію. Будемо раді будь-яким думкам, ідеям та зауваженням по темі
Сторінка конференції JDay Lviv

Будемо вдячні всім хто розмістить інформацію про конференцію та посилання на своїх блогах, FB  сторінках, Google+  чи Twitter (хештег #JDayLviv). Чим більшу аудиторію ми залучимо тим якісніші будуть спонсори і відповідно доповідачі.


пʼятницю, 8 лютого 2013 р.

Fridays Fun


Бібліотека для знущання над кастомера
http://code.google.com/p/gag/ 




JUG 18 Feedback


Дорогі Друзі дякую всім за відвідини нашої зустрічі.

Цього разу нас зібралось близько 60 осіб і це була одна з найчисельніших зустрічей за всю історію.
Також це був експеремент. І як кожен експеремент - прийшов час отримати результати.

Напишіть ваші враження, думки, побажання. Опитування є анонімнм, але якщо ви хочите отримати відповідь на ваше запитання чи побажання - заповніть поле зворотнього звязку.


вівторок, 5 лютого 2013 р.

Сьогодні 06.01.2013 перша JUG Lviv 2013


Нагадую. Вже сьогодні перша JUG Lviv 2013, яка розпочнеться о 19:00

За адресою: Готель Рейкарц  - вул. Городоцька 107, конференц-зал
(при вході в готель будуть вказівники з написом JUG). Мапа

На вас чекає експериментальна зустріч на, якій вперше будуть обговорювати питання проходження співбесід, спілкування з фірмами і обговорення ЗАРПЛАТ!

Велике прохання зареєструватись: http://jug-lviv.blogspot.com/2013/01/18-java-user-group.html

Atlassian starter license


In scope of Atlassian sponsorship program we've got few starter licenses on any their products.
If you drive some startup and wannna use Atlassian products contact us by mail jug.lviv@gmail.com
Your startups have to meet following requirements
1) Development team is located in Lviv
2) JVM language based project




Java8 Lambda Code Sample







Code Sample тут

Оригінал статті тут



понеділок, 4 лютого 2013 р.

40 Java Collections Interview Questions and Answers


  1. What is Java Collections Framework? List out some benefits of Collections framework?

    Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack,Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms. Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package. Some of the benefits of collections framework are:
    • Reduced development effort by using core collection classes rather than implementing our own collection classes.
    • Code quality is enhanced with the use of well tested collections framework classes.
    • Reduced effort for code maintenance by using collection classes shipped with JDK.
    • Reusability and Interoperability


System Properties


Кусочок коду, який виведе налаштування вашої системи.
Можна дізнатись цікаві нюанси...

import java.util.Properties;
import java.util.Set;

public class SysProperties {
    public static void main(String[] args) {
        Properties prop = System.getProperties();
        Set<Object> keySet = prop.keySet();
        for(Object obj : keySet){
            System.out.println("System Property: {"+obj.toString()+","+
  System.getProperty(obj.toString())+"}");
        }
    }
}