working on it ...

Filters

Explore Public Snippets

Sort by

Found 38k snippets

    public by hamidmousavi modified Feb 18, 2017  68  0  4  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  65  0  2  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  118  2  4  1

    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  110  2  4  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  618  3  7  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  122  4  5  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  761  2  3  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 by hburaksavas modified Nov 19, 2016  631  1  2  0

    Codes For Java Blog

    Codes For Java Blog: Java: Hello World
    public class Ilk_Programim { 
            
           //main metodumuz
           public static void main(String[] args)
           {
           
               //Yazı yazdırma metodumuz    
               System.out.println("Hello World");
               System.out.println("Hello Java");
               System.out.println("I love Gist");
               
           }
    }
    
    

    public by cghersi modified Oct 5, 2016  709  1  4  0

    Preprovision a device via API with PLAT.ONE

    This is a way to use the PLAT.ONE API to create a device with a full structure: once the device is then active, it will be automatically integrated into the PLAT.ONE environment.
    // define the addressing information of the device:
    int netId = 1;			
    String deviceAddress = "100100";
    WSNNodeType nodeType = WSNNodeType.ENDPOINT;
    	
    // add sensor breakdown:
    List<LogNodeConfig> logNodeConfigs = new ArrayList<LogNodeConfig>();
    List<ObjectId> objsTemp = new ArrayList<ObjectId>();
    ObjectId objectIdTemp = frameParser.getObjID(0, 10);	// ObjectIdLow==0, ObjectIdHigh==10 = Temperature
    objsTemp.add(objectIdTemp);
    LogNodeConfig myNodeConf1 = frameParser.getLogNodeCfg(0, objsTemp, true);
    Tsap tsapTemp = frameParser.getTsap("AA:11:22:33:4E");
    myNodeConf1.setTsap(tsapTemp);
    logNodeConfigs.add(myNodeConf1);
    	
    // invoke the API
    ACSIresponseTicket<NodeIdentifier> ticket = null;
    try {
    	ticket = apiManager.ACSI_addNode(netId, nodeAddress, logNodeConfigs, nodeType, null);
    } catch (Exception e1) {
    	log.error("Could not create node ID= " + nodeAddress + ". "+ e1.getMessage());
    	return null;
    }
    
    log.trace("Ticket: " +  ticket.getRequestReturnCode());
    if (ticket.getRequestReturnCode() != ACSIreturnCodes.SUCCESS)
    	return null;
    
    nodeID = ticket.getResponse();
    if (nodeID!=null) {
    	log.info("Creating node: " + nodeID);
    } else {
    	log.error("CreateNode returned null NodeIdentifier");
    	return null;
    }          
    

    public by IanUnderhill modified Sep 20, 2016  662  0  3  0

    Powermock - mocking static methods

    shows how to mock a static method, using powermock
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.is;
    
    import java.io.IOException;
    import java.nio.channels.SocketChannel;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    
    /**
     * I test that mocking static methods works correctly
     *
     * @author Ian Underhill
     * @created 20 Sep 2016
     */
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ SocketChannel.class })
    public class StaticMethodsUnitTest {
    
        private boolean worked = false;
    
        @Test
        public void shouldBeAbleToMockStaticMethods() throws IOException {
            givenASocket();
            whenOpened();
            thenItWorked();
        }
    
        @SuppressWarnings("boxing")
        private void thenItWorked() {
            assertThat(this.worked, is(true));
        }
    
        private void whenOpened() throws IOException {
            SocketChannel.open();
        }
    
        private void givenASocket() {
            PowerMockito.mockStatic(SocketChannel.class, invocation -> {
                this.worked = true;
                return null;
            });
        }
    }
                            
    • Public Snippets
    • Channels Snippets