Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

lunes, 16 de marzo de 2009

Turn off menu transparece SwingX

You can turn off the transparency by changing the skinlf-themepack.xml file or by doing UIManager.put("PopupMenu.animation", Boolean.FALSE);

jueves, 5 de febrero de 2009

Java Books

http://www.itstudy8.org/java.asp
--
Eduardo R. Coll

viernes, 6 de junio de 2008

Running Eclipse

FUENTE: COPIA FIEL DE LA DOCUMENTACION DE ECLIPSE.

After installing the Eclipse SDK in a directory, you can start the Workbench by running the Eclipse executable included with the release (you also need a 1.4.2 JRE, not included with the Eclipse SDK). On Windows, the executable file is called eclipse.exe, and is located in the eclipse sub-directory of the install. If installed at c:\eclipse-SDK-3.3-win32, the executable is c:\eclipse-SDK-3.3-win32\eclipse\eclipse.exe. Note: Set-up on most other operating environments is analogous. Special instructions for Mac OS X are listed below.

Allocating enough memory and solving OutOfMemoryErrors

By default, Eclipse will allocate up to 256 megabytes of Java heap memory. This should be ample for all typical development tasks. However, depending on the JRE that you are running, the number of additional plug-ins you are using, and the number of files you will be working with, you could conceivably have to increase this amount. Eclipse allows you to pass arguments directly to the Java VM using the -vmargs command line argument, which must follow all other Eclipse specific arguments. Thus, to increase the available heap memory, you would typically use:

eclipse -vmargs -Xmx

with the value set to greater than "256M" (256 megabytes -- the default).

When using a Sun VM, you may also need to increase the size of the permanent generation memory. The default maximum is 64 megabytes, but more may be needed depending on your plug-in configuration and use. When the VM runs out of permanent generation memory, it may crash or hang during class loading. This failure is less common when using Sun JRE version 1.5.0_07 or greater. The maximum permanent generation size is increased using the -XX:MaxPermSize= argument:

eclipse -vmargs -XX:MaxPermSize=

This argument may not be available for all VM versions and platforms; consult your VM documentation for more details.

Note that setting memory sizes to be larger than the amount of available physical memory on your machine will cause Java to "thrash" as it copies objects back and forth to virtual memory, which will severely degrade your performance.

Selecting a workspace

When the Workbench is launched, the first thing you see is a dialog that allows you to select where the workspace will be located. The workspace is the directory where your work will be stored. If you do not specify otherwise, Eclipse creates the workspace in your user directory. This workspace directory is used as the default content area for your projects as well as for holding any required metadata. For shared or multi-workspace installs you must explicitly specify the location for your workspace using the dialog (or via the "-data" command line argument).

Here is a typical Eclipse command line:

eclipse -vm c:\jdk1.4.2\jre\bin\javaw

Tip: It's generally a good idea to explicitly specify which Java VM to use when running Eclipse. This is achieved with the "-vm" command line argument as illustrated above. If you don't use "-vm", Eclipse will look on the O/S path. When you install other Java-based products, they may change your path and could result in a different Java VM being used when you next launch Eclipse.

To create a Windows shortcut to an installed Eclipse:

  1. Navigate to eclipse.exe in Windows Explorer and use Create Shortcut on the content menu.
  2. Select the shortcut and edit its Properties. In the Target: field append the command line arguments.

Opening this shortcut launches Eclipse. (You can drag the shortcut to the Windows Desktop if you want to keep it in easy reach.)

Mac OS X

On Mac OS X, you start Eclipse by double clicking the Eclipse application. If you need to pass arguments to Eclipse, you'll have to edit the eclipse.ini file inside the Eclipse application bundle: select the Eclipse application bundle icon while holding down the Control Key. This will present you with a popup menu. Select "Show Package Contents" in the popup menu. Locate eclipse.ini file in the Contents/MacOS sub-folder and open it with your favorite text editor to edit the command line options.

On MacOS X you can only launch a UI program more than once if you have separate copies of the program on disk. The reason for this behavior is that every UI application on Mac can open multiple documents, so typically there is no need to open a program twice. Since Eclipse cannot open more than one workspace, this means you have to make a copy of the Eclipse install if you want to open more then one workspace at the same time (bug 139319).

If you need to launch Eclipse from the command line, you can use the symbolic link "eclipse" in the top-level eclipse folder. It refers to the eclipse executable inside the application bundle and takes the same arguments as "eclipse.exe" on other platforms.

On Mac OS X 10.4 and later, you may notice a slow down when working with significant numbers of resources if you allow Spotlight to index your workspace. To prevent this, start System Preferences, select the Spotlight icon, then the Privacy tab, then click the Add button ("+") and find your workspace directory in the dialog that appears.

Shared Install

The startup speed of a shared install can be improved if proper cache information is stored in the shared install area. To achieve this, after unzipping Eclipse distribution, run Eclipse once with the "-initialize" option from an account that has a write access to the install directory.

Advanced Topics in Running Eclipse

The Eclipse executable and the platform itself offer a number of execution options of interest to people developing or debugging parts of Eclipse. This is a list of the commonly used options, for a full list see the Eclipse runtime options page in the Platform Plug-in Developer Guide. The general form of running the Eclipse executable is:

eclipse [platform options] [-vmargs [Java VM arguments]]
Eclipse Startup Parameters
Command Description Since
-arch architecture
Defines the processor architecture on which the Eclipse platform is running. The Eclipse platform ordinarily computes the optimal setting using the prevailing value of Java os.arch property. If specified here, this is the value that the Eclipse platform uses. The value specified here is available to plug-ins as BootLoader.getOSArch(). Example values: "x86", "sparc", "PA-RISC", "ppc". 2.0
-application applicationId
The application to run. Applications are declared by plug-ins supplying extensions to the org.eclipse.core.runtime.applications extension point. This argument is typically not needed. If specified, the value overrides the value supplied by the configuration. If not specified, the Eclipse Workbench is run. 1.0
-clean
Cleans cached data used by the OSGi framework and Eclipse runtime. Try to run Eclipse once with this option if you observe startup errors after install, update, or using a shared configuration. 3.0
-configuration configurationFileURL
The location for the Eclipse Platform configuration file, expressed as a URL. The configuration file determines the location of the Eclipse platform, the set of available plug-ins, and the primary feature. Note that relative URLs are not allowed. The configuration file is written to this location when the Eclipse platform is installed or updated. 2.0
-consolelog
Mirrors the Eclipse platform's error log to the console used to run Eclipse. Handy when combined with -debug. 1.0
-data workspacePath
The path of the workspace on which to run the Eclipse platform. The workspace location is also the default location for projects. Relative paths are interpreted relative to the directory that Eclipse was started from. 1.0
-debug [optionsFile]
Puts the platform in debug mode and loads the debug options from the file at the given location, if specified. This file indicates which debug points are available for a plug-in and whether or not they are enabled. If a file location is not given, the platform looks in the directory that eclipse was started from for a file called ".options". Both URLs and file system paths are allowed as file locations. 1.0
-dev [classpathEntries]
Puts the platform in development mode. The optional classpath entries (a comma separated list) are added to the runtime classpath of each plug-in. For example, when the workspace contains plug-ins being developed, specifying -dev bin adds a classpath entry for each plug-in project's directory named bin, allowing freshly generated class files to be found there. Redundant or non-existent classpath entries are eliminated. 1.0
-initialize
Initializes the configuration being run. All runtime related data structures and caches are refreshed. Handy with shared installs: running Eclipse once with this option from an account with write privileges will improve startup performance. 3.0
-keyring keyringFilePath
The location of the authorization database (or "key ring" file) on disk. This argument must be used in conjunction with the -password option. Relative paths are interpreted relative to the directory that Eclipse was started from. 1.0
-nl locale
Defines the name of the locale on which the Eclipse platform is running. The Eclipse platform ordinarily computes the optimal setting automatically. If specified here, this is the value that the Eclipse platform uses. The value specified here is available to plug-ins as BootLoader.getNL(). Example values: "en_US" and "fr_FR_EURO". 2.0
-nosplash
Runs the platform without putting up the splash screen. 1.0
-os operatingSystem
Defines the operating system on which the Eclipse platform is running. The Eclipse platform ordinarily computes the optimal setting using the prevailing value of Java os.name property. If specified here, this is the value that the Eclipse platform uses. The value specified here is available to plug-ins as BootLoader.getOS(), and used to resolve occurrences of the $os$ variable in paths mentioned in the plug-in manifest file. Example values: "win32", "linux", "hpux", "solaris", "aix". 1.0
-password password
The password for the authorization database. Used in conjunction with the -keyring option. 1.0
-perspective perspectiveId
The perspective to open in the active workbench window on startup. If this parameter is not specified, the perspective that was active on shutdown will be opened. 1.0
-plugincustomization
propertiesFile
The location of a properties file containing default settings for plug-in preferences. These default settings override default settings specified in the primary feature. Relative paths are interpreted relative to the directory that eclipse was started from. 2.0
-product productId
The ID of the product to run. The product gives the launched instance of Eclipse its personality, and determines the product customization information used. This replaces -feature, which is still supported for compatibility. 3.0
-refresh 
Option for performing a global refresh of the workspace on startup. This will reconcile any changes that were made in the file system since the platform was last run. 1.0
-showlocation [workspaceName]
Option for displaying the location of the workspace in the window title bar. In release 2.0 this option only worked in conjunction with the -data command line argument. In 3.2, an optional workspace name argument was added that displays the provided name in the window title bar instead of the location of the workspace. 2.0
-vm vmPath
The location of Java Runtime Environment (JRE) to use to run the Eclipse platform. If not specified, the launcher will attempt to find a JRE. It will first look for a directory called jre as a sibling of the Eclipse executable, and then look on the operating system path. Relative paths are interpreted relative to the directory that eclipse was started from. 1.0
-vmargs args
When passed to the Eclipse, this option is used to customize the operation of the Java VM used to run Eclipse. If specified, this option must come at the end of the command line. The given arguments are dependant on VM that is being run. 1.0

All arguments following (but not including) the -vmargs entry are passed directly through to the indicated Java VM as virtual machine arguments (that is, before the class to run). Note: If an Eclipse startup argument, such as -data, is provided after the Java vm arguments (-vmargs), Eclipse will not start and you will receive a "JVM terminated. Exit code=1" error.

martes, 20 de mayo de 2008

java.lang.OutOfMemoryError: Java heap space

Fuentes:
http://www.saiyine.com/post.798.php
http://www.consultoriajava.com/publico/JavaHeapSpace.shtml
http://hausheer.osola.com/docs/5

Si tu programa en Java se queda sin memoria suficiente, tiene lugar el siguiente error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Se puede deber a dos motivos:

* Que tu aplicación en Java tenga una perdida de memoria. Toca buscar el problema en el código, en breve os haré un post comentando el profiler que suelo usar, que me parece genial aunque a 400€ por licencia no creo que esté al alcance de todo el mundo.
* Que tu programa realmente necesite un montón de memoria. En este caso, la memoria disponible la puedes incrementar llamando a la maquina virtual con estos parametros:

java -Xms -Xmx

Por defecto tenemos:

java -Xms32m -Xmx128m

Estos parametros se pueden pasar en diferentes puntos dependiendo del entorno que utilicemos para programar.

Otro:

Este error se puede producir por diversos motivos, un programación poco eficiente es el motivo más grave y en ocasiones es conveniente un proceso de refactorización.

Sin embargo en determinadas circunstancias se puede evitar este fallo grave ampliando el espacio de la zona de intercambio, esto se hace con los siguientes parámetros de la JVM (Máquina virtual de Java):

-Xms 

Por ejemplo: -Xms6291456, -Xms6144k, -Xms1500M

-Xmx

Por ejemplo, -Xmx83886080, -Xmx81920k, -Xmx1500M

Obviamente la cantidad de memoria que puedas emplear estará limitada por tu propia maquina, al emplear este tipo de opciones ten un poco de cuidado por que según que SSOO estés usando podrias saturar su memoria y disminuiria su rendimiento.

Si ves que ampliando la sección del área de intercambio no se resuelve tu problema, entonces existen otras soluciones más agresivas.

Otro:

If Java runs out of memory, the following error occurs:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

This can have two reasons:

  • Your Java application has a memory leak. There are tools like YourKit Java Profiler that help you to identify such leaks.
  • Your Java application really needs a lot of memory (more than 128 MB by default!). In this case the Java heap size can be increased using the following runtime parameters:
java -Xms -Xmx

Defaults are:

java -Xms32m -Xmx128m

You can set this either in the Java Control Panel or on the command line, depending on the environment you run your application.

Otro: http://forums.java.net/jive/thread.jspa?messageID=216415

Thankx for ur suggestion... ny wy my problem is not with GC info, every thing is working fine for me in that aspect, I can see the same behaviour while Im using JProbe (Profile while testing). Id like explain problem is as follows :

We have observed a new behavior in jdk 1.6 while testing . i.e., when a service is started with custom Memory arguments ( -Xms, -Xmx) which refers to HEAP memory, as per the SUN documentation the behavior must be as follows :

1. If we configure MIN and MAX memory to have a range, say MIN=64M and MAX=512M, then initially the service will occupy only 64M and later scale upto 512M on demand. This approach is having its own disadvantages as it creates more stress on JVM while scaling upto MAX.

2. If we configure MIN and MAX to the same number, then the entire memory is available to the JVM right from the start. JVM will not release the assigned memory, even if there is no activity.

We have a practice of configuring MIN and MAX to the same amount in majority of cases and it behaved as expected until jdk 1.5. And now for jdk 1.6 we observed a new trend. i.e., even if the Application is configured to have MIN and MAX values configured to the same value, JVM is only using a part of it (say 10%) when the Service is Idle(no activity).

This is causing the false alarm in the application,

Let me explain the case in details,
We configured MIN and MAX to 768MB, start the service. Now observe that the process iniatlly occupies all the Memory (say 650M, we refer to this as CAPACITY memory) and if there is no activity on the service for a period of time (say 30 min - 1 Hr), JVM performs a FULLGC and from there onwards the CAPACITY memory is cut down to 29M in which 22MB is used and 7MB free (please refer the snapshot below).

This is an intelligent behavior as far as JVM is considered;) but Runtime.getRuntime().freeMemory() ( This is the logic implemented in our Application ) will give only the Free Space which is Committed to JVM, thereby we have a False Alarm. To avoid this we need to change the logic to evaluate Free memory on the Box ( i.e., MaxHeap -Capacity + Free = Actual Free Memory avilable to JVM).

Heap memory is a part of physical memory ie., RAM. When you allocate heap size using -Xms and -Xmx your kernel will not allocate whole of the MINIMUM size to your java process. The -Xms and -Xmx is you are telling to the kernel that your process may require -Xms MINIMUM memory and -Xmx MAXIMUM memory and that MIN and MAX is Virtual. Only on demand the memory pages are allocated to your java process.


The reason why most people set MIN and MAX to same value is to avoid frequent Heap Shrinkage and Heap Growth. Frequent shrink and growth is an overhead.


martes, 28 de agosto de 2007

Jhyton 2.2

vía Barra Punto:. http://barrapunto.com/articles/07/08/26/156257.shtml

Se acaba de publicar Jython 2.2, la primera versión estable de Jython en seis años. Su funcionalidad es equivalente a la de CPython 2.2 (es decir, la implementación habitual de Python hecha en C). Jython permite programar en la máquina virtual de Java utilizando Python como lenguaje, pudiendo acceder a las clases de Java (y Java las de Jython). El siguiente objetivo es implementar Python 2.4 ó 2.5. Un ejemplo espectacular de Jython es la demostración del uso del WorldWind JDK (WorldWind es el Google Earth de la NASA).

martes, 14 de agosto de 2007

jMonkey

jMonkey Engine parece ser un compendio de librerias que fácilita la manipulación de objetos 3D.
Dicho de otra forma, tranquilamente puede ser un Engine para programar video juegos 3D en JAVA.
Estuve viendo varias imágenes y la verdad que parece muy muy bueno, será cosa de probarlo.
Por si alguno quiere echarle una ojeada.

http://jmonkeyengine.com/

miércoles, 20 de junio de 2007

¿Qué es Castor?

Antes que nada definimos data binding: Tecnología que mapea las propiedades de la instancia de un objeto de datos con con su localización en una fuente de datos. Donde Fuente de datos es cualquier repositorio donde estén o puedan almacenarse esos datos como bases de datos, directorios LDAP, archivos, etc
Ahora si: Castor es un framework data binding de codigo abierto para java. Es basicamente el camino mas corto entre: objetos java, documentos xml, y tablas SQL. Castor hace el nexo entre: Java y XML, JAVA y SQL y algunos mas.

Link: página oficial de Castor.

Instalacion de Tiles sin struts y con struts

Las "Tiles" son un un sistema de plantillas en java. Se definen diferentes templates (header, footer, menu, scripts, body) que luego pueden ser utilizados en cualquier jsp. Agiliza en desarrollo de cada página y logra una coherencia de estilos y de layouts entre las paginas de una aplicación web.

Instalar Tiles en un proyecto web (con y sin struts): http://www.allapplabs.com/tiles/installing_tiles.htm

Una alternativa al uso de tiles es "SiteMesh" el cual es un también un sistema de plantillas y un decoration framework.

La página oficial de SiteMesh es:
http://www.opensymphony.com/sitemesh/

miércoles, 6 de junio de 2007

¿Qué es un POJO?

Se denomina POJO a las clases regulares de java que no son de ningun tipo especial (como java Beans, EJB) y no cumplen nigun otro rol ni implementan alguna interfaz especial.

El acrónimo es Plan Old Java Object.

Fuente: Wikipedia

lunes, 4 de junio de 2007

OpenSwing - Componentes Swing avanzados

OpenSwing es una libreria que provee una serie de componentes gráficos avanzados y un framework para desarrollar aplicaciones java basadas en swing.

La pagina del proyecto en sourceforge es: http://sourceforge.net/projects/oswing/
La pagina oficial: http://oswing.sourceforge.net/

Framework j2ee - OpenXava

OpenXava es un framework para desarrollar en jdee, define objetos de negocio con archivos xml. Genera codigo, formularios de alta, y listados.

La pagina del proyecto en sourceforge es: http://sourceforge.net/projects/openxava/
La pagina oficial: http://www.gestion400.com/web/guest/openxava

martes, 22 de mayo de 2007

Poner al Tomcat como un servicio de Windows

Hacer un bat de lo siguiente y luego ejecutar.

D:\...\tomcat\bin\tomcat -install "NombreServicio" C:\j2sdk1.4.2_03\jre\bin\server\jvm.dll -Djava.class.path=D:\...\tomcat\bin\bootstrap.jar;C:\j2sdk1.4.2_03\lib\tools.jar -Dcatalina.home=D:\...\tomcat %CATALINA_OPTS% -Xrs -start org.apache.catalina.startup.Bootstrap -params start -stop org.apache.catalina.startup.Bootstrap -params stop -out D:\...\tomcat\logs\stdout.log -err D:\...\tomcat\logs\stderr.log

Cliente oracle en java

El programa se llama Aqua Data Studio. Es un cliente Oracle que solo necesita la conexion por jdbc. Muy bueno, facil de usar con intefaz muy intuitiva.

Link para descarga

lunes, 21 de mayo de 2007

Array In Struts

<!-- ASI SE ITERA
<logic:iterate indexId="imagesArrayLenght" id="imagesArrayLenghtId" property="offeredProductImages" name="offeredProductForm">
<nested:file property="offeredProductImages[${imagesArrayLenght}]" name="offeredProductForm" styleId="offeredProductImages[${imagesArrayLenght}]"/>
</logic:iterate> -->>


<logic:iterate indexId="currentFieldIndexId" id="currentField" property="reportFields" name="wizardForm">
<tr>
<td class="celdaFormulario" align="right">
<nested:write property="fielNameToShow" name="currentField"/>
</td>
<td class="celdaFormulario" align="left">
<nested:text property="reportFields[${currentFieldIndexId}].fieldValue" name="wizardForm" styleId="${ currentField.fieldName}"/>
<nested:equal value="true" property="requiered" name="currentField">
<font color="red">*</font>
</nested:equal>
<nested:equal value="DateType" property="fieldType" name="currentField"><!-- Mostrar calendar -->
<input type="button" id="btDate<nested:write property="fieldName" name="currentField"/>" value="..." onmousedown="dateChooser('<nested:write property="fieldName" name="currentField"/>','btDate<nested:write property="fieldName" name="currentField"/>');" />
</nested:equal>
</td>
</tr>
</logic:iterate>

Java Web - Suggest tag

Este tag es funciona de la siguiente manera:
Se hace un click en un textfield y va mostrando una lista que se va filtrando con los caracteres ingresados hasta el momento. Lo hace con Ajax.
link: http://struts.application-servers.com/suggest/index.html

Paso 1: crear la clase


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import fr.improve.struts.taglib.layout.suggest.SuggestAction;

public class CountrySuggestAction extends SuggestAction {

public Collection getSuggestionList(HttpServletRequest in_request, String in_word) {

// Get all the country names
Collection allCountries = CountryCollection.getAllCountries();

// Start to build the suggestions list
ArrayList suggestions = new ArrayList();

if (in_word != null && in_word.length() > 0)
{
Iterator iter = allCountries.iterator();

while(iter.hasNext())
{
String currentWord = (String) iter.next();

if(currentWord.toLowerCase().startsWith(in_word.toLowerCase()))
suggestions.add(currentWord);
}
}

return suggestions;
}

}

Paso 2: configurar la accion de struts


<struts-config>
<action-mappings>
<action path="/getCountrySuggestions"
type="fr.improve.demosuggest.countries.CountrySuggestAction">
</action>
</action-mappings>
</struts-config>


Paso 3: Crear el jsp

<%@ taglib uri="/WEB-INF/struts-layout.tld" prefix="layout" %>
<layout:html>
<layout:suggest suggestAction="/getCountrySuggestions" key="Country" styleId="myTextField" value="" suggestCount="8" />
</layout:html>

Swing - tabla con filtros de búsqueda dinámicos

Esto es: tenemos un textfield y al ingresar una letra se va actualizando dinamicamente la tabla swing.

El link a la pagina es:

http://java.sun.com/developer/JDCTechTips/2005/tt1115.html

Conectar Java con Flash usando WebServices (configuracion de jbuilder)

Los Web Services o servicios webs son una forma de comunicar aplicaciones diferentes usando XML. Esto resulta muy útil ya que nos brinda una opción de comunicación estándar que podemos usar entre aplicaciones realizadas con distintos lenguajes como actionscript, c# o java.

Link a la pagina