Java

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Java and the translation is 38% complete.

Outdated translations are marked like this.
Other languages:
Deutsch • ‎English • ‎español • ‎français • ‎português do Brasil • ‎русский • ‎中文(中国大陆)‎ • ‎日本語 • ‎한국어
Resources

Java é uma linguagem de programação, originalmente desenvolvida pela Sun Microsystems, que usa runtime para permitir a execução de aplicativos desenvolvidos em Java em várias plataformas. É uma escolha popular para desenvolvedores que querem criar aplicativos cross-plataform.

O que é Java?

Visão Geral

Java é uma linguagem de programação desenvolvida por engenheiros da Sun Microsystems. É uma linguagem orientada a objetos e projetada para rodar em várias plataformas sem a necessidade de recompilar o código em cada uma delas. Embora Java possa ser compilado como um programa nativo, a maior parte da popularidade do Java pode ser atribuída à sua portabilidade, junto com outras características, como coleta de lixo. Para tornar a independência de plataforma possível, o compilador do Java compila o código Java para uma representação intermediária, chamada "Java bytecode" que roda em um JRE (Java Runtime Environment) e não diretamente no sistema operacional.

Para executar o Java bytecode, é preciso ter o JRE (Java Runtime Environment) instalado. o JRE fornece bibliotecas principais, uma Máquina Virutal Java dependente da plataforma, plugins para browsers, entre outras coisas. O JDK (Java Development Kit) adiciona ferramentas de programação, como um compilador de bytecode e um debugger.

JVM languages

The Java virtual machine is not used exclusively by Java programming language. Multiple programming languages use the Java platform and run on the JVM. Examples of such include: Clojure, Apache Groovy, Kotlin or Scala.

Instalando a máquina virtual

O básico

Gentoo fornece vários Java Runtime Environments (JREs) e Development Kits (JDKs). As opções atuais incluem:

Vendor JDK JRE
The IcedTea Open Java SE (formerly icedtea6-bin) dev-java/icedtea and dev-java/icedtea-bin
OpenJDK dev-java/openjdk and dev-java/openjdk-bin
Oracle's Java dev-java/oracle-jdk-bin dev-java/oracle-jre-bin
The GCJ IcedTea GNU GCC Java (currently IcedTea-7) dev-java/icedtea sys-devel/gcc USE="gcj"

Instalando o JRE/JDK

Para instalar JDK padrão execute:

root #emerge --ask virtual/jdk

Para instalar o JRE padrão execute:

root #emerge --ask virtual/jre
Warning
Some JDKs and JREs, including the Oracle packages, require accepting an EULA (End-User License Agreement). If its license (such as dlj-1.1) is not listed in the ACCEPT_LICENSE variable (found in /etc/portage/make.conf), then the JDK/JRE will be unable to be installed. For more information on how to add acceptable licenses to make.conf read the Licenses chapter of the Portage Handbook.

Para evitar qualquer problema de licença, considere instalar o icedtea-bin, que é uma implementação Java aberta do projeto OpenJDK.

Note
Esteja ciente de que cada JDK incluirá um JRE ; A instalação de um JRE não é necessária se um JDK tiver sido instalado.

Instalando a Máquina Virtual IcedTea GCJ

Important
gcj está obsoleto e foi removido nas versões 7.0 e superiores do GCC. Está indisponível a partir do GCC 6.0 no Gentoo. Considere esta seção obsoleta.

The IcedTea virtual machine is provided in source code and requires compilation by a Java bytecode compiler. This bootstrapping can be executed by the GNU Compiler for Java (GCJ). This compiler is available when GCC is built with the gcj USE flag.

When GCC is rebuilt with this USE flag set, the dev-java/icedtea package can be installed. Because of a Portage bug, users need to install dev-java/gcj-jdk and dev-java/ant-core explicitly first if they are not already present.

root #emerge --ask --oneshot dev-java/gcj-jdk dev-java/ant-core
root #emerge --ask dev-java/icedtea:7

Installing fetch-restricted virtual machines

Some of the JDKs and JREs require a few extra steps in their configurations. Emerge the packages as normal. If additional steps are required the ebuilds will provide instruction for the user on where to go and what to download.

Download the indicated file(s) into /var/cache/distfiles (or the value of DISTDIR). Once the files are in the right directories, rerun the emerge command, at which point the JRE/JDK will be begin to install.

Setting up a headless JRE

Sometimes there is no need for a full JRE with all the capabilities of java. Using java on a server often does not require any GUI, graphical, sound or even printer related features. To install a simplified (sometimes also referred to as headless) JRE, a few USE flags need to be changed for the selected JRE flavor.

FILE /etc/portage/package.useRequired USE flag changes
dev-java/icedtea headless-awt -alsa -cups
dev-java/icedtea-bin headless-awt -alsa -cups
dev-java/oracle-jre-bin headless-awt -alsa -cups

Depending on the current Gentoo profile, this might already be the case. As usual, the USE flag settings that are applicable to a particular package can be checked by running emerge in pretend mode:

user $emerge --pretend --verbose virtual/jre

Configurando a Máquina Virtual Java

Visão Geral

Gentoo tem a capacidade de ter múltiplos JDks e JREs instalados sem causar conflitos.

Usando a ferramenta java-config com privilégios de root, uma máquina virtual java padrão pode ser configurada. Usuários também podem usar o java-config para configurar uma VM personalizada.

Note
eselect também pode ser usado para mudar a VM do sistema e do usuário. Veja eselect java-vm help.

Configurando uma máquina virtual padrão

Executando o comando java-config com a opção --list-available-vms irá produzir uma lista de todos os JREs a JDKs instalados no sistema. Por exemplo:

root #java-config --list-available-vms
The following VMs are available for generation-2:
1)      IcedTea JDK 7.2.6.3 [icedtea-7]
*)      IcedTea JDK 3.0.1 [icedtea-8]
Note
VMs marcadas como 'Build Only' podem conter vulnerabilidades de segurança e/ou estar no fim de vida (end of life). Gentoo recomenda que essas VMs não sejam selecionadas como VM do sistema ou do usuário. Por favor, veja Build Only VM para mais informações.

O * indica que esta é a JVM ativa atual(system-vm ou user-vm quando configurada). O nome entre colchetes ([]) é o identificador ou ID dessa VM específica. O identificador ou o número para java-config --set-system-vm pode ser usado para definir a VM. O texto seguinte fornece um exemplo de como configurar a VM do sistema.

Configurando a VM do sistema(preferido):

root #java-config --set-system-vm icedtea-7
Now using icedtea-7 as your generation-2 system JVM

Método alternativo: selecione a VM pelo número identificador:

root #java-config --set-system-vm 3
Now using icedtea-7 as your generation-2 system JVM

Como usuário comum, use java-config --set-user-vm.

Note
source-ing the profile for existing shell sessions is not usually needed when changing the user or system VM. The only exception is that variables such as JAVA_HOME will still point to the old location after setting a user VM for the first time or revert back to the system VM.

Build only VM

Some virtual machines are flagged as build-only due to being EOL and/or containing security vulnerabilities. These virtual machines will not automatically be used by Gentoo for the running of applications using Gentoo launchers (run-java-tool script designed for switching VMs), but will still be available for use by Gentoo's build environment as some packages may require them for building. The setting of these virtual machines as either the system or user VM is strongly discouraged as these VMs will then be used when running the /usr/bin/{java,javac,..} executables, as well as used by any packages not using Gentoo's launcher scripts.

Setting a default CLASSPATH

Warning
The options explained in this section should be considered deprecated and will most likely be removed in the future. It is strongly recommended against using these, because Java projects or applications should ideally manage their own classpaths. When choosing to specify a default CLASSPATH, some applications may behave unexpectedly, because classes they were not expecting to be on the classpath.

java-config can also be used to set a system-wide default CLASSPATH, as well a user-specific default CLASSPATH.

First, list available Java libraries installed on the system to possibly put in the CLASSPATH variable. Here is an example of output:

root #java-config --list-available-packages
[xerces-2] The next generation of high performance, fully compliant XML parsers in the Apache Xerces family (/usr/share/xerces-2/package.env)
[junit] Simple framework to write repeatable tests (/usr/share/junit/package.env)
[bsh] BeanShell: A small embeddable Java source interpreter (/usr/share/bsh/package.env)
[bcel] The Byte Code Engineering Library: analyze, create, manipulate Java class files (/usr/share/bcel/package.env)
[log4j] A low-overhead robust logging package for Java (/usr/share/log4j/package.env)
...

Again, the names in brackets ([]) are the IDs to pass to java-config --set-system-classpath. Here is an example:

root #java-config --set-system-classpath log4j,xerces-2
Note
The current directory (.) will not be part of the system classpath, as that should be added to the system's login profile.

Update the environment by logging out, then in again or by typing source /etc/profile.

For users, java-config --set-user-classpath will create ~/.gentoo/java-env-classpath file, which should be sourced from the shell's profile.

CODE Sourcing user specific classpath
if [[ -f "${HOME}/.gentoo/java-env-classpath" ]]; then
       source ${HOME}/.gentoo/java-env-classpath
fi

If desiring a system wide or user default classpath add something like the following to the shell's profile. This is advised against:

root #export CLASSPATH="${CLASSPATH}:$(java-config --classpath log4j,xerces-2)"

Java browser plugins

Important
The Java plugin support had been deprecated in JDK 9[1].

The Java browser plugin used to be managed via eselect java-nsplugin. This has now been removed in favor of a simpler out-of-the-box experience. For basic usage, simply emerge the chosen JVM with the nsplugin USE flag enabled. Note that Oracle's plugin is only available for amd64 and x86.

Note
Note that Chromium-based browsers since version 42 and Firefox since version 52 no longer support NPAPI-based plugins[2]. This effectively disables the Java plugin on modern browsers.

For more information, including JVM selection, Web Start, and multilib, see the README installed with icedtea-web.

USE flags for use with Java

Setting USE flags

For more information regarding USE flags, refer to the USE flags chapter from the Gentoo Handbook.

USE flags

  • The java flag adds support for Java in a variety of programs;
  • The nsplugin flag adds support for Mozilla-like browsers (including Firefox). This is needed for viewing Java applets in a Mozilla-like browser;
  • The jce flag adds support for the Java Cryptography Engine;

Following USE flags go in JAVA_PKG_IUSE.

  • The source flag installs a zip of the source code of a package. This is traditionally used for IDEs to 'attach' source to the libraries that are being use;
  • For Java packages, the doc flag will build API documentation using javadoc.

See also

External resources

More information can be found offline:

  • man java-config
  • java-config --help

For suggestions or questions regarding this document, please email the Gentoo Java team: java@gentoo.org

References

  1. JDK 9 and the Java Plugin, java.com. Retrieved on November 30, 2018
  2. How do I enable Java in my web browser?, java.com. Retrieved on November 30, 2018

This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Joshua Nichols, Karl Trygve Kalleberg,
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article's associated history page.