Thursday, 13 April 2017

Java basics - Sting format

String Formatting

Most common way of formatting a string in java is using String.format(). If there were a “java sprintf” then this would be it.
String output = String.format("%s = %d", "joe", 35);

For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.
System.out.printf("My name is: %s%n", "joe");

Create a Formatter and link it to a StringBuilder. Output formatted using the format() method will be appended to the StringBuilder.
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("PI = %f%n", Math.PI);
System.out.print(sbuf.toString());
// you can continue to append data to sbuf here.






===========================================================


===========================================================



===========================================================

Tuesday, 11 April 2017

Printing all the parameters of http request



Enumeration params = request.getParameterNames();

while(params.hasMoreElements()){

String paramName = (String)params.nextElement();

System.out.println("Parameter Name -> "+paramName+", Value "+request.getParameter(paramName));

}

========================================================


package com.bethecoder.tutorials.commons_httpclient;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest3 {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");

    try {
      FileBody bin = new FileBody(new File("C:/ABC.txt"));
      StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("fileup0", bin);
      reqEntity.addPart("fileup1", comment);
      
      reqEntity.addPart("ONE", new StringBody("11111111"));
      reqEntity.addPart("TWO", new StringBody("222222222"));
      httppost.setEntity(reqEntity);

      System.out.println("Requesting : " + httppost.getRequestLine());
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}

==================================================================================



Sunday, 9 April 2017

Download Audio from reading stream & saving as mp3 file - Java


import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
public class Download{

    public static void main (String[] args){
        try{
            URLConnection conn = new URL("http://dl.jatt.link/hd.jatt.link/5239387a7e84528f196bbffde0b11054/kcizv/Aaja%20Na%20Ferrari%20Mein-(Mr-Jatt.com).mp3").openConnection();
            InputStream is = conn.getInputStream();

            OutputStream outstream = new FileOutputStream(new File("C:/Users/srini/Music/output.mp3"));
            byte[] buffer = new byte[4096];
            int len;
         
            while ((len = is.read(buffer)) > 0)  {
                outstream.write(buffer, 0, len);
            }
            outstream.close();
        }
        catch(Exception e){
            System.out.print(e);
        }
    }
}

================================================================


package sree;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

public class Download1 {

public static void main (String[] args){
        try{
        String  myUrl= "http://dl.smp3dl.com/files/data/4874/01%20Maana%20Ke%20Hum%20Yaar%20Nahi.mp3";

       
        BufferedReader br = new BufferedReader(new InputStreamReader(((HttpURLConnection) (new URL(myUrl)).openConnection()).getInputStream(), Charset.forName("UTF-8")));
       
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("C:/Users/mobigesture/Music/sree.mp3")));
        String l;
        while((l=br.readLine())!=null){
           bw.write(l);
           System.out.println("Downloading..........");
        }

        bw.close();
        System.out.println("Download completed....");
       
        }catch(Exception e){
            System.out.print(e);
        }
        }

}


============================================================

Friday, 7 April 2017

Java basics


=====================printing system properties===================
package com.vht;

import java.util.Enumeration;
import java.util.Properties;

public class Test {


public static void main(String args[])
{
Properties p = System.getProperties();
Enumeration<Object> keys = p.keys();
while (keys.hasMoreElements()) {
   String key = (String)keys.nextElement();
   String value = (String)p.get(key);
   System.out.println(key + " ---> " + value);
}

}


}
=============================================================

public class Test {


public static void main(String args[])
{
String FILE_NAME="toolkit.properties";

String path="C:/Program Files/Java/jdk1.6.0_45/jre/bin/";

path = path + (!path.endsWith("/") ? "*" : "") + FILE_NAME;
{
System.out.println(path);
}


  }
}


=============================================================='

public class Test {


public static void main(String args[])
{
File file = null;


String path="E:/Luv.txt";

file = new File(path);

if(file == null || !file.exists())
{   System.out.println("file not present");
}
else System.out.println("file exist");

  }
}


==========================================================
public class Test {


public static void main(String args[])
{
String fileName="Luv.txt";


String path="E:/abc/Luv.txt";
     path=path.substring(0, path.indexOf("/" + fileName));

     System.out.println(path);
}
}
   //////   Output :   E:/abc

======================================================

public class Test {


public static void main(String args[])
{

String PROPERTY_FILE_NAME = "toolkit.properties";

 String path="/VirtualHold/toolkit.properties";
 
   path=path.substring(0, path.indexOf("/" + PROPERTY_FILE_NAME));
   System.out.println(path);
   path = path + (!path.endsWith("/") ? "/" : "") + PROPERTY_FILE_NAME;
   System.out.println(path);
   
   
}
}
   //////   /VirtualHold
////VirtualHold/toolkit.properties


==============================================================

public class Test {


public static void main(String args[])
{

String PROPERTY_FILE_NAME = "toolkit.properties";

 String path="/VirtualHold/toolkit.properties";
 String PROMPT_RECORDER_FILE_NAME = "promptrecorder.properties";
 
   path=path.substring(0, path.indexOf("/" + PROPERTY_FILE_NAME));
   System.out.println(path);
   path = path + (!path.endsWith("/") ? "/" : "") + PROMPT_RECORDER_FILE_NAME;
   System.out.println(path);
   
   
}
}
/VirtualHold
/VirtualHold/promptrecorder.properties

=====================================================================

INFO|2017/03/20|07:12:29|p=PlatformSupport_AVP|s=E09BFED3012E3C703AE51DE937F29344|e=0001> Action "Begin" Starting
Could not locate: org.apache.http.client.HttpClient while resolving com.openmethods.vht.toolkit.impl.VHTToolkitStub
INFO|2017/03/20|07:12:29|p=PlatformSupport_AVP|s=E09BFED3012E3C703AE51DE937F29344> Creating Toolkit Stub Version 5.0.0
INFO|2017/03/20|07:12:29|p=PlatformSupport_AVP|s=E09BFED3012E3C703AE51DE937F29344> Loading Configuration from: C:\VirtualHold\toolkit.properties
Adding external media server: http://10.10.1.153:8080/voices/
Setting external media server distribution method to failover
Setting external media server logging to first-failure
INFO|2017/03/20|07:12:29|p=PlatformSupport_AVP|s=E09BFED3012E3C703AE51DE937F29344> : C:\VirtualHold\toolkit.properties\promptrecorder.properties
ERROR|2017/03/20|07:12:29|p=PlatformSupport_AVP|s=E09BFED3012E3C703AE51DE937F29344> Could not locate configuration file at /VirtualHold/toolkit.properties
java.io.FileNotFoundException: \VirtualHold\toolkit.properties\promptrecorder.properties (The system cannot find the path specified)
======================================================================





Thursday, 30 March 2017

Writing Directories into File & Reading from File C#




sample.aspx
=====================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>


<%

Context.Response.ContentType = "text/plain";

    DirectoryInfo[] cDirs = new DirectoryInfo(@"D:\").GetDirectories();

    StreamWriter sw = new StreamWriter("D:/CDriveDirs.txt", true);
 
        foreach (DirectoryInfo dir in cDirs)
        {
            sw.WriteLine(dir.Name);
            sw.WriteLine("\n");
            Response.Write(dir.Name);
            Response.Write("\n");
       
       }

        sw.Flush();
        sw.Close();
%>
=====================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>


<%

Context.Response.ContentType = "text/plain";

    DirectoryInfo[] cDirs = new DirectoryInfo(@"D:\").GetDirectories();

   
       StreamReader sr = new StreamReader("D:/CDriveDirs.txt");
 
           String line;
               
           while((line=sr.ReadLine())!=null)
           {
         
               Response.Write(line+"\n");
         
           }  
 
        sr.Close();
%>

=====================================================

Friday, 24 March 2017

c#

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>

<%

Context.Response.ContentType = "text/plain";

String directory = "/usr/local/tomcat7/webapps/voices/";

String action = Request.QueryString["action"];
HttpRequest request;

String upload = "upload";
String save = "save";
String delete = "delete";

if (upload==action){
 
    Response.Write("uploading file");
    directory += "temp/";
   
   
   
   
}
 else if (save==action) {

     Response.Write("saving file");
   
     String fileName = Request.QueryString["filename"];
     String language = Request.QueryString["language"];
     String mediaLibrary = Request.QueryString["mediaLibrary"];
     String path= directory + language + "/" + mediaLibrary + "/";

     File.Create(path + fileName);

     FileStream fs = File.Create(path + fileName);
   
 }

 else if (delete==action) {

     Response.Write("deleting file");

     if (File.Exists("test.txt"))
     {
         File.Delete("test.txt");
         if (File.Exists("test.txt") == false)
             Response.Write("File deleted...");
     }
     else
         Response.Write("File test.txt does not yet exist!");
   
   
   
   
 }

 

%>
   
   

%>

Thursday, 23 March 2017

ASP.NET & C#

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";

     String sree = "mobigesture";
     Response.Write(sree);
     
   
%>
----------------------------------------
http://10.10.1.153/voices/sample.aspx
------------------------------------------

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%

Context.Response.ContentType = "text/plain";

String sree = Request.QueryString["test"];
Response.Write(sree);
%>

--------------------------------------------------
http://10.10.1.153/voices/sample.aspx?test=HelloWorld
----------------------------------------------


=================================================================
var dataFile = Server.MapPath("~/Persons.txt");
Array userData = File.ReadAllLines(dataFile);

  foreach (string dataLine in userData)
  {
  foreach (string dataItem in dataLine.Split(','))
  Response.Write(dataItem);
 
  }
 
  =========================================
 
 
  <%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%

Context.Response.ContentType = "text/plain";

var dataFile = Server.MapPath("~/Persons.txt");
Array userData = File.ReadAllLines(dataFile);

  foreach (string dataLine in userData)
  {
  foreach (string dataItem in dataLine.Split(','))
  Response.Write(dataItem);
 
  }
%>

===================================================


<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";


    var names = new List<string>() { "John", "Tom", "Peter" };
    foreach (string name in names)
    {
        Response.Write(name+" \n");
    }
%>

=========================================================

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";


    string[] filePaths = Directory.GetFiles(@"D:\");

    for (int i = 0; i < filePaths.Length; i++)
    {
        Response.Write(filePaths[i]+"\n");
    }
 
%>

====================================================================
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%
 
    Context.Response.ContentType = "text/plain";

    int caseSwitch = 1;
    switch (caseSwitch)
    {
        case 1:
            Response.Write("Case 1");
            break;
        case 2:
            Response.Write("Case 2");
            break;
        default:
            Response.Write("Default case");
            break;
    }
%>

=====================================================================