Tuesday, December 6, 2011

Creating a new user in Oracle 11g

Here's how you create a new user in Oracle 11g to get you started in a project:

1. Login as SYSTEM with the password you set during Oracle's installation.
2. Execute the following script:

CREATE USER myNewUser IDENTIFIED BY myPassword
       DEFAULT TABLESPACE users
       TEMPORARY TABLESPACE temp
       QUOTA UNLIMITED ON users;

CREATE ROLE conn;

GRANT CREATE session, CREATE table, CREATE view,
       CREATE procedure, CREATE synonym,
       ALTER any table, ALTER any materialized view, ALTER any procedure,
       DROP ANY table, DROP any view, DROP any procedure, DROP ANY synonym, CREATE sequence, DROP ANY sequence
       TO conn;

GRANT conn TO myNewUser;

Friday, November 5, 2010

Javascript Singleton Object

Have you come across a problem where you have to create an object that can only be initialized once and you want to reuse that object throughout your whole application? Well maybe you haven't but I actually came across that problem the other day and here's the solution for it:

function singleton() {
var instance = (function() {
var privateVar;

function privateMethod () {
// ...
}

return { // public interface
publicMethod1
: function () {
// private members can be accessed here
},
publicMethod2
: function () {
// ...
}
};
})();

singleton
= function () { // re-define the function for subsequent calls
return instance;
};

return singleton(); // call the new function
}
Solution given by CMS on Stack overflow(http://stackoverflow.com/questions/1895635/javascript-singleton-question)

Tuesday, May 18, 2010

Get number of weeks within fiscal year

The other day I found myself looking for a solution to find the week number we are in within a given fiscal year. Here's the solution I came up with with a snippet from my code:

Date.prototype.getWeek = function (dowOffset)
{
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */
dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
var newYear = new Date(this.getFullYear(),0,1);
var day = newYear.getDay() - dowOffset; //the day of week the year begins on
day = (day >= 0 ? day : day + 7);
var daynum = Math.floor((this.getTime() - newYear.getTime() - (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
var weeknum;
//if the year starts before the middle of a week
if(day < 4)
{
weeknum = Math.floor((daynum+day-1)/7) + 1;
if(weeknum > 52)
{
nYear = new Date(this.getFullYear() + 1,0,1);
nday = nYear.getDay() - dowOffset;
nday = nday >= 0 ? nday : nday + 7;
/*if the next year starts before the middle of
the week, it is week #1 of that year*/
weeknum = nday < 4 ? 1 : 53;
}
}
else
{
weeknum = Math.floor((daynum+day-1)/7);
}
return weeknum;
}
var todaysDate = new Date();
var currentFiscalYear = todaysDate.getFullYear() - 1;
var numberWeeks;
if(todaysDate.getMonth() > 8 && todaysDate.getMonth() < 11)
{
currentFiscalYear = todaysDate.getFullYear();
}
var beginFiscalDate = new Date();
beginFiscalDate.setFullYear(currentFiscalYear,8,1);
var endFiscalDate = new Date();
endFiscalDate.setFullYear(currentFiscalYear+1,7,31);
var currYearBegFiscalYear = new Date();
currYearBegFiscalYear.setFullYear(todaysDate.getFullYear(), 8,1);
if(todaysDate.getFullYear() > beginFiscalDate.getFullYear()) //Check to see if today comes after september of the current year
{
var decFiscalYear = new Date();
decFiscalYear.setFullYear(currentFiscalYear,11,31);
numberWeeks = todaysDate.getWeek() + (decFiscalYear.getWeek() - beginFiscalDate.getWeek());
}
else
{
numberWeeks = todaysDate.getWeek() - beginFiscalDate.getWeek();
}

Tuesday, March 2, 2010

Mimic mySQL's LIMIT command in Oracle

I have struggled in the past and have heard of people struggling with writing a SQL statement in Oracle that would mimic mySQL's command LIMIT.

LIMIT doesn't exist in Oracle and there are two ways of displaying the range of records you want from a table. The first one is to use PLSQL. I'm not going to get into details here but all you have to do is do a SELECT statement INTO a CURSOR datatype, iterate your cursor and exit when your loop counter hits the number of rows you want.

As you can see this solution is not very effective and the best way of doing this is by creating a simple statement using the rownum column.

For instance, if you wanted to select the 10 first items from the item table you would do the following:

SELECT * FROM item WHERE rownnum < 11;

This should return the first 10 rows.

Tuesday, December 29, 2009

Enum as a class property in Objective-C

For this post I'd like to show how you can define an enum property in Objective-C.
In a nutshell an enum is a datatype you create where in theory only certain values can be assigned to it and none else.

The code is pretty straight forward. Here it goes:

typedef enum
{
North, South, East, West
} Direction;

@interface MyClassName : NSObject
{
Direction direction;
}

@property(nonatomic) Direction direction;

In the above example only the values North, South, East, and West can be assigned to the direction property of a MyClassName instance.

Tuesday, December 8, 2009

Querying an Oracle database using XSLT for dummies

In this post I will explain how you can query an Oracle database using XSLT technology and Xalan as your XML processor.

Requirements:
If you decide that you don't want to use an XML editor you will have to download Xalan and add the necessary libraries to your classpath before processing the XSLT file. If you decide to take that route you can follow the first steps in this tutorial, which explains how to setup your environment without an XML editor.

Tutorial

1. Open Oxygen and create a new document of type XSLT
2. Copy and paste the XSLT code below:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:sql="org.apache.xalan.lib.sql.XConnection"
 extension-element-prefixes="sql">
 <xsl:output method="html" />
 <xsl:template match="/">
  <xsl:variable
   name="movies"
   select="sql:new('oracle.jdbc.driver.OracleDriver'
   ,'jdbc:oracle:thin:@ipaddress:sid','username','password')" />
  <xsl:variable name="streaming" select="sql:disableStreamingMode($movies)" />
  <xsl:variable
   name="queryResults"
   select="sql:query($movies,'SELECT movie, actor FROM movie')" />
  <html>
   <head><title>Oracle Result Set</title></head>
   <body style="font-family: sans-serif;">
    <table border="1" cellpadding="5">
     <tr>
      <xsl:for-each select="$queryResults/sql/metadata/column-header">
       <th><xsl:value-of select="@column-label" /></th>
      </xsl:for-each>
     </tr>
     <xsl:apply-templates select="$queryResults/sql/row-set/row" />
    </table>
   </body>
  </html>
  <xsl:value-of select="sql:close($movies)" />
 </xsl:template>
 <xsl:template match="row">
  <tr><xsl:apply-templates select="col" /></tr>
 </xsl:template>
 <xsl:template match="col">
  <td><xsl:value-of select="text()" /></td>
 </xsl:template>
</xsl:stylesheet>
3. Be sure to make your changes accordingly
4. After pasting your code in the text area click on the XSLT debugger button as shown in the image below:







5.
Click on the Run button



6. Voilà! Now look at the result, and here is what I got from my XSLT:













MOVIEACTOR
Indiana Jones and the Last CrusadeAlison Doody
Indiana Jones and Raiders of the Lost ArkHarrison Ford
Indiana Jones and Raiders of the Lost ArkDenholm Elliott
Indiana Jones and the Last CrusadeSean Connery
Indiana Jones and Raiders of the Lost ArkJonn Rhys-Davies

Friday, February 27, 2009

Turning off the PC Speaker on Ubuntu

Here is how you turn off the PC Speaker on Ubuntu. This command migh even work with other Linux distros.

modprobe -r pcspkr

Friday, February 6, 2009

Deleting files/folders with the same name characteristics in Linux

I was trying to delete the .svn folders from a project in my linux machine and I had two options of doing that. Going folder by folder and find those .svn folders, which were about 20 or delete them all with one line of command connected by a pipe "|".

Here goes the trick and the explanation will follow it.

find /path/projectFolder -type d -name '.svn' | xargs rm -rf

Notice that we start this batch of commands with the find command. The find command takes 3 arguments. The find command will go through all directories and subdirectories starting from the path specified.

The first argument is the path to the folder where you want to perform the lookup of the file/folder. That's pretty straight forward

The second argument is the option "-type" where you define whether you are looking up a file or a directory. In the example given above I defined the type as being a directory. If I wanted to do a lookup for a file I would have an "f" there rather than a "d".

The third argument is the option "-name" where you define the name of the file or folder you want to look for enclosed by single quotes. You can also use wildcards in the name.

The second command I want to talk about is the rm -rf. This command removes all folders that are empty or has something in it.

Now here comes the trick. Every line that the find command returns is passed in to rm -rf through | xargs.
Now, having that in mind if you read from right to left this line commands should make more sense to you.

Google the commands find and xargs to see some cool stuff that you can do with them.

Hope this helps!

Friday, December 5, 2008

Configure JBoss for Oracle

  1. Oracle and JBoss use the same port by default, 8080. If you are using Oracle and JBoss on the same server, modify the http port for Oracle to something other than 8080 (i.e, 8081). Skip this step if you are running Oracle on a different server.
  2. Login to Oracle using SQLPLUS as the SYSTEM user and enter the following script command:


    BEGIN
    dbms_xdb.sethttpport(’8081′);
    END;
    /

    Locate the online_help file in the Oracle \server folder, right click, select properties, and modify the url to:

    http://127.0.0.1:8081/apex/wwv_flow_help.show_help?p_flow_id=4500&p_step_id=1000

    Locate the postDBCreation file in the Oracle server\config\log folder, open it and modify the following line:

    URL=http://127.0.0.1:8081/htmldb/wwv_flow_help.show_help

  3. JBoss needs to know where the Oracle jdbc driver classes are located. This can be done by either, copying the Oracle jdbc archive file to the server default lib folder. Search and locate the ojdbc14.jar file in the Oracle \jdbc\lib folder. Copy the ojdbc14.ja file to the JBoss \server\default\lib folder.
  4. Define a datasource in JBOSS to access a specific Oracle database instance. Copy the /docs/examples/jca/oracle-ds.xml file from the jboss directory to the /server/default/deploy folder in JBoss. Open a text editor (e.g., WordPad or xCode) and modify the file as follows.






  5. OracleDS
    jdbc:oracle:thin:@localhost:1521:xe
    oracle.jdbc.driver.OracleDriver
    homedirectbank
    bank

    Oracle9i



  6. Modify the standardjbosscmp-jdbc.xml configuration file in the JBoss /server/default/conf folder. Add the following and sub-tags to the tag. These tags map the datasource, OracleDS, to the data mapping, Oracle9i, defined further down in this file. The data mapping tag defines how the specific Oracle database types map to the corresponding Java data types.







  7. java:/OracleDS




Configure JBoss for Oracle

  1. Oracle and JBoss use the same port by default, 8080. If you are using Oracle and JBoss on the same server, modify the http port for Oracle to something other than 8080 (i.e, 8081). Skip this step if you are running Oracle on a different server.
  2. Login to Oracle using SQLPLUS as the SYSTEM user and enter the following script command:


    BEGIN
    dbms_xdb.sethttpport(’8081′);
    END;
    /

    Locate the online_help file in the Oracle \server folder, right click, select properties, and modify the url to:

    http://127.0.0.1:8081/apex/wwv_flow_help.show_help?p_flow_id=4500&p_step_id=1000

    Locate the postDBCreation file in the Oracle server\config\log folder, open it and modify the following line:

    URL=http://127.0.0.1:8081/htmldb/wwv_flow_help.show_help

  3. JBoss needs to know where the Oracle jdbc driver classes are located. This can be done by either, copying the Oracle jdbc archive file to the server default lib folder. Search and locate the ojdbc14.jar file in the Oracle \jdbc\lib folder. Copy the ojdbc14.ja file to the JBoss \server\default\lib folder.
  4. Define a datasource in JBOSS to access a specific Oracle database instance. Copy the /docs/examples/jca/oracle-ds.xml file from the jboss directory to the /server/default/deploy folder in JBoss. Open a text editor (e.g., WordPad or xCode) and modify the file as follows.






  5. OracleDS
    jdbc:oracle:thin:@localhost:1521:xe
    oracle.jdbc.driver.OracleDriver
    homedirectbank
    bank

    Oracle9i



  6. Modify the standardjbosscmp-jdbc.xml configuration file in the JBoss /server/default/conf folder. Add the following and sub-tags to the tag. These tags map the datasource, OracleDS, to the data mapping, Oracle9i, defined further down in this file. The data mapping tag defines how the specific Oracle database types map to the corresponding Java data types.







  7. java:/OracleDS




Tuesday, November 18, 2008

Trouble opening java applications in Leopard

I was having trouble executing applications that were developed in java the other day. Here goes a snippet of the error I was getting:

com.apple.launchd[191] ([0x0-0x1fdefdd].????[36322]) posix_spawnp("/Applications/.../Contents/MacOS/JavaApplicationStub", ...): Permission denied

You can easily fix the problem by giving Read, Write and Execute permissions to the user to the JavaApplicationStub executable file.
You do so by running the following command: chmod 777 /[your application path].app/Contents/MacOS/JavaApplicationStub .

Hope that helps.

Thursday, November 6, 2008

Installing code repository subversion (SVN) on Linux Ubuntu

To install subversion, open a terminal and run the following command:

sudo apt-get install subversion libapache2-svn

We're going to create the subversion repository in /svn, although you should choose a location that has a good amount of space.

sudo svnadmin create /home/svn

Next we'll need to edit the configuration file for the subversion webdav module. You can use a different editor if you'd like.

sudo vim /etc/apache2/mods-enabled/dav_svn.conf

The Location element in the configuration file dictates the root directory where subversion will be accessible from, for instance: http://www.server.com/svn

(Don't forget to uncomment the Location closing tag at the end of the document)

The DAV line needs to be uncommented to enable the dav module

#Uncomment this to enable the repository
DAV svn

The SVNPath line should be set to the same place your created the repository with the svnadmin command.

#Set this to the path to your repository
SVNPath /home/svn

The next section will let you turn on authentication. This is just basic authentication, so don't consider it extremely secure. The password file will be located where the AuthUserFile setting sets it to

#Uncomment the following 3 lines to enable Basic Authentication
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile /etc/apache2/dav_svn.passwd

To create a user on the repository use, the following command:

sudo htpasswd -cm /etc/apache2/dav_svn.passwd

Note that you should only use the -c option the FIRST time that you create a user. After that you will only want to use the -m option, which specifies MD5 encryption of the password, but doesn't recreate the file.

Restart apache by running the following command:

sudo /etc/init.d/apache2 restart

Now if you go in your browser to http://www.server.com/svn, you should see that the repository is enabled for anonymous read access, but commit access will require a username.

If you want to force all users to authenticate even for read access, add the following line right below the AuthUserFile line from above. Restart apache after changing this line.

Require valid-user

Now if you refresh your browser, you'll be prompted for your credentials.

Credit goes to Jason Meridith (http://www.lostechies.com/blogs/jason_meridth/)

How to update Ubuntu Server from command line

  1. First you need to update /etc/apt/sources.list. Just open it up with your favorite editor
    sudo vi /etc/apt/sources.list
  2. Since I was using 5.10, at the end of all the URL’s it should say ‘breezy’. You need to change all of these to ‘edgy’. Write the file out and quit.
  3. Next, we need to update the source list by using the following command
    sudo apt-get update
  4. To upgrade to the new distro, just enter dist-upgrade!
    sudo apt-get dist-upgrade
  5. It will ask you if you want to update all of these packages, just say yes. Also, I had a few times that I had to hit ‘OK’ to confirm some postfix stuff. Since im not running any mail services, I dont need to set this up. Just keep an eye on the update since these messages delay the update.
  6. You may have to force some installs/updates. If so (I had to do this), just enter
    sudo apt-get -f install
  7. Once the upgrade is complete (it took mine forever since I was also downloading a trial game AND cygwin), restart your machine
    sudo shutdown -r now
  8. Done!
Credits go to Jon (http://crazytrain.wordpress.com/)

Wednesday, September 3, 2008

How to determine which applications are listening on which ports

If you want to find out which ports your applications are listening upon you cand easily do so by using two different commands. The following assumes you are in a Windows environment. If you find out the commands for other platforms I would appreciate if you included them as a comment.

netstat -ano ---------> This will give you the list of all ports that are being used by all your processes and will also give you the PID for that process along with some other information
tasklist /SVC ---------> This will give you a list with the names of the processes your computer is running along with their corresponding PID

The command for linux is:
sudo lsof -i [TCP]:[8080]
(don't forget to leave the brakets out and put your own parameters)
As you can see this will give you a list of all processes that are listening on port 8080 through the TCP protocol.

Thursday, August 28, 2008

Setting up MS SQL Server for remote authentication

The same problems you are having right now I also had, while setting up my SQL Server for remote access.
Here are some links that I found to be pretty helpful:

http://www.datamasker.com/SSE2005_NetworkCfg.htm
http://www.carlj.ca/2008/01/09/the-user-is-not-associated-with-a-trusted-sql-server-connection/
http://www.alpesh.nakars.com/blog/howto-configure-sql-express-to-allow-remote-connections/

Tuesday, July 29, 2008

Sending a java object over HTTP protocol

As you may know HTTP communication is based on strings that are sent back and forth, and if you want to send an object across the wire over HTTP just object serialization isn't enough. You will have to convert your object into an XML string, and stream it in a ByteArrayOutputStream.
Here goes a snippet of my client code:

MethodInvokerBean miBean = new MethodInvokerBean(); //Instantiate your java bean

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

XMLEncoder encoder = new XMLEncoder(buffer); //Assign ByteArrayOutputStream object to your XMLEncoder object

encoder.writeObject(miBean); //Write object on XMLEncoder object
encoder.close(); //close stream

String url = "http://192.168.1.25/BeanDecoder"; //Servlet's URL

//The classes and methods used in the block below to establish connection with the servlet and pass my object as a parameter come from the HTTP apache client library called commons-httpclient

PostMethod post = new PostMethod(url);
NameValuePair[] nvp = new NameValuePair[1];
nvp[0] = new NameValuePair("bean",buffer.toString());
post.setRequestBody(nvp);
HttpClient httpClient = new HttpClient();

try
{
int result = httpClient.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
System.out.println("HTTP Status: " + result);
}
...


Let's see the servlet's code now:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
String beanXML= req.getParameter("bean");
ByteArrayInputStream bais = new ByteArrayInputStream(beanXML.getBytes());
XMLDecoder decoder = new XMLDecoder(bais);
MethodInvokerBean miBean = null;
miBean = (MethodInvokerBean)decoder.readObject();
}

Thursday, June 19, 2008

Creating an object out of a string

Something that I had to do in one of my projects was send a HTTP request from javascript to a Servlet and get some information back. But, what's better to hold data than an Object?
So I decided to make the servlet send an object back as a response to that javascript request. Here is what I did.

Javascript sends AJAX request
Servlet receives request
Servlet sends an object as a string (eg: {property1: "hello", property2: "World", property3: "!"})
Javascript reads the response and interprets it as a string

In order to turn that encapsulated object in a string to a real javascript object you'll need to use the eval() function and append parenthesis to both sides of the string.

//Since this entry is not to teach you how to do AJAX requests I'm just going to assign a string to a variable and call it "ajaxRequest"
var ajaxResponse = "{property1: "hello", property2: "World", property3: "!"}";

//Notice the parethesis before and after the string that has the object
var myObject = eval( "("+ajaxResponse+")");

alert(myObject.property1 + " " + myObject.property2 + " " + myObject.property3);

Pretty cool uh?

Tuesday, May 27, 2008

SQL date manipulating in Oracle

Today I wrote a script that would take the values I had from my Calendar table, which contained all months with their start date and end date for the year of 2008, and insert them back for the year of 2007. My first solution didn't work so well and threw an error. I came to learn that the TO_YMINTERVAL function doesn't work because it doesn't handle leap year.
The function that did the job right was ADD_MONTH.
Here goes my script:

INSERT INTO calendar
(calendar_id,
month,
full_month,
begin_date,
end_date)
SELECT calendar_s1.nextval,
month,
full_month,
add_months(begin_date,-12),
add_months(end_date,-12)
FROM calendar;

Try that out and let me know if you have other simpler solutions for a similar problem.

Wednesday, May 14, 2008

Introduction

Dear readers,
The purpose of this blog is to provide information, definitions, and ways of doing stuff with technology, mostly with programming, database, setting up different types of server - such as normal proxy servers, transparent proxy servers, web servers, etc...
The main purpose of this blog is really to keep my notes online so I can reference to them later on, if I go through the same problem.
I also want to go over some basic programming and database concepts to help beginners dive in programming without fear.
Let me know if you have any questions.

A brief introduction about me.
My name is Mathew Pretel. I work at Corda Technologies currently as a developer while going to school at BYU-Idaho. My major is Computer Information Technology with emphasis in development.
I'm married and we have a 6 months old little girl.