voronyansky
voronyansky
Yegor Voronyansky
3 posts
Hello everyone! I am a java developer. This sound like a diagnos. Feel free to ask anything.
Don't wanna be here? Send us removal request.
voronyansky · 8 years ago
Text
Iterator
All we know iterator pattern it allow traverse collection without knowledge about internal collection work. This pattern have some benefits and pitfalls.
Benefits
1. Convinient traversal operation 2. Remove elements 3. Avoid NoSuchElementException by calling hasNext method
Pitfalls
1. When you call hasNext method pointer at the iterator does not move to the next value 2. When you call next method from iterator internal pointer move to the next value
Simple example of usage
public class HelloIterator {    public static void main(String[] args) {      List<String> strings = new ArrayList<>();      string.add("one");      string.add("two");      string.add("three");
     Iterator<String> iterator = strings.iterator();
     while (iterator.hasNext()) {         System.out.println(iterator.next());      }
   } } When you execute this code you should see this: one two three
Iterator implementation
 private class More Itr implements Iterator<E> {         int cursor;       // index of next element to return         int lastRet = -1; // index of last element returned; -1 if no such         int expectedModCount = modCount;
        public boolean More hasNext() {             return cursor != size;         }
        @SuppressWarnings("unchecked")         public E More next() {             checkForComodification();             int i = cursor;             if (i >= size)                 throw new NoSuchElementException();             Object[] elementData = ArrayList.this.elementData;             if (i >= elementData.length)                 throw new ConcurrentModificationException();             cursor = i + 1;             return (E) elementData[lastRet = i];        }
        public void More remove() {             if (lastRet < 0)                throw new IllegalStateException();             checkForComodification();
            try {                 ArrayList.this.remove(lastRet);                 cursor = lastRet;                 lastRet = -1;                 expectedModCount = modCount;             } catch (IndexOutOfBoundsException ex) {                 throw new ConcurrentModificationException();             }         }
        @Override         @SuppressWarnings("unchecked")         public void More forEachRemaining(Consumer<? super E> consumer) {             Objects.requireNonNull(consumer);             final int size = ArrayList.this.size;             int i = cursor;             if (i >= size) {                 return;             }             final Object[] elementData = ArrayList.this.elementData;             if (i >= elementData.length) {                 throw new ConcurrentModificationException();             }             while (i != size && modCount == expectedModCount) {                 consumer.accept((E) elementData[i++]);             }             // update once at end of iteration to reduce heap write traffic             cursor = i;             lastRet = i - 1;             checkForComodification();         }
        final void checkForComodification() {             if (modCount != expectedModCount)                 throw new ConcurrentModificationException();         }     } First method hasNext() return true if cursor(pointer on the current element) not equals to the size of list. Next memthod next() execute checking that list not changed, if otherwise throw ConcurrentModificationException, further step is move cursor to the next position and update lastRet variable which contains last returned element and finally return element.
Your own iterator
If you would like to create your own iterator - it is possible, all your need is implement Iterator interface. Go to the create Iterator which return only odd numbers. public class OddIterator<Integer> implements Iterator<Integer> {
  private final int[] values;   private int cursor;   private int size;
  public OddIterator(final int[] values) {     this.values = values;     this.size = this.length;     this.cursor = 0;   }
  @Override   public boolean hasNext() {      return this.cursor != this.size;   }
  @Override   public Integer next() {     return findOdd();   }
  @Override   public void remove() {      throw UnsupportedOperationException();   }
  @Override   public void More forEachRemaining(Consumer<? super E> consumer) {       throw UnsupportedOperationException();   }
  private int findOdd() {     int result 0;     for (int index = cursor; index < this.size; index++) {        if (index % / 2 == 0) {           result = index;           cursor = index;        }     }     return result;   }
} This iterator will be return only odd numbers from array. But it is a very simple implementation which not support remove and other more complex operations.
3 notes · View notes
voronyansky · 8 years ago
Text
Java Servlet Tutorial
Preface
All java web application based on servlet, knowledge about servlet it is basic for start develop web apps on the Java. Inside all java web frameworks use servlets.
Let’s start
First you need to add to your pom.xml dependency on Servlet API. Scope value is provided - this means that this library which be provided by servlet container such as Tomcat or Jetty. Java web app should be packaged in war. Servlet Container provide for environment, sockets, manage resources and class loading for servlets. All java application which use maven should have three dirs at the src/main, it is java - hold source code, resources - hold config files and webapp - contains file which describe that this is web app. Third directory interesting for us. At this should be WEB-INF directory which must contain web.xml - deployment descriptor which needs for servlet container.
Configuration
When I try make my first servlet app, I get stuck - xml configuration does not works and I am start using annotations. XML configuration must be placed at the web.xml, otherwise annotations based configuration should be placed at the class file. XML Configuration: <web-app> <servlet>     <servlet-name>HelloServlet</servlet-name>        <servlet-class>me.vrnsky.HelloServlet</servlet-class>   </servlet>   <servlet-mapping>   <servlet-name>HelloServlet</servlet-name>        <url-pattern>/hello</url-pattern>   </servlet-mapping> </web-app> Annotations configuration @WebServlet("/hello") public class HelloServlet {
}
Some code
Let’s create a first servlet - create a package at the java directory and create on it Index class. It must extends HttpServletClass which contains method for handle HTTP requests. And another three interesting method is init, service and destroy. What does this method ? First of it is create servlet object, second run at the endless loop and serve HTTP requests and last it call when servlet container shut down. Note that servlet container do not instant servlet object until receive request for servlet. It may change by set load-on-startup parameter. Another important thing that on all servlet container exist ONLY ONE object of servlet.
Override one of servlet method
By default servlet call doGet method, try to override it. We want to get some response from server in utf-8. For this we should write this code. Notice that servlet have a PrintWriter and OutputStreamWriter do not use it together, if you try to use this together you get an exception.
@WebServlet("/hello") public class HelloServlet {
  @Override   public void doGet(HttpServletRequest req, HttpServletResponse resp) throws Exception {      resp.setContentType("text/utf-8");      PrintWriter writer = resp.getWriter();      writer.append("hello, I am a servlet!");      writer.flush();   } }
At this time most used method is doGet and doPost, other uses but less at the real web app.
doTrace - check trace of request
doPut - update data on the server
doDelete - delete data from server
doGet - get data from server
doPost - send data to server(not idempotent method, because produce different data)
doHead - ask about header without message
doOptions - return server options
doPatch - frequency update data on server
Another important thing
When servlet container receive an request it create two object HttpServletRequest and HttpServletRespone and give it to the thread of Servlet by this way servlet may serve a few user at one time, this thing allow improve speed of responding to the user.
A small task to the servlet and it’s solution
How to count how many users ask about some servlets? For solution I have two idea - thread local - which allow contains variable for current thread and atomic constant. First is not suitable for this and second is very suitable for it.
@WebServlet("/counter") public class Counter {
  private static final AtomicInteger COUNTER = new AtomicInteger(0);
  @Override   public void doGet(HttpServletRequest req, HttpServletResponse resp) throws Exception {      resp.setContentType("text/utf-8");      PrintWriter writer = resp.getWriter();      writer.append(String.format("%s user visit this page", COUNTER.incrementAndGet()));      writer.flush();   } }
Related links
Oracle Servlet Docs
0 notes
voronyansky · 8 years ago
Text
I return to this blog platform
Hello everyone! Recently I was again start bloggin on this platfrom. Why I start again? For improve my skills in communication and writing. Also for better understanding English, for me English is not native language. Specially for me native language is Russian.
What I am tell about at this blog?
My blog post will be about open source project which will intrested for me, also I will write about Java programming language. And the third part of blog will be about productivity and other relevant subject of programming.
I am always open for disscussion and happy to answer for your question!
Feel free to comment and tell what you intresting in programming?
0 notes