Tag Archive for java

Java script to flip & also copy image or word in this instance from stressed to desserts

<STYLE TYPE = "text/css">

   BODY  { background-color: blue }

 

   TABLE { font-size: 3 em:

           font-family: Calibri, sans-serif;

           background-color: yellow;

           border-style: outset ;

           border-collapse: separate }

 

   TD    { border-style: inset;

           padding: 2ex }

</STYLE>

<TABLE>

 

   <TR>

      <TD STYLE = "filter: fliph">StresseD</TD>

      <TD>StresseD</TD>

   </TR>

 

   </TR>

       <TD STYLE = "filter: flipv fliph">StresseD</TD>

       <TD STYLE = "filter: flipv">StresseD</TD>

   </TR>

</TABLE>

source

Java Date Detection

<% java.util.Date today = new java.util.Date(); java.util.Date ad = new java.util.Date("May 25, 2010 12:00 AM");%>
<% if (today.compareTo(ad) > 0){ %>
  Displays after date
<%} else {%>
  Displays before date
<% } %>

source

Finding classes

File moduleFile = new File(Catalog.class.getProtectionDomain().getCodeSource().getLocation().toURI());
final ClassFinder finder = new ClassFinder();
finder.clear();
assertTrue(finder.add(moduleFile));
final ClassFilter filter = new AndClassFilter(new NotClassFilter(new InterfaceOnlyClassFilter()), new NotClassFilter(new AbstractClassFilter()), new SubclassClassFilter(UpdateTask.class));
Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>();
finder.findClasses(foundClasses, filter);

source

Use cookie to save session data

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShoppingCartViewerCookie extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
      IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String sessionid = null;
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("sessionid")) {
          sessionid = cookies[i].getValue();
          break;
        }
      }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
      sessionid = generateSessionId();
      Cookie c = new Cookie("sessionid", sessionid);
      res.addCookie(c);
    }

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
      out.println("<B>None</B>");
    } else {
      out.println("<UL>");
      for (int i = 0; i < items.length; i++) {
        out.println("<LI>" + items[i]);
      }
      out.println("</UL>");
    }

    // Ask if they want to add more items or check out.
    out.println("<FORM ACTION="/servlet/ShoppingCart" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=" Add More Items ">");
    out.println("<INPUT TYPE=SUBMIT VALUE=" Check Out ">");
    out.println("</FORM>");

    // Offer a help page.
    out.println("For help, click <A HREF="/servlet/Help"
        + "?topic=ShoppingCartViewerCookie">here</A>");

    out.println("</BODY></HTML>");
  }

  private static String generateSessionId() throws UnsupportedEncodingException {
    String uid = new java.rmi.server.UID().toString(); // guaranteed unique
    return URLEncoder.encode(uid,"UTF-8"); // encode any special chars
  }

  private static String[] getItemsFromCart(String sessionid) {
    return new String[]{"a","b"};  
  }
}

source

Convert X509 certificate to base64

X509Certificate cert;
BASE64Encoder encoder=new BASE64Encoder();
String psB64Certificate = encoder.encodeBuffer(cert.getEncoded());

source

Axis call over SSL

System.setProperty("javax.net.debug", "ssl");
System.setProperty("javax.net.ssl.trustStore", RUTA_TRUSTSTORE);
System.setProperty("javax.net.ssl.trustStorePassword", PASS_TRUSTSTORE);
System.setProperty("javax.net.ssl.keyStoreType", KEYSTORE_TYPE);
					
org.apache.axis.client.Service service = new Service();
org.apache.axis.client.Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new java.net.URL(ENDPOINT));
call.setOperationName(OPERATION_NAME);
String ret = (String) call.invoke(new Object[] { PARAMETER });

source

Close modal panel in JSF

<rich:modalPanel id="previewPanel" width="550" height="400"
			moveable="true">
  <a4j:commandButton reRender="previewPanel" value="OK" id="okPreview">
  <rich:componentControl for="previewPanel" attachTo="okPreview"
						operation="hide" event="onclick" />
  </a4j:commandButton>
</rich:modalPanel>

source

Anagram Validator

//regular expression
String patternStr = "(?=.*d.*d)(?=.*e)(?=.*b)(?=.*i)(?=.*t)(?=.*s)(?=.*c)(?=.*a)(?=.*r)^..........$";
boolean b;
Matcher matcher;
Pattern pattern;

System.out.println("Regex pattern = "+patternStr);
pattern = Pattern.compile(patternStr);//compiles the regex
		
//validates bad credit
System.out.println("Validating: bad credit");
matcher = pattern.matcher("bad credit");
b = matcher.matches();
if(b) System.out.println("bad credit: matched");
else System.out.println("bad credit: not matched");

//validates debit card
System.out.println("Validating: debit card");
matcher = pattern.matcher("debit card");
b = matcher.matches();
if(b) System.out.println("debit card: matched");
else System.out.println("debit card: not matched");

source

java web page download

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Main.java
 *
 * @author <a href="http://www.javadb.com">www.javadb.com</a>
 */
public class Main {
    
    /**
     * Reads a web page into a StringBuilder object
     * and prints it out to console along with the
     * size of the page.
     */
    public void getWebSite() {
        
        try {
            
            URL url = new URL("<a href="http://www.google.com");" >http://www.google.com");</a>
            URLConnection urlc = url.openConnection();
            
            BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
            
            StringBuilder builder = new StringBuilder();
            int byteRead;
            while ((byteRead = buffer.read()) != -1)
                builder.append((char) byteRead);
            
            buffer.close();
            
            System.out.println(builder.toString());
            System.out.println("The size of the web page is " + builder.length() + " bytes.");
            
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().getWebSite();
    }
}

source

latex source code formatting

	itle{Nice Code}
author{Jonathan Bunde-Pedersen}

documentclass[12pt]{article}

usepackage{color}
usepackage{fancyvrb}
usepackage{listings}

% include the lines below to use a nicer fixed-width font than the default one
usepackage{fontspec}
setmonofont[Scale=0.8]{Consolas} 

lstset{fancyvrb=true}
lstset{
	basicstyle=small	t,
	keywordstyle=color{blue},
	identifierstyle=,
	commentstyle=color{green},
	stringstyle=color{red},
	showstringspaces=false,
	tabsize=3,
	numbers=left,
	captionpos=b,
	numberstyle=	iny
	%stepnumber=4
	}

egin{document}
maketitle

section{Some nice Java code}

egin{figure}[h]
lstset{language=java,caption=Nicely formatted code.,label=lst:nicecode}
egin{lstlisting}
public class Whatever {
	public static void main(String[] args) {
		// whatever
		System.out.println("Hello, world!");
	}	
}
end{lstlisting}
end{figure}


end{document}

source