working on it ...

Filters

Explore Public Snippets

Sort by

Found 36k snippets

    public by cghersi modified Jan 10, 2017  52  1  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  40  1  3  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  541  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  61  3  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  713  1  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  583  0  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  620  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  617  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 by DinhoPutz modified Aug 23, 2016  862  1  4  0

    Calculadora Básica em Java (4 operações)

    // Enter here the actual content of the snippet.            package calculadora;
    public class Calculadora {
    	
        public static void main(String[] args) {
    		
    		double valor1 = 0;
            double valor2 = 0;
    		char operador = ' ';
    		double resultado = 0;
    		
    		System.out.println("Hello World");
    		
    		
    		System.out.println("Digite o primeiro digito");
    		
    		valor1 = new java.util.Scanner(System.in).nextDouble();
    		
    		System.out.println("Valor 1: " + valor1);
    		
    		while(true){
    			System.out.println("Digite o operador (+, -, /, *) ");
    			operador = new java.util.Scanner(System.in).next().charAt(0);
    			if (operador == '+' || operador == '-' || operador == '/' || operador == '*'){
    				break; // Sai da extrutura de repetição
    			}
    			else{
    				System.out.println("Operador inválido. Tente novamente");
    			}
    		}
    		
    		System.out.println("Digite o segundo digito");
    		
    		valor2 = new java.util.Scanner(System.in).nextDouble();
    		
    		switch(operador){
    			case '+':
    			resultado = valor1 + valor2;
    			break;
    			
    			case '-':
    			resultado = valor1 - valor2;
    			break;
    			
    			case '*':
    			resultado = valor1 * valor2;
    			break;
    			
    			case '/':
    			resultado = valor1 / valor2;
    			break;
    		}
    		
    		System.out.println("Resultado: " + resultado);
    		
    		
    	}
    } 
    
    

    public by chileaus modified Aug 11, 2016  647  0  3  0

    Background work

    SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>()
            {
                @Override
                protected Boolean doInBackground() throws Exception
                {
                    lblProgressStatus.setText("start message goes here ");
                    [method goes here];
                    return true;
                }
    
                @Override
                protected void done()
                {
                    boolean status;
                    try
                    {
                        status = get();
                        lblProgressStatus.setText("finish message goes here");
                        [is up to you if you want to put a method ];
                        lblProgressStatus.setText("");
                    }
                    catch ( InterruptedException | ExecutionException e )
                    {
                    }
                }
    
            };
            worker.execute();            
    • Public Snippets
    • Channels Snippets