working on it ...

Filters

Explore Public Snippets

Sort by

Found 40k snippets

    public by giovanni.gambaro modified Jun 27, 2017  394  1  3  1

    Date formatting using ThreadLocal variable

    How to avoid synchronization for a not thread safe classes
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Foo
    {
        // SimpleDateFormat is not thread-safe, so give one to each thread
        private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected SimpleDateFormat initialValue()
            {
                return new SimpleDateFormat("yyyyMMdd HHmm");
            }
        };
    
        public String formatIt(Date date)
        {
            return formatter.get().format(date);
        }
    }

    public by IanUnderhill modified May 16, 2017  171  15  2  0

    lazy singleton

    public final class Singleton {
        private static volatile Singleton INSTANCE = null;
    
        private Singleton() {// singleton instance}
    
        /**
         * @return the single instance of the class
         */
        public static Singleton getInstance() {
            if (INSTANCE == null) {
                synchronized(Singleton.class) {
                    if (INSTANCE == null) {
                        INSTANCE = new Singleton();
                    }
                }
            }
            return INSTANCE;
        }
    }                                    

    public by AlexZezekalo modified May 8, 2017  580  0  4  0

    Potential NPE

    //@Override
    //public boolean isSatisfiedBy(T candidate) {
    //return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
    //потенциальный NPE   
    
    //Nonnull as solvation?
    
    
    public class AndSpecification<T> extends CompositeSpecification<T> {
    
        @Nonnull
        private final Specification<T> left;
    
        @Nonnull
        private final Specification<T> right;
    
        public AndSpecification(@Nonnull Specification<T> left, @Nonnull Specification<T> right) {
            this.left = left;
            this.right = right;
        }
    
        @Override
        public boolean isSatisfiedBy(T candidate) {
            return left.isSatisfiedBy(candidate) && right.isSatisfiedBy(candidate);
        }
    
    }
    

    public by hamidmousavi modified Feb 18, 2017  1522  0  5  0

    This method will return WebElement After Given wait

    // This method will return WebElement After Given wait           
    public static WebElement FindWithWait(WebDriver driver,By locator, int seconds) throws Exception{
    		// Sleep until the Element we want is visible or n seconds is over
    		WebElement element=null;
    		
    		//Because if implict wait is set then fluint wait will not work
    		driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    		try{
    					FluentWait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
    							.withTimeout(seconds, TimeUnit.SECONDS)
    							.pollingEvery(200, TimeUnit.MILLISECONDS)
    							.ignoring(NoSuchElementException.class)
    							.ignoring(StaleElementReferenceException.class)
    							.ignoring(WebDriverException.class);
    									 
    				element=fluentWait.until(
    							
    							ExpectedConditions.visibilityOfElementLocated(locator)
    							
    							);
    				return element;
    					
    		} catch(Exception e){
    			
    			throw new Exception("Timeout reached when searching for element! Time: " + seconds+" seconds " +"\n" +e.getMessage());
    			
    		}
    		finally {
    			driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    		}
    		
    	}

    public by GennadyBal modified Jan 31, 2017  1622  0  3  1

    Using Scanner to Read System Inputs - Java Stdin and Stdout

    Using Scanner to Read System Inputs - Java Stdin and Stdout
    import java.util.*;
    
    Scanner scanner = new Scanner(System.in);
    String myString = scanner.next();
    int myInt = scanner.nextInt();
    scanner.close();
    
    System.out.println("myString is: " + myString);
    System.out.println("myInt is: " + myInt);

    public by cghersi modified Jan 10, 2017  1994  9  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by cghersi modified Jan 10, 2017  2192  2  5  1

    Read file in Java

    Efficient way to read file in Java using Files class
      import java.nio.file.Files; 
      import java.nio.file.Paths;
    
      public static String readFile(String path) throws Exception {
    		if (isNullOrEmpty(path)) {
    			return "";
    		}
    		return new String(Files.readAllBytes(Paths.get(path)));
    	}      

    public by cghersi modified Jan 10, 2017  289477  1  8  0

    How to read a file into a string in Java

    This simple snippet reads a file and put the content into a returned string
    private static String readFileAsString(String filePath) throws java.io.IOException{
    
    	StringBuffer fileData = new StringBuffer(1000);
    	BufferedReader reader = new BufferedReader(new FileReader(filePath));
    	char[] buf = new char[1024];
    	int numRead=0;
    	while((numRead=reader.read(buf)) != -1){
    		String readData = String.valueOf(buf, 0, numRead);
    		fileData.append(readData);
    		buf = new char[1024];
    	}
    
    	reader.close();
    	return fileData.toString();
    }            

    public by cghersi modified Dec 16, 2016  1934  5  6  0

    How to post an HTTP Request

    just consume a RESTful API via POST request
    public String sendPostReq(String url, String data, boolean addAccessToken) {
    		// Create a new client:
    		DefaultHttpClient httpClient = createHttpClient(url.startsWith("https"));
    		HttpPost httppost = new HttpPost(url);
    		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    		httppost.setHeader("Charset", "UTF-8");
    		httppost.setHeader("Accept", m_requestFormat.getMimeType());
    		httppost.setHeader(S2C_HEADER, S2C_HEADER_VALUE);
    
    		//access the secured service with the authorization cookie
    		if (addAccessToken && !Utils.isNullOrEmpty(m_accessToken)) {
    			addAccessTokenToCookies();
    		}
    		httpClient.setCookieStore(m_cookies);
    		try {
    			httppost.setEntity(new StringEntity(data, "UTF-8"));
    		} catch (UnsupportedEncodingException e1) {
    			log.error("Cannot encode data: " + data + " due to " + e1);
    			return "";
    		}
    
    		HttpResponse response = null;
    		String res = "";
    		try {
    			response = httpClient.execute(httppost);
    			res = readStreamData(response.getEntity().getContent());
    			log.info("Response:" + res);
    		} catch (org.apache.http.conn.HttpHostConnectException e) {
    			log.error("Cannot receive response due to " + e);
    			if (url.contains(LOGIN_URL))
    				res = TIMEOUT_RESP;
    		} catch (IOException e) {
    			log.error("Cannot parse incoming response due to " + e);
    		} finally {
    			httpClient.getConnectionManager().shutdown();
    		}
    		
    		m_cookies = httpClient.getCookieStore(); //save cookies for the next secured run		
    		return res;
    	}

    public by hburaksavas modified Nov 23, 2016  8321  1  4  0

    Creating String Objects With Java

    Creating String Objects With Java: Java:CreatingString.java
    public class CreatingString{
      
      public static void main(String[] args){
        
        String ad;
        ad= "Burak";
        
        String soyad = "Savaş";
        
        String adres = new String("İstanbul - Ataşehir");
        
        System.out.println("Yazar bilgileri");
        System.out.println(ad);
        System.out.println(soyad);
        System.out.println(adres);
        
      }
    }
    
    
    • Public Snippets
    • Channels Snippets