提交 d84d71b5 编写于 作者: L lana

Merge

...@@ -31,7 +31,7 @@ BUILDDIR = .. ...@@ -31,7 +31,7 @@ BUILDDIR = ..
PRODUCT = com PRODUCT = com
include $(BUILDDIR)/common/Defs.gmk include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = sun SUBDIRS = sun oracle
include $(BUILDDIR)/common/Subdirs.gmk include $(BUILDDIR)/common/Subdirs.gmk
all build clean clobber:: all build clean clobber::
......
#
# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
BUILDDIR = ../..
PRODUCT = oracle
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = net
include $(BUILDDIR)/common/Subdirs.gmk
all build clean clobber::
$(SUBDIRS-loop)
#
# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
BUILDDIR = ../../..
PRODUCT = oracle
include $(BUILDDIR)/common/Defs.gmk
#
# Files to compile
#
AUTO_FILES_JAVA_DIRS = com/oracle/net
#
# Rules
#
include $(BUILDDIR)/common/Classes.gmk
...@@ -573,13 +573,13 @@ $(NOT_RT_JAR_LIST): FRC ...@@ -573,13 +573,13 @@ $(NOT_RT_JAR_LIST): FRC
$(ECHO) "sun/jvmstat/" >> $@ $(ECHO) "sun/jvmstat/" >> $@
$(ECHO) "sun/nio/cs/ext/" >> $@ $(ECHO) "sun/nio/cs/ext/" >> $@
$(ECHO) "sun/awt/HKSCS.class" >> $@ $(ECHO) "sun/awt/HKSCS.class" >> $@
$(ECHO) "sun/awt/motif/X11GB2312$Decoder.class" >> $@ $(ECHO) "sun/awt/motif/X11GB2312\$$Decoder.class" >> $@
$(ECHO) "sun/awt/motif/X11GB2312$Encoder.class" >> $@ $(ECHO) "sun/awt/motif/X11GB2312\$$Encoder.class" >> $@
$(ECHO) "sun/awt/motif/X11GB2312.class" >> $@ $(ECHO) "sun/awt/motif/X11GB2312.class" >> $@
$(ECHO) "sun/awt/motif/X11GBK$Encoder.class" >> $@ $(ECHO) "sun/awt/motif/X11GBK\$$Encoder.class" >> $@
$(ECHO) "sun/awt/motif/X11GBK.class" >> $@ $(ECHO) "sun/awt/motif/X11GBK.class" >> $@
$(ECHO) "sun/awt/motif/X11KSC5601$Decoder.class" >> $@ $(ECHO) "sun/awt/motif/X11KSC5601\$$Decoder.class" >> $@
$(ECHO) "sun/awt/motif/X11KSC5601$Encoder.class" >> $@ $(ECHO) "sun/awt/motif/X11KSC5601\$$Encoder.class" >> $@
$(ECHO) "sun/awt/motif/X11KSC5601.class" >> $@ $(ECHO) "sun/awt/motif/X11KSC5601.class" >> $@
$(ECHO) "sun/rmi/rmic/" >> $@ $(ECHO) "sun/rmi/rmic/" >> $@
$(ECHO) "sun/tools/asm/" >> $@ $(ECHO) "sun/tools/asm/" >> $@
......
...@@ -91,6 +91,8 @@ SCTPAPI_PKGS = com.sun.nio.sctp ...@@ -91,6 +91,8 @@ SCTPAPI_PKGS = com.sun.nio.sctp
TRACING_PKGS = com.sun.tracing \ TRACING_PKGS = com.sun.tracing \
com.sun.tracing.dtrace com.sun.tracing.dtrace
ORACLENET_PKGS = com.oracle.net
# non-core packages in rt.jar # non-core packages in rt.jar
NON_CORE_PKGS = $(DOMAPI_PKGS) \ NON_CORE_PKGS = $(DOMAPI_PKGS) \
$(MGMT_PKGS) \ $(MGMT_PKGS) \
...@@ -101,5 +103,6 @@ NON_CORE_PKGS = $(DOMAPI_PKGS) \ ...@@ -101,5 +103,6 @@ NON_CORE_PKGS = $(DOMAPI_PKGS) \
$(HTTPSERVER_PKGS) \ $(HTTPSERVER_PKGS) \
$(SMARTCARDIO_PKGS) \ $(SMARTCARDIO_PKGS) \
$(TRACING_PKGS) \ $(TRACING_PKGS) \
$(SCTPAPI_PKGS) $(SCTPAPI_PKGS) \
$(ORACLENET_PKGS)
...@@ -183,10 +183,22 @@ JAVA_JAVA_java = \ ...@@ -183,10 +183,22 @@ JAVA_JAVA_java = \
java/util/MissingFormatWidthException.java \ java/util/MissingFormatWidthException.java \
java/util/UnknownFormatConversionException.java \ java/util/UnknownFormatConversionException.java \
java/util/UnknownFormatFlagsException.java \ java/util/UnknownFormatFlagsException.java \
java/util/IllformedLocaleException.java \
java/util/FormatterClosedException.java \ java/util/FormatterClosedException.java \
java/util/ListResourceBundle.java \ java/util/ListResourceBundle.java \
sun/util/EmptyListResourceBundle.java \ sun/util/EmptyListResourceBundle.java \
java/util/Locale.java \ java/util/Locale.java \
sun/util/locale/AsciiUtil.java \
sun/util/locale/BaseLocale.java \
sun/util/locale/Extension.java \
sun/util/locale/InternalLocaleBuilder.java \
sun/util/locale/LanguageTag.java \
sun/util/locale/LocaleExtensions.java \
sun/util/locale/LocaleObjectCache.java \
sun/util/locale/LocaleSyntaxException.java \
sun/util/locale/ParseStatus.java \
sun/util/locale/StringTokenIterator.java \
sun/util/locale/UnicodeLocaleExtension.java \
java/util/LocaleISOData.java \ java/util/LocaleISOData.java \
sun/util/LocaleServiceProviderPool.java \ sun/util/LocaleServiceProviderPool.java \
sun/util/LocaleDataMetaInfo.java \ sun/util/LocaleDataMetaInfo.java \
......
...@@ -39,10 +39,6 @@ FILES_c = \ ...@@ -39,10 +39,6 @@ FILES_c = \
ResolverConfigurationImpl.c \ ResolverConfigurationImpl.c \
DefaultProxySelector.c DefaultProxySelector.c
ifeq ($(PLATFORM), solaris)
FILES_c += SdpProvider.c
endif
ifeq ($(PLATFORM), linux) ifeq ($(PLATFORM), linux)
FILES_c += linux_close.c FILES_c += linux_close.c
endif endif
......
...@@ -44,6 +44,8 @@ ifeq ($(PLATFORM), windows) ...@@ -44,6 +44,8 @@ ifeq ($(PLATFORM), windows)
endif endif
FILES_c += NTLMAuthSequence.c FILES_c += NTLMAuthSequence.c
FILES_c += NetworkInterface_winXP.c FILES_c += NetworkInterface_winXP.c
else
FILES_c += SdpSupport.c
endif endif
FILES_export = \ FILES_export = \
...@@ -84,7 +86,8 @@ endif ...@@ -84,7 +86,8 @@ endif
# #
# Find platform specific native code # Find platform specific native code
# #
vpath %.c $(PLATFORM_SRC)/native/sun/net/dns $(PLATFORM_SRC)/native/sun/net/www/protocol/http/ntlm $(PLATFORM_SRC)/native/sun/net/spi vpath %.c $(PLATFORM_SRC)/native/sun/net/dns $(PLATFORM_SRC)/native/sun/net/www/protocol/http/ntlm \
$(PLATFORM_SRC)/native/sun/net/sdp $(PLATFORM_SRC)/native/sun/net/spi
# #
# Include rules # Include rules
......
...@@ -88,9 +88,10 @@ SUNWprivate_1.1 { ...@@ -88,9 +88,10 @@ SUNWprivate_1.1 {
Java_java_net_PlainDatagramSocketImpl_setTimeToLive; Java_java_net_PlainDatagramSocketImpl_setTimeToLive;
Java_sun_net_dns_ResolverConfigurationImpl_localDomain0; Java_sun_net_dns_ResolverConfigurationImpl_localDomain0;
Java_sun_net_dns_ResolverConfigurationImpl_fallbackDomain0; Java_sun_net_dns_ResolverConfigurationImpl_fallbackDomain0;
Java_sun_net_sdp_SdpSupport_convert0;
Java_sun_net_sdp_SdpSupport_create0;
Java_sun_net_spi_DefaultProxySelector_init; Java_sun_net_spi_DefaultProxySelector_init;
Java_sun_net_spi_DefaultProxySelector_getSystemProxy; Java_sun_net_spi_DefaultProxySelector_getSystemProxy;
Java_sun_net_spi_SdpProvider_convert;
NET_AllocSockaddr; NET_AllocSockaddr;
NET_SockaddrToInetAddress; NET_SockaddrToInetAddress;
NET_SockaddrEqualsInetAddress; NET_SockaddrEqualsInetAddress;
......
...@@ -83,6 +83,7 @@ FILES_src = \ ...@@ -83,6 +83,7 @@ FILES_src = \
java/nio/file/ClosedFileSystemException.java \ java/nio/file/ClosedFileSystemException.java \
java/nio/file/ClosedWatchServiceException.java \ java/nio/file/ClosedWatchServiceException.java \
java/nio/file/CopyOption.java \ java/nio/file/CopyOption.java \
java/nio/file/DirectoryIteratorException.java \
java/nio/file/DirectoryNotEmptyException.java \ java/nio/file/DirectoryNotEmptyException.java \
java/nio/file/DirectoryStream.java \ java/nio/file/DirectoryStream.java \
java/nio/file/FileAlreadyExistsException.java \ java/nio/file/FileAlreadyExistsException.java \
...@@ -199,6 +200,7 @@ FILES_src = \ ...@@ -199,6 +200,7 @@ FILES_src = \
sun/nio/ch/PipeImpl.java \ sun/nio/ch/PipeImpl.java \
sun/nio/ch/PollArrayWrapper.java \ sun/nio/ch/PollArrayWrapper.java \
sun/nio/ch/Reflect.java \ sun/nio/ch/Reflect.java \
sun/nio/ch/Secrets.java \
sun/nio/ch/SelectionKeyImpl.java \ sun/nio/ch/SelectionKeyImpl.java \
sun/nio/ch/SelectorImpl.java \ sun/nio/ch/SelectorImpl.java \
sun/nio/ch/SelectorProviderImpl.java \ sun/nio/ch/SelectorProviderImpl.java \
......
...@@ -89,7 +89,7 @@ SUNWprivate_1.1 { ...@@ -89,7 +89,7 @@ SUNWprivate_1.1 {
Java_sun_nio_ch_IOUtil_drain; Java_sun_nio_ch_IOUtil_drain;
Java_sun_nio_ch_IOUtil_fdVal; Java_sun_nio_ch_IOUtil_fdVal;
Java_sun_nio_ch_IOUtil_initIDs; Java_sun_nio_ch_IOUtil_initIDs;
Java_sun_nio_ch_IOUtil_initPipe; Java_sun_nio_ch_IOUtil_makePipe;
Java_sun_nio_ch_IOUtil_randomBytes; Java_sun_nio_ch_IOUtil_randomBytes;
Java_sun_nio_ch_IOUtil_setfdVal; Java_sun_nio_ch_IOUtil_setfdVal;
Java_sun_nio_ch_NativeThread_current; Java_sun_nio_ch_NativeThread_current;
......
...@@ -76,7 +76,7 @@ SUNWprivate_1.1 { ...@@ -76,7 +76,7 @@ SUNWprivate_1.1 {
Java_sun_nio_ch_IOUtil_drain; Java_sun_nio_ch_IOUtil_drain;
Java_sun_nio_ch_IOUtil_fdVal; Java_sun_nio_ch_IOUtil_fdVal;
Java_sun_nio_ch_IOUtil_initIDs; Java_sun_nio_ch_IOUtil_initIDs;
Java_sun_nio_ch_IOUtil_initPipe; Java_sun_nio_ch_IOUtil_makePipe;
Java_sun_nio_ch_IOUtil_randomBytes; Java_sun_nio_ch_IOUtil_randomBytes;
Java_sun_nio_ch_IOUtil_setfdVal; Java_sun_nio_ch_IOUtil_setfdVal;
Java_sun_nio_ch_NativeThread_current; Java_sun_nio_ch_NativeThread_current;
......
# #
# Copyright (c) 1996, 2007, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -29,6 +29,7 @@ FILES_java = \ ...@@ -29,6 +29,7 @@ FILES_java = \
java/text/AttributedString.java \ java/text/AttributedString.java \
java/text/BreakDictionary.java \ java/text/BreakDictionary.java \
java/text/BreakIterator.java \ java/text/BreakIterator.java \
java/text/CalendarBuilder.java \
java/text/CharacterIterator.java \ java/text/CharacterIterator.java \
java/text/CharacterIteratorFieldDelegate.java \ java/text/CharacterIteratorFieldDelegate.java \
java/text/ChoiceFormat.java \ java/text/ChoiceFormat.java \
......
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
FILES_c = \ FILES_c = \
cmscam02.c \ cmscam02.c \
cmscam97.c \
cmscgats.c \ cmscgats.c \
cmscnvrt.c \ cmscnvrt.c \
cmserr.c \ cmserr.c \
...@@ -35,13 +34,17 @@ FILES_c = \ ...@@ -35,13 +34,17 @@ FILES_c = \
cmsio0.c \ cmsio0.c \
cmsio1.c \ cmsio1.c \
cmslut.c \ cmslut.c \
cmsmatsh.c \ cmsmd5.c \
cmsmtrx.c \ cmsmtrx.c \
cmsnamed.c \ cmsnamed.c \
cmsopt.c \
cmspack.c \ cmspack.c \
cmspcs.c \ cmspcs.c \
cmsplugin.c \
cmsps2.c \ cmsps2.c \
cmssamp.c \ cmssamp.c \
cmssm.c \
cmstypes.c \
cmsvirt.c \ cmsvirt.c \
cmswtpnt.c \ cmswtpnt.c \
cmsxform.c \ cmsxform.c \
......
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
FILES_c = \ FILES_c = \
cmscam02.c \ cmscam02.c \
cmscam97.c \
cmscgats.c \ cmscgats.c \
cmscnvrt.c \ cmscnvrt.c \
cmserr.c \ cmserr.c \
...@@ -35,13 +34,17 @@ FILES_c = \ ...@@ -35,13 +34,17 @@ FILES_c = \
cmsio0.c \ cmsio0.c \
cmsio1.c \ cmsio1.c \
cmslut.c \ cmslut.c \
cmsmatsh.c \ cmsmd5.c \
cmsmtrx.c \ cmsmtrx.c \
cmsnamed.c \ cmsnamed.c \
cmsopt.c \
cmspack.c \ cmspack.c \
cmspcs.c \ cmspcs.c \
cmsplugin.c \
cmsps2.c \ cmsps2.c \
cmssamp.c \ cmssamp.c \
cmssm.c \
cmstypes.c \
cmsvirt.c \ cmsvirt.c \
cmswtpnt.c \ cmswtpnt.c \
cmsxform.c \ cmsxform.c \
......
...@@ -80,8 +80,8 @@ vpath %.c $(SHARE_SRC)/native/$(PKGDIR) ...@@ -80,8 +80,8 @@ vpath %.c $(SHARE_SRC)/native/$(PKGDIR)
vpath %.c $(SHARE_SRC)/native/sun/java2d vpath %.c $(SHARE_SRC)/native/sun/java2d
ifeq ($(PLATFORM), windows) ifeq ($(PLATFORM), windows)
OTHER_CFLAGS += -DCMS_IS_WINDOWS_ -Dsqrtf=sqrt
OTHER_LDLIBS = user32.lib version.lib $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib OTHER_LDLIBS = $(OBJDIR)/../../../sun.awt/awt/$(OBJDIRNAME)/awt.lib
OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \ OTHER_INCLUDES += -I$(SHARE_SRC)/native/sun/java2d \
-I$(SHARE_SRC)/native/sun/awt/debug -I$(SHARE_SRC)/native/sun/awt/debug
......
...@@ -53,6 +53,7 @@ FILES_java = \ ...@@ -53,6 +53,7 @@ FILES_java = \
sun/net/ftp/FtpProtocolException.java \ sun/net/ftp/FtpProtocolException.java \
sun/net/ftp/impl/FtpClient.java \ sun/net/ftp/impl/FtpClient.java \
sun/net/ftp/impl/DefaultFtpClientProvider.java \ sun/net/ftp/impl/DefaultFtpClientProvider.java \
sun/net/sdp/SdpSupport.java \
sun/net/spi/DefaultProxySelector.java \ sun/net/spi/DefaultProxySelector.java \
sun/net/spi/nameservice/NameServiceDescriptor.java \ sun/net/spi/nameservice/NameServiceDescriptor.java \
sun/net/spi/nameservice/NameService.java \ sun/net/spi/nameservice/NameService.java \
...@@ -136,8 +137,6 @@ FILES_java = \ ...@@ -136,8 +137,6 @@ FILES_java = \
ifeq ($(PLATFORM), windows) ifeq ($(PLATFORM), windows)
FILES_java += sun/net/www/protocol/http/ntlm/NTLMAuthSequence.java FILES_java += sun/net/www/protocol/http/ntlm/NTLMAuthSequence.java
endif else
FILES_java += sun/net/sdp/SdpProvider.java
ifeq ($(PLATFORM), solaris)
FILES_java += sun/net/spi/SdpProvider.java
endif endif
...@@ -712,19 +712,19 @@ SetModulesBootClassPath(const char *jrepath) ...@@ -712,19 +712,19 @@ SetModulesBootClassPath(const char *jrepath)
struct stat statbuf; struct stat statbuf;
/* return if jre/lib/rt.jar exists */ /* return if jre/lib/rt.jar exists */
sprintf(pathname, "%s%slib%srt.jar", jrepath, separator, separator); JLI_Snprintf(pathname, sizeof(pathname), "%s%slib%srt.jar", jrepath, separator, separator);
if (stat(pathname, &statbuf) == 0) { if (stat(pathname, &statbuf) == 0) {
return; return;
} }
/* return if jre/classes exists */ /* return if jre/classes exists */
sprintf(pathname, "%s%sclasses", jrepath, separator); JLI_Snprintf(pathname, sizeof(pathname), "%s%sclasses", jrepath, separator);
if (stat(pathname, &statbuf) == 0) { if (stat(pathname, &statbuf) == 0) {
return; return;
} }
/* modularized jre */ /* modularized jre */
sprintf(pathname, "%s%slib%s*", jrepath, separator, separator); JLI_Snprintf(pathname, sizeof(pathname), "%s%slib%s*", jrepath, separator, separator);
s = (char *) JLI_WildcardExpandClasspath(pathname); s = (char *) JLI_WildcardExpandClasspath(pathname);
def = JLI_MemAlloc(sizeof(format) def = JLI_MemAlloc(sizeof(format)
- 2 /* strlen("%s") */ - 2 /* strlen("%s") */
...@@ -1624,11 +1624,8 @@ ReadKnownVMs(const char *jrepath, const char * arch, jboolean speculative) ...@@ -1624,11 +1624,8 @@ ReadKnownVMs(const char *jrepath, const char * arch, jboolean speculative)
if (JLI_IsTraceLauncher()) { if (JLI_IsTraceLauncher()) {
start = CounterGet(); start = CounterGet();
} }
JLI_Snprintf(jvmCfgName, sizeof(jvmCfgName), "%s%slib%s%s%sjvm.cfg",
JLI_StrCpy(jvmCfgName, jrepath); jrepath, FILESEP, FILESEP, arch, FILESEP);
JLI_StrCat(jvmCfgName, FILESEP "lib" FILESEP);
JLI_StrCat(jvmCfgName, arch);
JLI_StrCat(jvmCfgName, FILESEP "jvm.cfg");
jvmCfg = fopen(jvmCfgName, "r"); jvmCfg = fopen(jvmCfgName, "r");
if (jvmCfg == NULL) { if (jvmCfg == NULL) {
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.net;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
import java.net.SocketException;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.io.IOException;
import java.io.FileDescriptor;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.lang.reflect.Constructor;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationTargetException;
import sun.net.sdp.SdpSupport;
/**
* This class consists exclusively of static methods that Sockets or Channels to
* sockets that support the InfiniBand Sockets Direct Protocol (SDP).
*/
public final class Sdp {
private Sdp() { }
/**
* The package-privage ServerSocket(SocketImpl) constructor
*/
private static final Constructor<ServerSocket> serverSocketCtor;
static {
try {
serverSocketCtor = (Constructor<ServerSocket>)
ServerSocket.class.getDeclaredConstructor(SocketImpl.class);
setAccessible(serverSocketCtor);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
/**
* The package-private SdpSocketImpl() constructor
*/
private static final Constructor<SocketImpl> socketImplCtor;
static {
try {
Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null);
socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor();
setAccessible(socketImplCtor);
} catch (ClassNotFoundException e) {
throw new AssertionError(e);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
private static void setAccessible(final AccessibleObject o) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
o.setAccessible(true);
return null;
}
});
}
/**
* SDP enabled Socket.
*/
private static class SdpSocket extends Socket {
SdpSocket(SocketImpl impl) throws SocketException {
super(impl);
}
}
/**
* Creates a SDP enabled SocketImpl
*/
private static SocketImpl createSocketImpl() {
try {
return socketImplCtor.newInstance();
} catch (InstantiationException x) {
throw new AssertionError(x);
} catch (IllegalAccessException x) {
throw new AssertionError(x);
} catch (InvocationTargetException x) {
throw new AssertionError(x);
}
}
/**
* Creates an unconnected and unbound SDP socket. The {@code Socket} is
* associated with a {@link java.net.SocketImpl} of the system-default type.
*
* @return a new Socket
*
* @throws UnsupportedOperationException
* If SDP is not supported
* @throws IOException
* If an I/O error occurs
*/
public static Socket openSocket() throws IOException {
SocketImpl impl = createSocketImpl();
return new SdpSocket(impl);
}
/**
* Creates an unbound SDP server socket. The {@code ServerSocket} is
* associated with a {@link java.net.SocketImpl} of the system-default type.
*
* @return a new ServerSocket
*
* @throws UnsupportedOperationException
* If SDP is not supported
* @throws IOException
* If an I/O error occurs
*/
public static ServerSocket openServerSocket() throws IOException {
// create ServerSocket via package-private constructor
SocketImpl impl = createSocketImpl();
try {
return serverSocketCtor.newInstance(impl);
} catch (IllegalAccessException x) {
throw new AssertionError(x);
} catch (InstantiationException x) {
throw new AssertionError(x);
} catch (InvocationTargetException x) {
Throwable cause = x.getCause();
if (cause instanceof IOException)
throw (IOException)cause;
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new RuntimeException(x);
}
}
/**
* Opens a socket channel to a SDP socket.
*
* <p> The channel will be associated with the system-wide default
* {@link java.nio.channels.spi.SelectorProvider SelectorProvider}.
*
* @return a new SocketChannel
*
* @throws UnsupportedOperationException
* If SDP is not supported or not supported by the default selector
* provider
* @throws IOException
* If an I/O error occurs.
*/
public static SocketChannel openSocketChannel() throws IOException {
FileDescriptor fd = SdpSupport.createSocket();
return sun.nio.ch.Secrets.newSocketChannel(fd);
}
/**
* Opens a socket channel to a SDP socket.
*
* <p> The channel will be associated with the system-wide default
* {@link java.nio.channels.spi.SelectorProvider SelectorProvider}.
*
* @return a new ServerSocketChannel
*
* @throws UnsupportedOperationException
* If SDP is not supported or not supported by the default selector
* provider
* @throws IOException
* If an I/O error occurs
*/
public static ServerSocketChannel openServerSocketChannel()
throws IOException
{
FileDescriptor fd = SdpSupport.createSocket();
return sun.nio.ch.Secrets.newServerSocketChannel(fd);
}
}
/* /*
* Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,13 +31,14 @@ import java.util.Collections; ...@@ -31,13 +31,14 @@ import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.applet.Applet;
import java.awt.AWTEvent; import java.awt.AWTEvent;
import java.awt.EventQueue; import java.awt.EventQueue;
import java.awt.Component; import java.awt.Component;
import java.awt.Container; import java.awt.Container;
import java.awt.Window;
import javax.swing.JComponent; import javax.swing.JComponent;
import javax.swing.RepaintManager; import javax.swing.RepaintManager;
import javax.swing.SwingUtilities;
/** /**
* A collection of utility methods for Swing. * A collection of utility methods for Swing.
...@@ -91,7 +92,7 @@ public class SwingUtilities3 { ...@@ -91,7 +92,7 @@ public class SwingUtilities3 {
*/ */
public static void setVsyncRequested(Container rootContainer, public static void setVsyncRequested(Container rootContainer,
boolean isRequested) { boolean isRequested) {
assert SwingUtilities.getRoot(rootContainer) == rootContainer; assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
if (isRequested) { if (isRequested) {
vsyncedMap.put(rootContainer, Boolean.TRUE); vsyncedMap.put(rootContainer, Boolean.TRUE);
} else { } else {
...@@ -106,7 +107,7 @@ public class SwingUtilities3 { ...@@ -106,7 +107,7 @@ public class SwingUtilities3 {
* @return {@code true} if vsync painting is requested for {@code rootContainer} * @return {@code true} if vsync painting is requested for {@code rootContainer}
*/ */
public static boolean isVsyncRequested(Container rootContainer) { public static boolean isVsyncRequested(Container rootContainer) {
assert SwingUtilities.getRoot(rootContainer) == rootContainer; assert (rootContainer instanceof Applet) || (rootContainer instanceof Window);
return Boolean.TRUE == vsyncedMap.get(rootContainer); return Boolean.TRUE == vsyncedMap.get(rootContainer);
} }
......
/* /*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -399,7 +399,7 @@ class GTKPainter extends SynthPainter { ...@@ -399,7 +399,7 @@ class GTKPainter extends SynthPainter {
} }
String detail = "arrow"; String detail = "arrow";
if (name == "ScrollBar.button") { if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
if (arrowType == ArrowType.UP || arrowType == ArrowType.DOWN) { if (arrowType == ArrowType.UP || arrowType == ArrowType.DOWN) {
detail = "vscrollbar"; detail = "vscrollbar";
} else { } else {
...@@ -409,7 +409,7 @@ class GTKPainter extends SynthPainter { ...@@ -409,7 +409,7 @@ class GTKPainter extends SynthPainter {
name == "Spinner.previousButton") { name == "Spinner.previousButton") {
detail = "spinbutton"; detail = "spinbutton";
} else if (name != "ComboBox.arrowButton") { } else if (name != "ComboBox.arrowButton") {
assert false; assert false : "unexpected name: " + name;
} }
int gtkState = GTKLookAndFeel.synthStateToGTKState( int gtkState = GTKLookAndFeel.synthStateToGTKState(
...@@ -436,7 +436,7 @@ class GTKPainter extends SynthPainter { ...@@ -436,7 +436,7 @@ class GTKPainter extends SynthPainter {
String name = button.getName(); String name = button.getName();
String detail = "button"; String detail = "button";
int direction = SwingConstants.CENTER; int direction = SwingConstants.CENTER;
if (name == "ScrollBar.button") { if ((name == "ScrollBar.button") || (name == "TabbedPane.button")) {
Integer prop = (Integer) Integer prop = (Integer)
button.getClientProperty("__arrow_direction__"); button.getClientProperty("__arrow_direction__");
direction = (prop != null) ? direction = (prop != null) ?
...@@ -457,7 +457,7 @@ class GTKPainter extends SynthPainter { ...@@ -457,7 +457,7 @@ class GTKPainter extends SynthPainter {
} else if (name == "Spinner.nextButton") { } else if (name == "Spinner.nextButton") {
detail = "spinbutton_up"; detail = "spinbutton_up";
} else if (name != "ComboBox.arrowButton") { } else if (name != "ComboBox.arrowButton") {
assert false; assert false : "unexpected name: " + name;
} }
int state = context.getComponentState(); int state = context.getComponentState();
......
...@@ -150,11 +150,6 @@ class PangoFonts { ...@@ -150,11 +150,6 @@ class PangoFonts {
* case for it to be a problem the values would have to be different. * case for it to be a problem the values would have to be different.
* It also seems unlikely to arise except when a user explicitly * It also seems unlikely to arise except when a user explicitly
* deletes the X resource database entry. * deletes the X resource database entry.
* 3) Because of rounding errors sizes may differ very slightly
* between JDK and GTK. To fix that would at the very least require
* Swing to specify floating pt font sizes.
* Eg "10 pts" for GTK at 96 dpi to get the same size at Java 2D's
* 72 dpi you'd need to specify exactly 13.33.
* There also some other issues to be aware of for the future: * There also some other issues to be aware of for the future:
* GTK specifies the Xft.dpi value as server-wide which when used * GTK specifies the Xft.dpi value as server-wide which when used
* on systems with 2 distinct X screens with different physical DPI * on systems with 2 distinct X screens with different physical DPI
...@@ -197,11 +192,16 @@ class PangoFonts { ...@@ -197,11 +192,16 @@ class PangoFonts {
String fcFamilyLC = family.toLowerCase(); String fcFamilyLC = family.toLowerCase();
if (FontUtilities.mapFcName(fcFamilyLC) != null) { if (FontUtilities.mapFcName(fcFamilyLC) != null) {
/* family is a Fc/Pango logical font which we need to expand. */ /* family is a Fc/Pango logical font which we need to expand. */
return FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size); Font font = FontUtilities.getFontConfigFUIR(fcFamilyLC, style, size);
font = font.deriveFont(style, (float)dsize);
return new FontUIResource(font);
} else { } else {
/* It's a physical font which we will create with a fallback */ /* It's a physical font which we will create with a fallback */
Font font = new FontUIResource(family, style, size); Font font = new Font(family, style, size);
return FontUtilities.getCompositeFontUIResource(font); /* a roundabout way to set the font size in floating points */
font = font.deriveFont(style, (float)dsize);
FontUIResource fuir = new FontUIResource(font);
return FontUtilities.getCompositeFontUIResource(fuir);
} }
} }
......
/* /*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -40,8 +40,6 @@ import java.awt.Insets; ...@@ -40,8 +40,6 @@ import java.awt.Insets;
import java.awt.Point; import java.awt.Point;
import java.awt.Rectangle; import java.awt.Rectangle;
import java.io.Serializable;
/** /**
* Factory object that can vend Icons appropriate for the basic L & F. * Factory object that can vend Icons appropriate for the basic L & F.
* <p> * <p>
...@@ -99,7 +97,7 @@ public class MotifBorders { ...@@ -99,7 +97,7 @@ public class MotifBorders {
} }
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
if (((JComponent)c).hasFocus()) { if (c.hasFocus()) {
g.setColor(focus); g.setColor(focus);
g.drawRect(x, y, w-1, h-1); g.drawRect(x, y, w-1, h-1);
} else { } else {
...@@ -233,6 +231,9 @@ public class MotifBorders { ...@@ -233,6 +231,9 @@ public class MotifBorders {
} }
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (!(c instanceof JMenuBar)) {
return;
}
JMenuBar menuBar = (JMenuBar)c; JMenuBar menuBar = (JMenuBar)c;
if (menuBar.isBorderPainted() == true) { if (menuBar.isBorderPainted() == true) {
// this draws the MenuBar border // this draws the MenuBar border
...@@ -658,6 +659,9 @@ public class MotifBorders { ...@@ -658,6 +659,9 @@ public class MotifBorders {
* @param height the height of the painted border * @param height the height of the painted border
*/ */
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (!(c instanceof JPopupMenu)) {
return;
}
Font origFont = g.getFont(); Font origFont = g.getFont();
Color origColor = g.getColor(); Color origColor = g.getColor();
...@@ -701,6 +705,9 @@ public class MotifBorders { ...@@ -701,6 +705,9 @@ public class MotifBorders {
* @param insets the object to be reinitialized * @param insets the object to be reinitialized
*/ */
public Insets getBorderInsets(Component c, Insets insets) { public Insets getBorderInsets(Component c, Insets insets) {
if (!(c instanceof JPopupMenu)) {
return insets;
}
FontMetrics fm; FontMetrics fm;
int descent = 0; int descent = 0;
int ascent = 16; int ascent = 16;
......
/* /*
* Copyright (c) 1998, 2005, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -32,12 +32,8 @@ import javax.swing.plaf.basic.*; ...@@ -32,12 +32,8 @@ import javax.swing.plaf.basic.*;
import java.awt.Component; import java.awt.Component;
import java.awt.Insets; import java.awt.Insets;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Color; import java.awt.Color;
import java.awt.Graphics; import java.awt.Graphics;
import java.io.Serializable;
import static com.sun.java.swing.plaf.windows.TMSchema.*; import static com.sun.java.swing.plaf.windows.TMSchema.*;
import static com.sun.java.swing.plaf.windows.XPStyle.Skin; import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
...@@ -159,6 +155,9 @@ public class WindowsBorders { ...@@ -159,6 +155,9 @@ public class WindowsBorders {
public void paintBorder(Component c, Graphics g, int x, int y, public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) { int width, int height) {
if (!(c instanceof JToolBar)) {
return;
}
g.translate(x, y); g.translate(x, y);
XPStyle xp = XPStyle.getXP(); XPStyle xp = XPStyle.getXP();
...@@ -225,6 +224,9 @@ public class WindowsBorders { ...@@ -225,6 +224,9 @@ public class WindowsBorders {
public Insets getBorderInsets(Component c, Insets insets) { public Insets getBorderInsets(Component c, Insets insets) {
insets.set(1,1,1,1); insets.set(1,1,1,1);
if (!(c instanceof JToolBar)) {
return insets;
}
if (((JToolBar)c).isFloatable()) { if (((JToolBar)c).isFloatable()) {
int gripInset = (XPStyle.getXP() != null) ? 12 : 9; int gripInset = (XPStyle.getXP() != null) ? 12 : 9;
if (((JToolBar)c).getOrientation() == HORIZONTAL) { if (((JToolBar)c).getOrientation() == HORIZONTAL) {
......
...@@ -474,7 +474,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice ...@@ -474,7 +474,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
This is necessary for Receivers retrieved via MidiSystem.getReceiver() This is necessary for Receivers retrieved via MidiSystem.getReceiver()
(which opens the device implicitely). (which opens the device implicitely).
*/ */
protected abstract class AbstractReceiver implements Receiver { protected abstract class AbstractReceiver implements MidiDeviceReceiver {
private boolean open = true; private boolean open = true;
...@@ -508,6 +508,10 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice ...@@ -508,6 +508,10 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
AbstractMidiDevice.this.closeInternal(this); AbstractMidiDevice.this.closeInternal(this);
} }
public MidiDevice getMidiDevice() {
return AbstractMidiDevice.this;
}
protected boolean isOpen() { protected boolean isOpen() {
return open; return open;
} }
...@@ -529,7 +533,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice ...@@ -529,7 +533,7 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
* Also, it has some optimizations regarding sending to the Receivers, * Also, it has some optimizations regarding sending to the Receivers,
* for known Receivers, and managing itself in the TransmitterList. * for known Receivers, and managing itself in the TransmitterList.
*/ */
protected class BasicTransmitter implements Transmitter { protected class BasicTransmitter implements MidiDeviceTransmitter {
private Receiver receiver = null; private Receiver receiver = null;
TransmitterList tlist = null; TransmitterList tlist = null;
...@@ -568,6 +572,9 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice ...@@ -568,6 +572,9 @@ abstract class AbstractMidiDevice implements MidiDevice, ReferenceCountingDevice
} }
} }
public MidiDevice getMidiDevice() {
return AbstractMidiDevice.this;
}
} // class BasicTransmitter } // class BasicTransmitter
......
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -40,8 +40,6 @@ import javax.sound.sampled.AudioFormat.Encoding; ...@@ -40,8 +40,6 @@ import javax.sound.sampled.AudioFormat.Encoding;
*/ */
public abstract class AudioFloatConverter { public abstract class AudioFloatConverter {
public static final Encoding PCM_FLOAT = new Encoding("PCM_FLOAT");
/*************************************************************************** /***************************************************************************
* *
* LSB Filter, used filter least significant byte in samples arrays. * LSB Filter, used filter least significant byte in samples arrays.
...@@ -982,7 +980,7 @@ public abstract class AudioFloatConverter { ...@@ -982,7 +980,7 @@ public abstract class AudioFloatConverter {
format.getSampleSizeInBits() + 7) / 8) - 4); format.getSampleSizeInBits() + 7) / 8) - 4);
} }
} }
} else if (format.getEncoding().equals(PCM_FLOAT)) { } else if (format.getEncoding().equals(Encoding.PCM_FLOAT)) {
if (format.getSampleSizeInBits() == 32) { if (format.getSampleSizeInBits() == 32) {
if (format.isBigEndian()) if (format.isBigEndian())
conv = new AudioFloatConversion32B(); conv = new AudioFloatConversion32B();
......
/* /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -175,7 +175,6 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -175,7 +175,6 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
for (int c = 0; c < targetChannels; c++) { for (int c = 0; c < targetChannels; c++) {
for (int i = 0, ix = off + c; i < len2; i++, ix += cs) { for (int i = 0, ix = off + c; i < len2; i++, ix += cs) {
b[ix] = conversion_buffer[i]; b[ix] = conversion_buffer[i];
;
} }
} }
} else if (targetChannels == 1) { } else if (targetChannels == 1) {
...@@ -186,7 +185,6 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -186,7 +185,6 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
for (int c = 1; c < sourceChannels; c++) { for (int c = 1; c < sourceChannels; c++) {
for (int i = c, ix = off; i < len2; i += cs, ix++) { for (int i = c, ix = off; i < len2; i += cs, ix++) {
b[ix] += conversion_buffer[i]; b[ix] += conversion_buffer[i];
;
} }
} }
float vol = 1f / ((float) sourceChannels); float vol = 1f / ((float) sourceChannels);
...@@ -390,6 +388,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -390,6 +388,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
return -1; return -1;
if (len < 0) if (len < 0)
return 0; return 0;
int offlen = off + len;
int remain = len / nrofchannels; int remain = len / nrofchannels;
int destPos = 0; int destPos = 0;
int in_end = ibuffer_len; int in_end = ibuffer_len;
...@@ -423,7 +422,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -423,7 +422,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
for (int c = 0; c < nrofchannels; c++) { for (int c = 0; c < nrofchannels; c++) {
int ix = 0; int ix = 0;
float[] buff = cbuffer[c]; float[] buff = cbuffer[c];
for (int i = c; i < b.length; i += nrofchannels) { for (int i = c + off; i < offlen; i += nrofchannels) {
b[i] = buff[ix++]; b[i] = buff[ix++];
} }
} }
...@@ -447,7 +446,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -447,7 +446,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
} }
public long skip(long len) throws IOException { public long skip(long len) throws IOException {
if (len > 0) if (len < 0)
return 0; return 0;
if (skipbuffer == null) if (skipbuffer == null)
skipbuffer = new float[1024 * targetFormat.getFrameSize()]; skipbuffer = new float[1024 * targetFormat.getFrameSize()];
...@@ -470,7 +469,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -470,7 +469,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
} }
private Encoding[] formats = { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED, private Encoding[] formats = { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
AudioFloatConverter.PCM_FLOAT }; Encoding.PCM_FLOAT };
public AudioInputStream getAudioInputStream(Encoding targetEncoding, public AudioInputStream getAudioInputStream(Encoding targetEncoding,
AudioInputStream sourceStream) { AudioInputStream sourceStream) {
...@@ -482,7 +481,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -482,7 +481,7 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
float samplerate = format.getSampleRate(); float samplerate = format.getSampleRate();
int bits = format.getSampleSizeInBits(); int bits = format.getSampleSizeInBits();
boolean bigendian = format.isBigEndian(); boolean bigendian = format.isBigEndian();
if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT)) if (targetEncoding.equals(Encoding.PCM_FLOAT))
bits = 32; bits = 32;
AudioFormat targetFormat = new AudioFormat(encoding, samplerate, bits, AudioFormat targetFormat = new AudioFormat(encoding, samplerate, bits,
channels, channels * bits / 8, samplerate, bigendian); channels, channels * bits / 8, samplerate, bigendian);
...@@ -521,19 +520,19 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -521,19 +520,19 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
public Encoding[] getSourceEncodings() { public Encoding[] getSourceEncodings() {
return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED, return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
AudioFloatConverter.PCM_FLOAT }; Encoding.PCM_FLOAT };
} }
public Encoding[] getTargetEncodings() { public Encoding[] getTargetEncodings() {
return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED, return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
AudioFloatConverter.PCM_FLOAT }; Encoding.PCM_FLOAT };
} }
public Encoding[] getTargetEncodings(AudioFormat sourceFormat) { public Encoding[] getTargetEncodings(AudioFormat sourceFormat) {
if (AudioFloatConverter.getConverter(sourceFormat) == null) if (AudioFloatConverter.getConverter(sourceFormat) == null)
return new Encoding[0]; return new Encoding[0];
return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED, return new Encoding[] { Encoding.PCM_SIGNED, Encoding.PCM_UNSIGNED,
AudioFloatConverter.PCM_FLOAT }; Encoding.PCM_FLOAT };
} }
public AudioFormat[] getTargetFormats(Encoding targetEncoding, public AudioFormat[] getTargetFormats(Encoding targetEncoding,
...@@ -572,17 +571,17 @@ public class AudioFloatFormatConverter extends FormatConversionProvider { ...@@ -572,17 +571,17 @@ public class AudioFloatFormatConverter extends FormatConversionProvider {
} }
} }
if (targetEncoding.equals(AudioFloatConverter.PCM_FLOAT)) { if (targetEncoding.equals(Encoding.PCM_FLOAT)) {
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
AudioSystem.NOT_SPECIFIED, false)); AudioSystem.NOT_SPECIFIED, false));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
AudioSystem.NOT_SPECIFIED, true)); AudioSystem.NOT_SPECIFIED, true));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
AudioSystem.NOT_SPECIFIED, false)); AudioSystem.NOT_SPECIFIED, false));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
AudioSystem.NOT_SPECIFIED, true)); AudioSystem.NOT_SPECIFIED, true));
} }
......
...@@ -42,12 +42,15 @@ public class AudioSynthesizerPropertyInfo { ...@@ -42,12 +42,15 @@ public class AudioSynthesizerPropertyInfo {
*/ */
public AudioSynthesizerPropertyInfo(String name, Object value) { public AudioSynthesizerPropertyInfo(String name, Object value) {
this.name = name; this.name = name;
this.value = value;
if (value instanceof Class) if (value instanceof Class)
valueClass = (Class)value; valueClass = (Class)value;
else if (value != null) else
{
this.value = value;
if (value != null)
valueClass = value.getClass(); valueClass = value.getClass();
} }
}
/** /**
* The name of the property. * The name of the property.
*/ */
......
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -781,7 +781,7 @@ public class DLSSoundbank implements Soundbank { ...@@ -781,7 +781,7 @@ public class DLSSoundbank implements Soundbank {
} }
if (sampleformat == 3) { if (sampleformat == 3) {
audioformat = new AudioFormat( audioformat = new AudioFormat(
AudioFloatConverter.PCM_FLOAT, samplerate, bits, Encoding.PCM_FLOAT, samplerate, bits,
channels, framesize, samplerate, false); channels, framesize, samplerate, false);
} }
...@@ -965,7 +965,7 @@ public class DLSSoundbank implements Soundbank { ...@@ -965,7 +965,7 @@ public class DLSSoundbank implements Soundbank {
sampleformat = 1; sampleformat = 1;
else if (audioformat.getEncoding().equals(Encoding.PCM_SIGNED)) else if (audioformat.getEncoding().equals(Encoding.PCM_SIGNED))
sampleformat = 1; sampleformat = 1;
else if (audioformat.getEncoding().equals(AudioFloatConverter.PCM_FLOAT)) else if (audioformat.getEncoding().equals(Encoding.PCM_FLOAT))
sampleformat = 3; sampleformat = 3;
fmt_chunk.writeUnsignedShort(sampleformat); fmt_chunk.writeUnsignedShort(sampleformat);
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import javax.sound.midi.*;
/**
* Helper class which allows to convert {@code Receiver}
* to {@code MidiDeviceReceiver}.
*
* @author Alex Menkov
*/
public class MidiDeviceReceiverEnvelope implements MidiDeviceReceiver {
private final MidiDevice device;
private final Receiver receiver;
/**
* Creates a new {@code MidiDeviceReceiverEnvelope} object which
* envelops the specified {@code Receiver}
* and is owned by the specified {@code MidiDevice}.
*
* @param device the owner {@code MidiDevice}
* @param receiver the {@code Receiver} to be enveloped
*/
public MidiDeviceReceiverEnvelope(MidiDevice device, Receiver receiver) {
if (device == null || receiver == null) {
throw new NullPointerException();
}
this.device = device;
this.receiver = receiver;
}
// Receiver implementation
public void close() {
receiver.close();
}
public void send(MidiMessage message, long timeStamp) {
receiver.send(message, timeStamp);
}
// MidiDeviceReceiver implementation
public MidiDevice getMidiDevice() {
return device;
}
/**
* Obtains the receiver enveloped
* by this {@code MidiDeviceReceiverEnvelope} object.
*
* @return the enveloped receiver
*/
public Receiver getReceiver() {
return receiver;
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import javax.sound.midi.*;
/**
* Helper class which allows to convert {@code Transmitter}
* to {@code MidiDeviceTransmitter}.
*
* @author Alex Menkov
*/
public class MidiDeviceTransmitterEnvelope implements MidiDeviceTransmitter {
private final MidiDevice device;
private final Transmitter transmitter;
/**
* Creates a new {@code MidiDeviceTransmitterEnvelope} object which
* envelops the specified {@code Transmitter}
* and is owned by the specified {@code MidiDevice}.
*
* @param device the owner {@code MidiDevice}
* @param transmitter the {@code Transmitter} to be enveloped
*/
public MidiDeviceTransmitterEnvelope(MidiDevice device, Transmitter transmitter) {
if (device == null || transmitter == null) {
throw new NullPointerException();
}
this.device = device;
this.transmitter = transmitter;
}
// Transmitter implementation
public void setReceiver(Receiver receiver) {
transmitter.setReceiver(receiver);
}
public Receiver getReceiver() {
return transmitter.getReceiver();
}
public void close() {
transmitter.close();
}
// MidiDeviceReceiver implementation
public MidiDevice getMidiDevice() {
return device;
}
/**
* Obtains the transmitter enveloped
* by this {@code MidiDeviceTransmitterEnvelope} object.
*
* @return the enveloped transmitter
*/
public Transmitter getTransmitter() {
return transmitter;
}
}
...@@ -205,7 +205,8 @@ public class ModelByteBufferWavetable implements ModelWavetable { ...@@ -205,7 +205,8 @@ public class ModelByteBufferWavetable implements ModelWavetable {
} }
if (buffer.array() == null) { if (buffer.array() == null) {
return AudioFloatInputStream.getInputStream(new AudioInputStream( return AudioFloatInputStream.getInputStream(new AudioInputStream(
buffer.getInputStream(), format, buffer.capacity())); buffer.getInputStream(), format,
buffer.capacity() / format.getFrameSize()));
} }
if (buffer8 != null) { if (buffer8 != null) {
if (format.getEncoding().equals(Encoding.PCM_SIGNED) if (format.getEncoding().equals(Encoding.PCM_SIGNED)
......
...@@ -56,7 +56,7 @@ public abstract class ModelInstrument extends Instrument { ...@@ -56,7 +56,7 @@ public abstract class ModelInstrument extends Instrument {
public ModelDirector getDirector(ModelPerformer[] performers, public ModelDirector getDirector(ModelPerformer[] performers,
MidiChannel channel, ModelDirectedPlayer player) { MidiChannel channel, ModelDirectedPlayer player) {
return new ModelStandardDirector(performers, player); return new ModelStandardIndexedDirector(performers, player);
} }
public ModelPerformer[] getPerformers() { public ModelPerformer[] getPerformers() {
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
/**
* A standard indexed director who chooses performers
* by there keyfrom,keyto,velfrom,velto properties.
*
* @author Karl Helgason
*/
public class ModelStandardIndexedDirector implements ModelDirector {
ModelPerformer[] performers;
ModelDirectedPlayer player;
boolean noteOnUsed = false;
boolean noteOffUsed = false;
// Variables needed for index
byte[][] trantables;
int[] counters;
int[][] mat;
public ModelStandardIndexedDirector(ModelPerformer[] performers,
ModelDirectedPlayer player) {
this.performers = performers;
this.player = player;
for (int i = 0; i < performers.length; i++) {
ModelPerformer p = performers[i];
if (p.isReleaseTriggered()) {
noteOffUsed = true;
} else {
noteOnUsed = true;
}
}
buildindex();
}
private int[] lookupIndex(int x, int y) {
if ((x >= 0) && (x < 128) && (y >= 0) && (y < 128)) {
int xt = trantables[0][x];
int yt = trantables[1][y];
if (xt != -1 && yt != -1) {
return mat[xt + yt * counters[0]];
}
}
return null;
}
private int restrict(int value) {
if(value < 0) return 0;
if(value > 127) return 127;
return value;
}
private void buildindex() {
trantables = new byte[2][129];
counters = new int[trantables.length];
for (ModelPerformer performer : performers) {
int keyFrom = performer.getKeyFrom();
int keyTo = performer.getKeyTo();
int velFrom = performer.getVelFrom();
int velTo = performer.getVelTo();
if (keyFrom > keyTo) continue;
if (velFrom > velTo) continue;
keyFrom = restrict(keyFrom);
keyTo = restrict(keyTo);
velFrom = restrict(velFrom);
velTo = restrict(velTo);
trantables[0][keyFrom] = 1;
trantables[0][keyTo + 1] = 1;
trantables[1][velFrom] = 1;
trantables[1][velTo + 1] = 1;
}
for (int d = 0; d < trantables.length; d++) {
byte[] trantable = trantables[d];
int transize = trantable.length;
for (int i = transize - 1; i >= 0; i--) {
if (trantable[i] == 1) {
trantable[i] = -1;
break;
}
trantable[i] = -1;
}
int counter = -1;
for (int i = 0; i < transize; i++) {
if (trantable[i] != 0) {
counter++;
if (trantable[i] == -1)
break;
}
trantable[i] = (byte) counter;
}
counters[d] = counter;
}
mat = new int[counters[0] * counters[1]][];
int ix = 0;
for (ModelPerformer performer : performers) {
int keyFrom = performer.getKeyFrom();
int keyTo = performer.getKeyTo();
int velFrom = performer.getVelFrom();
int velTo = performer.getVelTo();
if (keyFrom > keyTo) continue;
if (velFrom > velTo) continue;
keyFrom = restrict(keyFrom);
keyTo = restrict(keyTo);
velFrom = restrict(velFrom);
velTo = restrict(velTo);
int x_from = trantables[0][keyFrom];
int x_to = trantables[0][keyTo + 1];
int y_from = trantables[1][velFrom];
int y_to = trantables[1][velTo + 1];
if (x_to == -1)
x_to = counters[0];
if (y_to == -1)
y_to = counters[1];
for (int y = y_from; y < y_to; y++) {
int i = x_from + y * counters[0];
for (int x = x_from; x < x_to; x++) {
int[] mprev = mat[i];
if (mprev == null) {
mat[i] = new int[] { ix };
} else {
int[] mnew = new int[mprev.length + 1];
mnew[mnew.length - 1] = ix;
for (int k = 0; k < mprev.length; k++)
mnew[k] = mprev[k];
mat[i] = mnew;
}
i++;
}
}
ix++;
}
}
public void close() {
}
public void noteOff(int noteNumber, int velocity) {
if (!noteOffUsed)
return;
int[] plist = lookupIndex(noteNumber, velocity);
if(plist == null) return;
for (int i : plist) {
ModelPerformer p = performers[i];
if (p.isReleaseTriggered()) {
player.play(i, null);
}
}
}
public void noteOn(int noteNumber, int velocity) {
if (!noteOnUsed)
return;
int[] plist = lookupIndex(noteNumber, velocity);
if(plist == null) return;
for (int i : plist) {
ModelPerformer p = performers[i];
if (!p.isReleaseTriggered()) {
player.play(i, null);
}
}
}
}
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -116,7 +116,7 @@ public class SoftChannel implements MidiChannel, ModelDirectedPlayer { ...@@ -116,7 +116,7 @@ public class SoftChannel implements MidiChannel, ModelDirectedPlayer {
protected int tuning_program = 0; protected int tuning_program = 0;
protected SoftInstrument current_instrument = null; protected SoftInstrument current_instrument = null;
protected ModelChannelMixer current_mixer = null; protected ModelChannelMixer current_mixer = null;
private ModelDirector current_director = null; protected ModelDirector current_director = null;
// Controller Destination Settings // Controller Destination Settings
protected int cds_control_number = -1; protected int cds_control_number = -1;
...@@ -1264,15 +1264,18 @@ public class SoftChannel implements MidiChannel, ModelDirectedPlayer { ...@@ -1264,15 +1264,18 @@ public class SoftChannel implements MidiChannel, ModelDirectedPlayer {
} }
public void programChange(int bank, int program) { public void programChange(int bank, int program) {
bank = restrict7Bit(bank); bank = restrict14Bit(bank);
program = restrict7Bit(program); program = restrict7Bit(program);
synchronized (control_mutex) { synchronized (control_mutex) {
mainmixer.activity(); mainmixer.activity();
if(this.bank != bank || this.program != program)
{
this.bank = bank; this.bank = bank;
this.program = program; this.program = program;
current_instrument = null; current_instrument = null;
} }
} }
}
public int getProgram() { public int getProgram() {
synchronized (control_mutex) { synchronized (control_mutex) {
......
/* /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -118,16 +118,16 @@ public class SoftMixingMixer implements Mixer { ...@@ -118,16 +118,16 @@ public class SoftMixingMixer implements Mixer {
AudioSystem.NOT_SPECIFIED, bits, channels, channels AudioSystem.NOT_SPECIFIED, bits, channels, channels
* bits / 8, AudioSystem.NOT_SPECIFIED, true)); * bits / 8, AudioSystem.NOT_SPECIFIED, true));
} }
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
AudioSystem.NOT_SPECIFIED, false)); AudioSystem.NOT_SPECIFIED, false));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4, AudioSystem.NOT_SPECIFIED, 32, channels, channels * 4,
AudioSystem.NOT_SPECIFIED, true)); AudioSystem.NOT_SPECIFIED, true));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
AudioSystem.NOT_SPECIFIED, false)); AudioSystem.NOT_SPECIFIED, false));
formats.add(new AudioFormat(AudioFloatConverter.PCM_FLOAT, formats.add(new AudioFormat(Encoding.PCM_FLOAT,
AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8, AudioSystem.NOT_SPECIFIED, 64, channels, channels * 8,
AudioSystem.NOT_SPECIFIED, true)); AudioSystem.NOT_SPECIFIED, true));
} }
......
...@@ -27,6 +27,7 @@ package com.sun.media.sound; ...@@ -27,6 +27,7 @@ package com.sun.media.sound;
import java.util.TreeMap; import java.util.TreeMap;
import javax.sound.midi.MidiDevice; import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiDeviceReceiver;
import javax.sound.midi.MidiMessage; import javax.sound.midi.MidiMessage;
import javax.sound.midi.ShortMessage; import javax.sound.midi.ShortMessage;
......
/* /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,16 +25,25 @@ ...@@ -25,16 +25,25 @@
package com.sun.media.sound; package com.sun.media.sound;
import java.io.BufferedInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.security.AccessControlException; import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import javax.sound.midi.Instrument; import javax.sound.midi.Instrument;
import javax.sound.midi.MidiChannel; import javax.sound.midi.MidiChannel;
...@@ -182,6 +191,7 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -182,6 +191,7 @@ public class SoftSynthesizer implements AudioSynthesizer,
// 1: DLS Voice Allocation // 1: DLS Voice Allocation
protected int voice_allocation_mode = 0; protected int voice_allocation_mode = 0;
protected boolean load_default_soundbank = false;
protected boolean reverb_light = true; protected boolean reverb_light = true;
protected boolean reverb_on = true; protected boolean reverb_on = true;
protected boolean chorus_on = true; protected boolean chorus_on = true;
...@@ -226,8 +236,6 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -226,8 +236,6 @@ public class SoftSynthesizer implements AudioSynthesizer,
= new HashMap<String, SoftTuning>(); = new HashMap<String, SoftTuning>();
private Map<String, SoftInstrument> inslist private Map<String, SoftInstrument> inslist
= new HashMap<String, SoftInstrument>(); = new HashMap<String, SoftInstrument>();
private Map<String, ModelInstrument> availlist
= new HashMap<String, ModelInstrument>();
private Map<String, ModelInstrument> loadedlist private Map<String, ModelInstrument> loadedlist
= new HashMap<String, ModelInstrument>(); = new HashMap<String, ModelInstrument>();
...@@ -275,10 +283,12 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -275,10 +283,12 @@ public class SoftSynthesizer implements AudioSynthesizer,
synchronized (control_mutex) { synchronized (control_mutex) {
if (channels != null) if (channels != null)
for (SoftChannel c : channels) for (SoftChannel c : channels)
{
c.current_instrument = null; c.current_instrument = null;
c.current_director = null;
}
for (Instrument instrument : instruments) { for (Instrument instrument : instruments) {
String pat = patchToString(instrument.getPatch()); String pat = patchToString(instrument.getPatch());
availlist.remove(pat);
SoftInstrument softins SoftInstrument softins
= new SoftInstrument((ModelInstrument) instrument); = new SoftInstrument((ModelInstrument) instrument);
inslist.put(pat, softins); inslist.put(pat, softins);
...@@ -341,6 +351,7 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -341,6 +351,7 @@ public class SoftSynthesizer implements AudioSynthesizer,
number_of_midi_channels = (Integer)items[10].value; number_of_midi_channels = (Integer)items[10].value;
jitter_correction = (Boolean)items[11].value; jitter_correction = (Boolean)items[11].value;
reverb_light = (Boolean)items[12].value; reverb_light = (Boolean)items[12].value;
load_default_soundbank = (Boolean)items[13].value;
} }
private String patchToString(Patch patch) { private String patchToString(Patch patch) {
...@@ -578,7 +589,9 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -578,7 +589,9 @@ public class SoftSynthesizer implements AudioSynthesizer,
c.current_instrument = null; c.current_instrument = null;
inslist.remove(pat); inslist.remove(pat);
loadedlist.remove(pat); loadedlist.remove(pat);
availlist.remove(pat); for (int i = 0; i < channels.length; i++) {
channels[i].allSoundOff();
}
} }
} }
...@@ -600,7 +613,7 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -600,7 +613,7 @@ public class SoftSynthesizer implements AudioSynthesizer,
return false; return false;
synchronized (control_mutex) { synchronized (control_mutex) {
if (!loadedlist.containsValue(to) && !availlist.containsValue(to)) if (!loadedlist.containsValue(to))
throw new IllegalArgumentException("Instrument to is not loaded."); throw new IllegalArgumentException("Instrument to is not loaded.");
unloadInstrument(from); unloadInstrument(from);
ModelMappedInstrument mfrom = new ModelMappedInstrument( ModelMappedInstrument mfrom = new ModelMappedInstrument(
...@@ -609,13 +622,19 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -609,13 +622,19 @@ public class SoftSynthesizer implements AudioSynthesizer,
} }
} }
public synchronized Soundbank getDefaultSoundbank() { public Soundbank getDefaultSoundbank() {
if (defaultSoundBank == null) { synchronized (SoftSynthesizer.class) {
try { if (defaultSoundBank != null)
File javahome = new File(System.getProperties().getProperty( return defaultSoundBank;
"java.home"));
File libaudio = new File(new File(javahome, "lib"), "audio"); List<PrivilegedAction<InputStream>> actions =
new ArrayList<PrivilegedAction<InputStream>>();
actions.add(new PrivilegedAction<InputStream>() {
public InputStream run() {
File javahome = new File(System.getProperties()
.getProperty("java.home"));
File libaudio = new File(new File(javahome, "lib"), "audio");
if (libaudio.exists()) { if (libaudio.exists()) {
File foundfile = null; File foundfile = null;
File[] files = libaudio.listFiles(); File[] files = libaudio.listFiles();
...@@ -624,10 +643,11 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -624,10 +643,11 @@ public class SoftSynthesizer implements AudioSynthesizer,
File file = files[i]; File file = files[i];
if (file.isFile()) { if (file.isFile()) {
String lname = file.getName().toLowerCase(); String lname = file.getName().toLowerCase();
if (lname.endsWith(".sf2") || if (lname.endsWith(".sf2")
lname.endsWith(".dls")) { || lname.endsWith(".dls")) {
if (foundfile == null || (file.length() > if (foundfile == null
foundfile.length())) { || (file.length() > foundfile
.length())) {
foundfile = file; foundfile = file;
} }
} }
...@@ -636,92 +656,122 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -636,92 +656,122 @@ public class SoftSynthesizer implements AudioSynthesizer,
} }
if (foundfile != null) { if (foundfile != null) {
try { try {
Soundbank sbk = MidiSystem.getSoundbank(foundfile); return new FileInputStream(foundfile);
defaultSoundBank = sbk; } catch (IOException e) {
return defaultSoundBank;
} catch (Exception e) {
//e.printStackTrace();
} }
} }
} }
return null;
}
});
actions.add(new PrivilegedAction<InputStream>() {
public InputStream run() {
if (System.getProperties().getProperty("os.name") if (System.getProperties().getProperty("os.name")
.startsWith("Windows")) { .startsWith("Windows")) {
File gm_dls = new File(System.getenv("SystemRoot") File gm_dls = new File(System.getenv("SystemRoot")
+ "\\system32\\drivers\\gm.dls"); + "\\system32\\drivers\\gm.dls");
if (gm_dls.exists()) { if (gm_dls.exists()) {
try { try {
Soundbank sbk = MidiSystem.getSoundbank(gm_dls); return new FileInputStream(gm_dls);
defaultSoundBank = sbk; } catch (IOException e) {
return defaultSoundBank;
} catch (Exception e) {
//e.printStackTrace();
} }
} }
} }
} catch (AccessControlException e) { return null;
} catch (Exception e) {
//e.printStackTrace();
} }
});
File userhome = null; actions.add(new PrivilegedAction<InputStream>() {
File emg_soundbank_file = null; public InputStream run() {
/* /*
* Try to load saved generated soundbank * Try to load saved generated soundbank
*/ */
try { File userhome = new File(System.getProperty("user.home"),
userhome = new File(System.getProperty("user.home"),
".gervill"); ".gervill");
emg_soundbank_file = new File(userhome, "soundbank-emg.sf2"); File emg_soundbank_file = new File(userhome,
Soundbank sbk = MidiSystem.getSoundbank(emg_soundbank_file); "soundbank-emg.sf2");
if (emg_soundbank_file.exists()) {
try {
return new FileInputStream(emg_soundbank_file);
} catch (IOException e) {
}
}
return null;
}
});
for (PrivilegedAction<InputStream> action : actions) {
try {
InputStream is = AccessController.doPrivileged(action);
if(is == null) continue;
Soundbank sbk;
try {
sbk = MidiSystem.getSoundbank(new BufferedInputStream(is));
} finally {
is.close();
}
if (sbk != null) {
defaultSoundBank = sbk; defaultSoundBank = sbk;
return defaultSoundBank; return defaultSoundBank;
} catch (AccessControlException e) { }
} catch (Exception e) { } catch (Exception e) {
//e.printStackTrace(); }
} }
try { try {
/* /*
* Generate emergency soundbank * Generate emergency soundbank
*/ */
defaultSoundBank = EmergencySoundbank.createSoundbank(); defaultSoundBank = EmergencySoundbank.createSoundbank();
} catch (Exception e) {
}
if (defaultSoundBank != null) {
/* /*
* Save generated soundbank to disk for faster future use. * Save generated soundbank to disk for faster future use.
*/ */
if(defaultSoundBank != null) OutputStream out = AccessController
{ .doPrivileged(new PrivilegedAction<OutputStream>() {
if(!userhome.exists()) userhome.mkdirs(); public OutputStream run() {
if(!emg_soundbank_file.exists()) try {
((SF2Soundbank)defaultSoundBank).save(emg_soundbank_file); File userhome = new File(System
.getProperty("user.home"),
".gervill");
if (!userhome.exists())
userhome.mkdirs();
File emg_soundbank_file = new File(
userhome, "soundbank-emg.sf2");
if (emg_soundbank_file.exists())
return null;
return new FileOutputStream(
emg_soundbank_file);
} catch (IOException e) {
} catch (SecurityException e) {
}
return null;
}
});
if (out != null) {
try {
((SF2Soundbank) defaultSoundBank).save(out);
out.close();
} catch (IOException e) {
}
} }
} catch (Exception e) {
//e.printStackTrace();
} }
} }
return defaultSoundBank; return defaultSoundBank;
} }
public Instrument[] getAvailableInstruments() { public Instrument[] getAvailableInstruments() {
if (!isOpen()) {
Soundbank defsbk = getDefaultSoundbank(); Soundbank defsbk = getDefaultSoundbank();
if (defsbk == null) if (defsbk == null)
return new Instrument[0]; return new Instrument[0];
return defsbk.getInstruments(); Instrument[] inslist_array = defsbk.getInstruments();
}
synchronized (control_mutex) {
ModelInstrument[] inslist_array =
new ModelInstrument[availlist.values().size()];
availlist.values().toArray(inslist_array);
Arrays.sort(inslist_array, new ModelInstrumentComparator()); Arrays.sort(inslist_array, new ModelInstrumentComparator());
return inslist_array; return inslist_array;
} }
}
public Instrument[] getLoadedInstruments() { public Instrument[] getLoadedInstruments() {
if (!isOpen()) if (!isOpen())
...@@ -794,6 +844,31 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -794,6 +844,31 @@ public class SoftSynthesizer implements AudioSynthesizer,
return info; return info;
} }
private Properties getStoredProperties() {
return AccessController
.doPrivileged(new PrivilegedAction<Properties>() {
public Properties run() {
Properties p = new Properties();
String notePath = "/com/sun/media/sound/softsynthesizer";
try {
Preferences prefroot = Preferences.userRoot();
if (prefroot.nodeExists(notePath)) {
Preferences prefs = prefroot.node(notePath);
String[] prefs_keys = prefs.keys();
for (String prefs_key : prefs_keys) {
String val = prefs.get(prefs_key, null);
if (val != null)
p.setProperty(prefs_key, val);
}
}
} catch (BackingStoreException e) {
} catch (SecurityException e) {
}
return p;
}
});
}
public AudioSynthesizerPropertyInfo[] getPropertyInfo(Map<String, Object> info) { public AudioSynthesizerPropertyInfo[] getPropertyInfo(Map<String, Object> info) {
List<AudioSynthesizerPropertyInfo> list = List<AudioSynthesizerPropertyInfo> list =
new ArrayList<AudioSynthesizerPropertyInfo>(); new ArrayList<AudioSynthesizerPropertyInfo>();
...@@ -861,16 +936,91 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -861,16 +936,91 @@ public class SoftSynthesizer implements AudioSynthesizer,
item.description = "Turn light reverb mode on or off"; item.description = "Turn light reverb mode on or off";
list.add(item); list.add(item);
item = new AudioSynthesizerPropertyInfo("load default soundbank", o?load_default_soundbank:true);
item.description = "Enabled/disable loading default soundbank";
list.add(item);
AudioSynthesizerPropertyInfo[] items; AudioSynthesizerPropertyInfo[] items;
items = list.toArray(new AudioSynthesizerPropertyInfo[list.size()]); items = list.toArray(new AudioSynthesizerPropertyInfo[list.size()]);
if (info != null) Properties storedProperties = getStoredProperties();
for (AudioSynthesizerPropertyInfo item2: items) {
Object v = info.get(item2.name); for (AudioSynthesizerPropertyInfo item2 : items) {
Object v = (info == null) ? null : info.get(item2.name);
v = (v != null) ? v : storedProperties.getProperty(item2.name);
if (v != null) {
Class c = (item2.valueClass); Class c = (item2.valueClass);
if (v != null)
if (c.isInstance(v)) if (c.isInstance(v))
item2.value = v; item2.value = v;
else if (v instanceof String) {
String s = (String) v;
if (c == Boolean.class) {
if (s.equalsIgnoreCase("true"))
item2.value = Boolean.TRUE;
if (s.equalsIgnoreCase("false"))
item2.value = Boolean.FALSE;
} else if (c == AudioFormat.class) {
int channels = 2;
boolean signed = true;
boolean bigendian = false;
int bits = 16;
float sampleRate = 44100f;
try {
StringTokenizer st = new StringTokenizer(s, ", ");
String prevToken = "";
while (st.hasMoreTokens()) {
String token = st.nextToken().toLowerCase();
if (token.equals("mono"))
channels = 1;
if (token.startsWith("channel"))
channels = Integer.parseInt(prevToken);
if (token.contains("unsigned"))
signed = false;
if (token.equals("big-endian"))
bigendian = true;
if (token.equals("bit"))
bits = Integer.parseInt(prevToken);
if (token.equals("hz"))
sampleRate = Float.parseFloat(prevToken);
prevToken = token;
}
item2.value = new AudioFormat(sampleRate, bits,
channels, signed, bigendian);
} catch (NumberFormatException e) {
}
} else
try {
if (c == Byte.class)
item2.value = Byte.valueOf(s);
else if (c == Short.class)
item2.value = Short.valueOf(s);
else if (c == Integer.class)
item2.value = Integer.valueOf(s);
else if (c == Long.class)
item2.value = Long.valueOf(s);
else if (c == Float.class)
item2.value = Float.valueOf(s);
else if (c == Double.class)
item2.value = Double.valueOf(s);
} catch (NumberFormatException e) {
}
} else if (v instanceof Number) {
Number n = (Number) v;
if (c == Byte.class)
item2.value = Byte.valueOf(n.byteValue());
if (c == Short.class)
item2.value = Short.valueOf(n.shortValue());
if (c == Integer.class)
item2.value = Integer.valueOf(n.intValue());
if (c == Long.class)
item2.value = Long.valueOf(n.longValue());
if (c == Float.class)
item2.value = Float.valueOf(n.floatValue());
if (c == Double.class)
item2.value = Double.valueOf(n.doubleValue());
}
}
} }
return items; return items;
...@@ -1007,11 +1157,12 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -1007,11 +1157,12 @@ public class SoftSynthesizer implements AudioSynthesizer,
if (targetFormat != null) if (targetFormat != null)
setFormat(targetFormat); setFormat(targetFormat);
if (load_default_soundbank)
{
Soundbank defbank = getDefaultSoundbank(); Soundbank defbank = getDefaultSoundbank();
if (defbank != null) { if (defbank != null) {
loadAllInstruments(defbank); loadAllInstruments(defbank);
availlist.putAll(loadedlist); }
loadedlist.clear();
} }
voices = new SoftVoice[maxpoly]; voices = new SoftVoice[maxpoly];
...@@ -1117,7 +1268,6 @@ public class SoftSynthesizer implements AudioSynthesizer, ...@@ -1117,7 +1268,6 @@ public class SoftSynthesizer implements AudioSynthesizer,
} }
inslist.clear(); inslist.clear();
availlist.clear();
loadedlist.clear(); loadedlist.clear();
tunings.clear(); tunings.clear();
......
...@@ -279,9 +279,12 @@ public class SoftVoice extends VoiceStatus { ...@@ -279,9 +279,12 @@ public class SoftVoice extends VoiceStatus {
} }
protected void updateTuning(SoftTuning newtuning) { protected void updateTuning(SoftTuning newtuning) {
tuning = newtuning;
tunedKey = tuning.getTuning(note) / 100.0; tunedKey = tuning.getTuning(note) / 100.0;
if (!portamento) { if (!portamento) {
co_noteon_keynumber[0] = tunedKey * (1.0 / 128.0); co_noteon_keynumber[0] = tunedKey * (1.0 / 128.0);
if(performer == null)
return;
int[] c = performer.midi_connections[4]; int[] c = performer.midi_connections[4];
if (c == null) if (c == null)
return; return;
...@@ -433,6 +436,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -433,6 +436,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void setPolyPressure(int pressure) { protected void setPolyPressure(int pressure) {
if(performer == null)
return;
int[] c = performer.midi_connections[2]; int[] c = performer.midi_connections[2];
if (c == null) if (c == null)
return; return;
...@@ -441,6 +446,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -441,6 +446,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void setChannelPressure(int pressure) { protected void setChannelPressure(int pressure) {
if(performer == null)
return;
int[] c = performer.midi_connections[1]; int[] c = performer.midi_connections[1];
if (c == null) if (c == null)
return; return;
...@@ -449,6 +456,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -449,6 +456,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void controlChange(int controller, int value) { protected void controlChange(int controller, int value) {
if(performer == null)
return;
int[] c = performer.midi_ctrl_connections[controller]; int[] c = performer.midi_ctrl_connections[controller];
if (c == null) if (c == null)
return; return;
...@@ -457,6 +466,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -457,6 +466,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void nrpnChange(int controller, int value) { protected void nrpnChange(int controller, int value) {
if(performer == null)
return;
int[] c = performer.midi_nrpn_connections.get(controller); int[] c = performer.midi_nrpn_connections.get(controller);
if (c == null) if (c == null)
return; return;
...@@ -465,6 +476,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -465,6 +476,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void rpnChange(int controller, int value) { protected void rpnChange(int controller, int value) {
if(performer == null)
return;
int[] c = performer.midi_rpn_connections.get(controller); int[] c = performer.midi_rpn_connections.get(controller);
if (c == null) if (c == null)
return; return;
...@@ -473,6 +486,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -473,6 +486,8 @@ public class SoftVoice extends VoiceStatus {
} }
protected void setPitchBend(int bend) { protected void setPitchBend(int bend) {
if(performer == null)
return;
int[] c = performer.midi_connections[0]; int[] c = performer.midi_connections[0];
if (c == null) if (c == null)
return; return;
...@@ -499,6 +514,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -499,6 +514,8 @@ public class SoftVoice extends VoiceStatus {
co_noteon_on[0] = -1; co_noteon_on[0] = -1;
if(performer == null)
return;
int[] c = performer.midi_connections[3]; int[] c = performer.midi_connections[3];
if (c == null) if (c == null)
return; return;
...@@ -527,6 +544,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -527,6 +544,8 @@ public class SoftVoice extends VoiceStatus {
co_noteon_on[0] = 0; co_noteon_on[0] = 0;
if(performer == null)
return;
int[] c = performer.midi_connections[3]; int[] c = performer.midi_connections[3];
if (c == null) if (c == null)
return; return;
...@@ -543,6 +562,8 @@ public class SoftVoice extends VoiceStatus { ...@@ -543,6 +562,8 @@ public class SoftVoice extends VoiceStatus {
sustain = true; sustain = true;
co_noteon_on[0] = 1; co_noteon_on[0] = 1;
if(performer == null)
return;
int[] c = performer.midi_connections[3]; int[] c = performer.midi_connections[3];
if (c == null) if (c == null)
return; return;
...@@ -555,6 +576,11 @@ public class SoftVoice extends VoiceStatus { ...@@ -555,6 +576,11 @@ public class SoftVoice extends VoiceStatus {
active = false; active = false;
stopping = false; stopping = false;
audiostarted = false; audiostarted = false;
instrument = null;
performer = null;
connections = null;
extendedConnectionBlocks = null;
channelmixer = null;
if (osc_stream != null) if (osc_stream != null)
try { try {
osc_stream.close(); osc_stream.close();
......
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -271,7 +271,7 @@ public class WaveExtensibleFileReader extends AudioFileReader { ...@@ -271,7 +271,7 @@ public class WaveExtensibleFileReader extends AudioFileReader {
bits, channels, framesize, samplerate, false, p); bits, channels, framesize, samplerate, false, p);
} }
} else if (subFormat.equals(SUBTYPE_IEEE_FLOAT)) { } else if (subFormat.equals(SUBTYPE_IEEE_FLOAT)) {
audioformat = new AudioFormat(AudioFloatConverter.PCM_FLOAT, audioformat = new AudioFormat(Encoding.PCM_FLOAT,
samplerate, bits, channels, framesize, samplerate, false, p); samplerate, bits, channels, framesize, samplerate, false, p);
} else } else
throw new UnsupportedAudioFileException(); throw new UnsupportedAudioFileException();
......
/* /*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -33,6 +33,7 @@ import java.net.URL; ...@@ -33,6 +33,7 @@ import java.net.URL;
import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.UnsupportedAudioFileException;
...@@ -102,7 +103,7 @@ public class WaveFloatFileReader extends AudioFileReader { ...@@ -102,7 +103,7 @@ public class WaveFloatFileReader extends AudioFileReader {
throw new UnsupportedAudioFileException(); throw new UnsupportedAudioFileException();
AudioFormat audioformat = new AudioFormat( AudioFormat audioformat = new AudioFormat(
AudioFloatConverter.PCM_FLOAT, samplerate, bits, channels, Encoding.PCM_FLOAT, samplerate, bits, channels,
framesize, samplerate, false); framesize, samplerate, false);
AudioFileFormat fileformat = new AudioFileFormat( AudioFileFormat fileformat = new AudioFileFormat(
AudioFileFormat.Type.WAVE, audioformat, AudioFileFormat.Type.WAVE, audioformat,
......
/* /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -30,6 +30,7 @@ import java.io.OutputStream; ...@@ -30,6 +30,7 @@ import java.io.OutputStream;
import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioFileFormat.Type; import javax.sound.sampled.AudioFileFormat.Type;
...@@ -48,8 +49,7 @@ public class WaveFloatFileWriter extends AudioFileWriter { ...@@ -48,8 +49,7 @@ public class WaveFloatFileWriter extends AudioFileWriter {
public Type[] getAudioFileTypes(AudioInputStream stream) { public Type[] getAudioFileTypes(AudioInputStream stream) {
if (!stream.getFormat().getEncoding().equals( if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
AudioFloatConverter.PCM_FLOAT))
return new Type[0]; return new Type[0];
return new Type[] { Type.WAVE }; return new Type[] { Type.WAVE };
} }
...@@ -58,8 +58,7 @@ public class WaveFloatFileWriter extends AudioFileWriter { ...@@ -58,8 +58,7 @@ public class WaveFloatFileWriter extends AudioFileWriter {
if (!Type.WAVE.equals(type)) if (!Type.WAVE.equals(type))
throw new IllegalArgumentException("File type " + type throw new IllegalArgumentException("File type " + type
+ " not supported."); + " not supported.");
if (!stream.getFormat().getEncoding().equals( if (!stream.getFormat().getEncoding().equals(Encoding.PCM_FLOAT))
AudioFloatConverter.PCM_FLOAT))
throw new IllegalArgumentException("File format " throw new IllegalArgumentException("File format "
+ stream.getFormat() + " not supported."); + stream.getFormat() + " not supported.");
} }
......
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -518,7 +518,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern ...@@ -518,7 +518,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
setReadOnly(true); setReadOnly(true);
setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
setEscapeProcessing(true); setEscapeProcessing(true);
setTypeMap(null); //setTypeMap(null);
checkTransactionalWriter(); checkTransactionalWriter();
//Instantiating the vector for MatchColumns //Instantiating the vector for MatchColumns
...@@ -679,7 +679,10 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern ...@@ -679,7 +679,10 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
} else if (obj instanceof Clob) { } else if (obj instanceof Clob) {
obj = new SerialClob((Clob)obj); obj = new SerialClob((Clob)obj);
} else if (obj instanceof java.sql.Array) { } else if (obj instanceof java.sql.Array) {
if(map != null)
obj = new SerialArray((java.sql.Array)obj, map); obj = new SerialArray((java.sql.Array)obj, map);
else
obj = new SerialArray((java.sql.Array)obj);
} }
((Row)currentRow).initColumnObject(i, obj); ((Row)currentRow).initColumnObject(i, obj);
...@@ -6322,6 +6325,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern ...@@ -6322,6 +6325,7 @@ public class CachedRowSetImpl extends BaseRowSet implements RowSet, RowSetIntern
crs.RowSetMD = RowSetMD; crs.RowSetMD = RowSetMD;
crs.numRows = 1; crs.numRows = 1;
crs.cursorPos = 0; crs.cursorPos = 0;
crs.setTypeMap(this.getTypeMap());
// make sure we don't get someone playing with these // make sure we don't get someone playing with these
// %%% is this now necessary ??? // %%% is this now necessary ???
...@@ -10114,7 +10118,7 @@ a ...@@ -10114,7 +10118,7 @@ a
* during the deserialization process * during the deserialization process
* *
*/ */
protected void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here // Default state initialization happens here
ois.defaultReadObject(); ois.defaultReadObject();
// Initialization of transient Res Bundle happens here . // Initialization of transient Res Bundle happens here .
...@@ -10125,5 +10129,15 @@ a ...@@ -10125,5 +10129,15 @@ a
} }
} }
//------------------------- JDBC 4.1 -----------------------------------
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
throw new SQLFeatureNotSupportedException("Not supported yet.");
}
public <T> T getObject(String columnLabel, Class<T> type) throws SQLException {
throw new SQLFeatureNotSupportedException("Not supported yet.");
}
static final long serialVersionUID =1884577171200622428L; static final long serialVersionUID =1884577171200622428L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -1746,5 +1746,23 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C ...@@ -1746,5 +1746,23 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C
onInsertRow = false; onInsertRow = false;
super.insertRow(); super.insertRow();
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = 6178454588413509360L; static final long serialVersionUID = 6178454588413509360L;
} // end FilteredRowSetImpl class } // end FilteredRowSetImpl class
/* /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -153,4 +153,5 @@ public class JdbcRowSetResourceBundle implements Serializable { ...@@ -153,4 +153,5 @@ public class JdbcRowSetResourceBundle implements Serializable {
return propResBundle.handleGetObject(key); return propResBundle.handleGetObject(key);
} }
static final long serialVersionUID = 436199386225359954L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -127,6 +127,11 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet { ...@@ -127,6 +127,11 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
strMatchKey = null; strMatchKey = null;
supportedJOINs = supportedJOINs =
new boolean[] {false, true, false, false, false}; new boolean[] {false, true, false, false, false};
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
} }
...@@ -4306,5 +4311,22 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet { ...@@ -4306,5 +4311,22 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet {
return crsInternal.createCopySchema(); return crsInternal.createCopySchema();
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = -5590501621560008453L; static final long serialVersionUID = -5590501621560008453L;
} }
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.rowset;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.WebRowSet;
import javax.sql.rowset.RowSetFactory;
/**
* This is the implementation specific class for the
* <code>javax.sql.rowset.spi.RowSetFactory</code>. This is the platform
* default implementation for the Java SE platform.
*
* @author Lance Andersen
*
*
* @version 1.7
*/
public final class RowSetFactoryImpl implements RowSetFactory {
public CachedRowSet createCachedRowSet() throws SQLException {
return new com.sun.rowset.CachedRowSetImpl();
}
public FilteredRowSet createFilteredRowSet() throws SQLException {
return new com.sun.rowset.FilteredRowSetImpl();
}
public JdbcRowSet createJdbcRowSet() throws SQLException {
return new com.sun.rowset.JdbcRowSetImpl();
}
public JoinRowSet createJoinRowSet() throws SQLException {
return new com.sun.rowset.JoinRowSetImpl();
}
public WebRowSet createWebRowSet() throws SQLException {
return new com.sun.rowset.WebRowSetImpl();
}
}
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -103,6 +103,12 @@ public class WebRowSetImpl extends CachedRowSetImpl implements WebRowSet { ...@@ -103,6 +103,12 @@ public class WebRowSetImpl extends CachedRowSetImpl implements WebRowSet {
*/ */
public WebRowSetImpl(Hashtable env) throws SQLException { public WebRowSetImpl(Hashtable env) throws SQLException {
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
if ( env == null) { if ( env == null) {
throw new SQLException(resBundle.handleGetObject("webrowsetimpl.nullhash").toString()); throw new SQLException(resBundle.handleGetObject("webrowsetimpl.nullhash").toString());
} }
...@@ -263,5 +269,23 @@ public class WebRowSetImpl extends CachedRowSetImpl implements WebRowSet { ...@@ -263,5 +269,23 @@ public class WebRowSetImpl extends CachedRowSetImpl implements WebRowSet {
this.writeXml(oStream); this.writeXml(oStream);
} }
static final long serialVersionUID = -8771775154092422943L;
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = -8771775154092422943L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -490,4 +490,17 @@ public class CachedRowSetReader implements RowSetReader, Serializable { ...@@ -490,4 +490,17 @@ public class CachedRowSetReader implements RowSetReader, Serializable {
startPosition = pos; startPosition = pos;
} }
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID =5049738185801363801L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -31,7 +31,13 @@ import java.util.*; ...@@ -31,7 +31,13 @@ import java.util.*;
import java.io.*; import java.io.*;
import com.sun.rowset.*; import com.sun.rowset.*;
import java.text.MessageFormat;
import javax.sql.rowset.*; import javax.sql.rowset.*;
import javax.sql.rowset.serial.SQLInputImpl;
import javax.sql.rowset.serial.SerialArray;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialClob;
import javax.sql.rowset.serial.SerialStruct;
import javax.sql.rowset.spi.*; import javax.sql.rowset.spi.*;
...@@ -53,6 +59,7 @@ import javax.sql.rowset.spi.*; ...@@ -53,6 +59,7 @@ import javax.sql.rowset.spi.*;
* Standard JDBC RowSet implementations provide an object instance of this * Standard JDBC RowSet implementations provide an object instance of this
* writer by invoking the <code>SyncProvider.getRowSetWriter()</code> method. * writer by invoking the <code>SyncProvider.getRowSetWriter()</code> method.
* *
* @version 0.2
* @author Jonathan Bruce * @author Jonathan Bruce
* @see javax.sql.rowset.spi.SyncProvider * @see javax.sql.rowset.spi.SyncProvider
* @see javax.sql.rowset.spi.SyncFactory * @see javax.sql.rowset.spi.SyncFactory
...@@ -508,8 +515,9 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable { ...@@ -508,8 +515,9 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
ResultSet rs = null; ResultSet rs = null;
rs = pstmt.executeQuery(); rs = pstmt.executeQuery();
if (rs.next() == true) { ResultSetMetaData rsmd = rs.getMetaData();
if (rs.next()) {
if (rs.next()) { if (rs.next()) {
/** More than one row conflict. /** More than one row conflict.
* If rs has only one row we are able to * If rs has only one row we are able to
...@@ -552,6 +560,49 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable { ...@@ -552,6 +560,49 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
orig = origVals.getObject(i); orig = origVals.getObject(i);
curr = crs.getObject(i); curr = crs.getObject(i);
rsval = rs.getObject(i); rsval = rs.getObject(i);
/*
* the following block creates equivalent objects
* that would have been created if this rs is populated
* into a CachedRowSet so that comparison of the column values
* from the ResultSet and CachedRowSet are possible
*/
Map map = (crs.getTypeMap() == null)?con.getTypeMap():crs.getTypeMap();
if (rsval instanceof Struct) {
Struct s = (Struct)rsval;
// look up the class in the map
Class c = null;
c = (Class)map.get(s.getSQLTypeName());
if (c != null) {
// create new instance of the class
SQLData obj = null;
try {
obj = (SQLData)c.newInstance();
} catch (java.lang.InstantiationException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.unableins").toString(),
ex.getMessage()));
} catch (java.lang.IllegalAccessException ex) {
throw new SQLException(MessageFormat.format(resBundle.handleGetObject("cachedrowsetimpl.unableins").toString(),
ex.getMessage()));
}
// get the attributes from the struct
Object attribs[] = s.getAttributes(map);
// create the SQLInput "stream"
SQLInputImpl sqlInput = new SQLInputImpl(attribs, map);
// read the values...
obj.readSQL(sqlInput, s.getSQLTypeName());
rsval = obj;
}
} else if (rsval instanceof SQLData) {
rsval = new SerialStruct((SQLData)rsval, map);
} else if (rsval instanceof Blob) {
rsval = new SerialBlob((Blob)rsval);
} else if (rsval instanceof Clob) {
rsval = new SerialClob((Clob)rsval);
} else if (rsval instanceof java.sql.Array) {
rsval = new SerialArray((java.sql.Array)rsval, map);
}
// reset boolNull if it had been set // reset boolNull if it had been set
boolNull = true; boolNull = true;
...@@ -669,6 +720,9 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable { ...@@ -669,6 +720,9 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
} }
} //end for } //end for
rs.close();
pstmt.close();
this.crsResolve.insertRow(); this.crsResolve.insertRow();
this.crsResolve.moveToCurrentRow(); this.crsResolve.moveToCurrentRow();
...@@ -1179,11 +1233,22 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable { ...@@ -1179,11 +1233,22 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
private void buildKeyDesc(CachedRowSet crs) throws SQLException { private void buildKeyDesc(CachedRowSet crs) throws SQLException {
keyCols = crs.getKeyColumns(); keyCols = crs.getKeyColumns();
ResultSetMetaData resultsetmd = crs.getMetaData();
if (keyCols == null || keyCols.length == 0) { if (keyCols == null || keyCols.length == 0) {
keyCols = new int[callerColumnCount]; ArrayList<Integer> listKeys = new ArrayList<Integer>();
for (int i = 0; i < keyCols.length; ) {
keyCols[i] = ++i; for (int i = 0; i < callerColumnCount; i++ ) {
if(resultsetmd.getColumnType(i+1) != java.sql.Types.CLOB &&
resultsetmd.getColumnType(i+1) != java.sql.Types.STRUCT &&
resultsetmd.getColumnType(i+1) != java.sql.Types.SQLXML &&
resultsetmd.getColumnType(i+1) != java.sql.Types.BLOB &&
resultsetmd.getColumnType(i+1) != java.sql.Types.ARRAY &&
resultsetmd.getColumnType(i+1) != java.sql.Types.OTHER )
listKeys.add(i+1);
} }
keyCols = new int[listKeys.size()];
for (int i = 0; i < listKeys.size(); i++ )
keyCols[i] = listKeys.get(i);
} }
params = new Object[keyCols.length]; params = new Object[keyCols.length];
} }
...@@ -1359,4 +1424,17 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable { ...@@ -1359,4 +1424,17 @@ public class CachedRowSetWriter implements TransactionalWriter, Serializable {
} }
} }
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID =-8506030970299413976L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -157,4 +157,23 @@ public class InsertRow extends BaseRow implements Serializable, Cloneable { ...@@ -157,4 +157,23 @@ public class InsertRow extends BaseRow implements Serializable, Cloneable {
origVals[idx - 1] = val; origVals[idx - 1] = val;
markColInserted(idx - 1); markColInserted(idx - 1);
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = 1066099658102869344L;
} }
/* /*
* Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -35,6 +35,7 @@ import javax.sql.rowset.spi.*; ...@@ -35,6 +35,7 @@ import javax.sql.rowset.spi.*;
import com.sun.rowset.*; import com.sun.rowset.*;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream;
/** /**
* There will be two sets of data which will be maintained by the rowset at the * There will be two sets of data which will be maintained by the rowset at the
...@@ -4837,4 +4838,23 @@ public class SyncResolverImpl extends CachedRowSetImpl implements SyncResolver { ...@@ -4837,4 +4838,23 @@ public class SyncResolverImpl extends CachedRowSetImpl implements SyncResolver {
throws SQLException { throws SQLException {
throw new UnsupportedOperationException("Operation not yet supported"); throw new UnsupportedOperationException("Operation not yet supported");
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = -3345004441725080251L;
} //end class } //end class
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -216,4 +216,22 @@ public class WebRowSetXmlReader implements XmlReader, Serializable { ...@@ -216,4 +216,22 @@ public class WebRowSetXmlReader implements XmlReader, Serializable {
public void readData(RowSetInternal caller) { public void readData(RowSetInternal caller) {
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = -9127058392819008014L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -663,4 +663,23 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable { ...@@ -663,4 +663,23 @@ public class WebRowSetXmlWriter implements XmlWriter, Serializable {
return s; return s;
} }
/**
* This method re populates the resBundle
* during the deserialization process
*
*/
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID = 7163134986189677641L;
} }
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -245,4 +245,18 @@ public final class RIOptimisticProvider extends SyncProvider implements Serializ ...@@ -245,4 +245,18 @@ public final class RIOptimisticProvider extends SyncProvider implements Serializ
public String getVendor() { public String getVendor() {
return this.vendorName; return this.vendorName;
} }
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Default state initialization happens here
ois.defaultReadObject();
// Initialization of transient Res Bundle happens here .
try {
resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle();
} catch(IOException ioe) {
throw new RuntimeException(ioe);
}
}
static final long serialVersionUID =-3143367176751761936L;
} }
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
/**
* The NTLM client. Not multi-thread enabled.<p>
* Example:
* <pre>
* Client client = new Client(null, "host", "dummy",
* "REALM", "t0pSeCr3t".toCharArray());
* byte[] type1 = client.type1();
* // Send type1 to server and receive response as type2
* byte[] type3 = client.type3(type2, nonce);
* // Send type3 to server
* </pre>
*/
public final class Client extends NTLM {
final private String hostname;
final private String username;
private String domain; // might be updated by Type 2 msg
private byte[] pw1, pw2;
/**
* Creates an NTLM Client instance.
* @param version the NTLM version to use, which can be:
* <ul>
* <li>LM/NTLM: Original NTLM v1
* <li>LM: Original NTLM v1, LM only
* <li>NTLM: Original NTLM v1, NTLM only
* <li>NTLM2: NTLM v1 with Client Challenge
* <li>LMv2/NTLMv2: NTLM v2
* <li>LMv2: NTLM v2, LM only
* <li>NTLMv2: NTLM v2, NTLM only
* </ul>
* If null, "LMv2/NTLMv2" will be used.
* @param hostname hostname of the client, can be null
* @param username username to be authenticated, must not be null
* @param domain domain of {@code username}, can be null
* @param password password for {@code username}, must not be not null.
* This method does not make any modification to this parameter, it neither
* needs to access the content of this parameter after this method call,
* so you are free to modify or nullify this parameter after this call.
* @throws NullPointerException if {@code username} or {@code password} is null.
* @throws NTLMException if {@code version} is illegal
*/
public Client(String version, String hostname, String username,
String domain, char[] password) throws NTLMException {
super(version);
if ((username == null || password == null)) {
throw new NullPointerException("username/password cannot be null");
}
this.hostname = hostname;
this.username = username;
this.domain = domain;
this.pw1 = getP1(password);
this.pw2 = getP2(password);
debug("NTLM Client: (h,u,t,version(v)) = (%s,%s,%s,%s(%s))\n",
hostname, username, domain, version, v.toString());
}
/**
* Generates the Type 1 message
* @return the message generated
*/
public byte[] type1() {
Writer p = new Writer(1, 32);
int flags = 0x8203;
if (hostname != null) {
flags |= 0x2000;
}
if (domain != null) {
flags |= 0x1000;
}
if (v != Version.NTLM) {
flags |= 0x80000;
}
p.writeInt(12, flags);
p.writeSecurityBuffer(24, hostname, false);
p.writeSecurityBuffer(16, domain, false);
debug("NTLM Client: Type 1 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Generates the Type 3 message
* @param type2 the responding Type 2 message from server, must not be null
* @param nonce random 8-byte array to be used in message generation,
* must not be null except for original NTLM v1
* @return the message generated
* @throws NullPointerException if {@code type2} or {@code nonce} is null
* for NTLM v1.
* @throws NTLMException if the incoming message is invalid
*/
public byte[] type3(byte[] type2, byte[] nonce) throws NTLMException {
if (type2 == null || (v != Version.NTLM && nonce == null)) {
throw new NullPointerException("type2 and nonce cannot be null");
}
debug("NTLM Client: Type 2 received\n");
debug(type2);
Reader r = new Reader(type2);
byte[] challenge = r.readBytes(24, 8);
int inputFlags = r.readInt(20);
boolean unicode = (inputFlags & 1) == 1;
String domainFromServer = r.readSecurityBuffer(12, unicode);
if (domainFromServer != null) {
domain = domainFromServer;
}
if (domain == null) {
throw new NTLMException(NTLMException.NO_DOMAIN_INFO,
"No domain info");
}
int flags = 0x88200 | (inputFlags & 3);
Writer p = new Writer(3, 64);
byte[] lm = null, ntlm = null;
p.writeSecurityBuffer(28, domain, unicode);
p.writeSecurityBuffer(36, username, unicode);
p.writeSecurityBuffer(44, hostname, unicode);
if (v == Version.NTLM) {
byte[] lmhash = calcLMHash(pw1);
byte[] nthash = calcNTHash(pw2);
if (writeLM) lm = calcResponse (lmhash, challenge);
if (writeNTLM) ntlm = calcResponse (nthash, challenge);
} else if (v == Version.NTLM2) {
byte[] nthash = calcNTHash(pw2);
lm = ntlm2LM(nonce);
ntlm = ntlm2NTLM(nthash, nonce, challenge);
} else {
byte[] nthash = calcNTHash(pw2);
if (writeLM) lm = calcV2(nthash,
username.toUpperCase(Locale.US)+domain, nonce, challenge);
if (writeNTLM) {
byte[] alist = type2.length > 48 ?
r.readSecurityBuffer(40) : new byte[0];
byte[] blob = new byte[32+alist.length];
System.arraycopy(new byte[]{1,1,0,0,0,0,0,0}, 0, blob, 0, 8);
// TS
byte[] time = BigInteger.valueOf(new Date().getTime())
.add(new BigInteger("11644473600000"))
.multiply(BigInteger.valueOf(10000))
.toByteArray();
for (int i=0; i<time.length; i++) {
blob[8+time.length-i-1] = time[i];
}
System.arraycopy(nonce, 0, blob, 16, 8);
System.arraycopy(new byte[]{0,0,0,0}, 0, blob, 24, 4);
System.arraycopy(alist, 0, blob, 28, alist.length);
System.arraycopy(new byte[]{0,0,0,0}, 0,
blob, 28+alist.length, 4);
ntlm = calcV2(nthash, username.toUpperCase(Locale.US)+domain,
blob, challenge);
}
}
p.writeSecurityBuffer(12, lm);
p.writeSecurityBuffer(20, ntlm);
p.writeSecurityBuffer(52, new byte[0]);
p.writeInt(60, flags);
debug("NTLM Client: Type 3 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Returns the domain value provided by server after the authentication
* is complete, or the domain value provided by the client before it.
* @return the domain
*/
public String getDomain() {
return domain;
}
/**
* Disposes any password-derived information.
*/
public void dispose() {
Arrays.fill(pw1, (byte)0);
Arrays.fill(pw2, (byte)0);
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import static com.sun.security.ntlm.Version.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* NTLM authentication implemented according to MS-NLMP, version 12.1
* @since 1.7
*/
class NTLM {
private final SecretKeyFactory fac;
private final Cipher cipher;
private final MessageDigest md4;
private final Mac hmac;
private final MessageDigest md5;
private static final boolean DEBUG =
System.getProperty("ntlm.debug") != null;
final Version v;
final boolean writeLM;
final boolean writeNTLM;
protected NTLM(String version) throws NTLMException {
if (version == null) version = "LMv2/NTLMv2";
switch (version) {
case "LM": v = NTLM; writeLM = true; writeNTLM = false; break;
case "NTLM": v = NTLM; writeLM = false; writeNTLM = true; break;
case "LM/NTLM": v = NTLM; writeLM = writeNTLM = true; break;
case "NTLM2": v = NTLM2; writeLM = writeNTLM = true; break;
case "LMv2": v = NTLMv2; writeLM = true; writeNTLM = false; break;
case "NTLMv2": v = NTLMv2; writeLM = false; writeNTLM = true; break;
case "LMv2/NTLMv2": v = NTLMv2; writeLM = writeNTLM = true; break;
default: throw new NTLMException(NTLMException.BAD_VERSION,
"Unknown version " + version);
}
try {
fac = SecretKeyFactory.getInstance ("DES");
cipher = Cipher.getInstance ("DES/ECB/NoPadding");
md4 = sun.security.provider.MD4.getInstance();
hmac = Mac.getInstance("HmacMD5");
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchPaddingException e) {
throw new AssertionError();
} catch (NoSuchAlgorithmException e) {
throw new AssertionError();
}
}
/**
* Prints out a formatted string, called in various places inside then NTLM
* implementation for debugging/logging purposes. When the system property
* "ntlm.debug" is set, <code>System.out.printf(format, args)</code> is
* called. This method is designed to be overridden by child classes to
* match their own debugging/logging mechanisms.
* @param format a format string
* @param args the arguments referenced by <code>format</code>
* @see java.io.PrintStream#printf(java.lang.String, java.lang.Object[])
*/
public void debug(String format, Object... args) {
if (DEBUG) {
System.out.printf(format, args);
}
}
/**
* Prints out the content of a byte array, called in various places inside
* the NTLM implementation for debugging/logging purposes. When the system
* property "ntlm.debug" is set, the hexdump of the array is printed into
* System.out. This method is designed to be overridden by child classes to
* match their own debugging/logging mechanisms.
* @param bytes the byte array to print out
*/
public void debug(byte[] bytes) {
if (DEBUG) {
try {
new sun.misc.HexDumpEncoder().encodeBuffer(bytes, System.out);
} catch (IOException ioe) {
// Impossible
}
}
}
/**
* Reading an NTLM packet
*/
static class Reader {
private final byte[] internal;
Reader(byte[] data) {
internal = data;
}
int readInt(int offset) throws NTLMException {
try {
return internal[offset] & 0xff +
(internal[offset+1] & 0xff << 8) +
(internal[offset+2] & 0xff << 16) +
(internal[offset+3] & 0xff << 24);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
int readShort(int offset) throws NTLMException {
try {
return internal[offset] & 0xff +
(internal[offset+1] & 0xff << 8);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
byte[] readBytes(int offset, int len) throws NTLMException {
try {
return Arrays.copyOfRange(internal, offset, offset + len);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
byte[] readSecurityBuffer(int offset) throws NTLMException {
int pos = readInt(offset+4);
if (pos == 0) return null;
try {
return Arrays.copyOfRange(
internal, pos, pos + readShort(offset));
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");
}
}
String readSecurityBuffer(int offset, boolean unicode)
throws NTLMException {
byte[] raw = readSecurityBuffer(offset);
try {
return raw == null ? null : new String(
raw, unicode ? "UnicodeLittleUnmarked" : "ISO8859_1");
} catch (UnsupportedEncodingException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Invalid input encoding");
}
}
}
/**
* Writing an NTLM packet
*/
static class Writer {
private byte[] internal; // buffer
private int current; // current written content interface buffer
/**
* Starts writing a NTLM packet
* @param type NEGOTIATE || CHALLENGE || AUTHENTICATE
* @param len the base length, without security buffers
*/
Writer(int type, int len) {
assert len < 256;
internal = new byte[256];
current = len;
System.arraycopy (
new byte[] {'N','T','L','M','S','S','P',0,(byte)type},
0, internal, 0, 9);
}
void writeShort(int offset, int number) {
internal[offset] = (byte)(number);
internal[offset+1] = (byte)(number >> 8);
}
void writeInt(int offset, int number) {
internal[offset] = (byte)(number);
internal[offset+1] = (byte)(number >> 8);
internal[offset+2] = (byte)(number >> 16);
internal[offset+3] = (byte)(number >> 24);
}
void writeBytes(int offset, byte[] data) {
System.arraycopy(data, 0, internal, offset, data.length);
}
void writeSecurityBuffer(int offset, byte[] data) {
if (data == null) {
writeShort(offset+4, current);
} else {
int len = data.length;
if (current + len > internal.length) {
internal = Arrays.copyOf(internal, current + len + 256);
}
writeShort(offset, len);
writeShort(offset+2, len);
writeShort(offset+4, current);
System.arraycopy(data, 0, internal, current, len);
current += len;
}
}
void writeSecurityBuffer(int offset, String str, boolean unicode) {
try {
writeSecurityBuffer(offset, str == null ? null : str.getBytes(
unicode ? "UnicodeLittleUnmarked" : "ISO8859_1"));
} catch (UnsupportedEncodingException ex) {
assert false;
}
}
byte[] getBytes() {
return Arrays.copyOf(internal, current);
}
}
// LM/NTLM
/* Convert a 7 byte array to an 8 byte array (for a des key with parity)
* input starts at offset off
*/
byte[] makeDesKey (byte[] input, int off) {
int[] in = new int [input.length];
for (int i=0; i<in.length; i++ ) {
in[i] = input[i]<0 ? input[i]+256: input[i];
}
byte[] out = new byte[8];
out[0] = (byte)in[off+0];
out[1] = (byte)(((in[off+0] << 7) & 0xFF) | (in[off+1] >> 1));
out[2] = (byte)(((in[off+1] << 6) & 0xFF) | (in[off+2] >> 2));
out[3] = (byte)(((in[off+2] << 5) & 0xFF) | (in[off+3] >> 3));
out[4] = (byte)(((in[off+3] << 4) & 0xFF) | (in[off+4] >> 4));
out[5] = (byte)(((in[off+4] << 3) & 0xFF) | (in[off+5] >> 5));
out[6] = (byte)(((in[off+5] << 2) & 0xFF) | (in[off+6] >> 6));
out[7] = (byte)((in[off+6] << 1) & 0xFF);
return out;
}
byte[] calcLMHash (byte[] pwb) {
byte[] magic = {0x4b, 0x47, 0x53, 0x21, 0x40, 0x23, 0x24, 0x25};
byte[] pwb1 = new byte [14];
int len = pwb.length;
if (len > 14)
len = 14;
System.arraycopy (pwb, 0, pwb1, 0, len); /* Zero padded */
try {
DESKeySpec dks1 = new DESKeySpec (makeDesKey (pwb1, 0));
DESKeySpec dks2 = new DESKeySpec (makeDesKey (pwb1, 7));
SecretKey key1 = fac.generateSecret (dks1);
SecretKey key2 = fac.generateSecret (dks2);
cipher.init (Cipher.ENCRYPT_MODE, key1);
byte[] out1 = cipher.doFinal (magic, 0, 8);
cipher.init (Cipher.ENCRYPT_MODE, key2);
byte[] out2 = cipher.doFinal (magic, 0, 8);
byte[] result = new byte [21];
System.arraycopy (out1, 0, result, 0, 8);
System.arraycopy (out2, 0, result, 8, 8);
return result;
} catch (InvalidKeyException ive) {
// Will not happen, all key material are 8 bytes
assert false;
} catch (InvalidKeySpecException ikse) {
// Will not happen, we only feed DESKeySpec to DES factory
assert false;
} catch (IllegalBlockSizeException ibse) {
// Will not happen, we encrypt 8 bytes
assert false;
} catch (BadPaddingException bpe) {
// Will not happen, this is encryption
assert false;
}
return null; // will not happen, we returned already
}
byte[] calcNTHash (byte[] pw) {
byte[] out = md4.digest (pw);
byte[] result = new byte [21];
System.arraycopy (out, 0, result, 0, 16);
return result;
}
/* key is a 21 byte array. Split it into 3 7 byte chunks,
* Convert each to 8 byte DES keys, encrypt the text arg with
* each key and return the three results in a sequential []
*/
byte[] calcResponse (byte[] key, byte[] text) {
try {
assert key.length == 21;
DESKeySpec dks1 = new DESKeySpec(makeDesKey(key, 0));
DESKeySpec dks2 = new DESKeySpec(makeDesKey(key, 7));
DESKeySpec dks3 = new DESKeySpec(makeDesKey(key, 14));
SecretKey key1 = fac.generateSecret(dks1);
SecretKey key2 = fac.generateSecret(dks2);
SecretKey key3 = fac.generateSecret(dks3);
cipher.init(Cipher.ENCRYPT_MODE, key1);
byte[] out1 = cipher.doFinal(text, 0, 8);
cipher.init(Cipher.ENCRYPT_MODE, key2);
byte[] out2 = cipher.doFinal(text, 0, 8);
cipher.init(Cipher.ENCRYPT_MODE, key3);
byte[] out3 = cipher.doFinal(text, 0, 8);
byte[] result = new byte[24];
System.arraycopy(out1, 0, result, 0, 8);
System.arraycopy(out2, 0, result, 8, 8);
System.arraycopy(out3, 0, result, 16, 8);
return result;
} catch (IllegalBlockSizeException ex) { // None will happen
assert false;
} catch (BadPaddingException ex) {
assert false;
} catch (InvalidKeySpecException ex) {
assert false;
} catch (InvalidKeyException ex) {
assert false;
}
return null;
}
// LMv2/NTLMv2
byte[] hmacMD5(byte[] key, byte[] text) {
try {
SecretKeySpec skey =
new SecretKeySpec(Arrays.copyOf(key, 16), "HmacMD5");
hmac.init(skey);
return hmac.doFinal(text);
} catch (InvalidKeyException ex) {
assert false;
} catch (RuntimeException e) {
assert false;
}
return null;
}
byte[] calcV2(byte[] nthash, String text, byte[] blob, byte[] challenge) {
try {
byte[] ntlmv2hash = hmacMD5(nthash,
text.getBytes("UnicodeLittleUnmarked"));
byte[] cn = new byte[blob.length+8];
System.arraycopy(challenge, 0, cn, 0, 8);
System.arraycopy(blob, 0, cn, 8, blob.length);
byte[] result = new byte[16+blob.length];
System.arraycopy(hmacMD5(ntlmv2hash, cn), 0, result, 0, 16);
System.arraycopy(blob, 0, result, 16, blob.length);
return result;
} catch (UnsupportedEncodingException ex) {
assert false;
}
return null;
}
// NTLM2 LM/NTLM
static byte[] ntlm2LM(byte[] nonce) {
return Arrays.copyOf(nonce, 24);
}
byte[] ntlm2NTLM(byte[] ntlmHash, byte[] nonce, byte[] challenge) {
byte[] b = Arrays.copyOf(challenge, 16);
System.arraycopy(nonce, 0, b, 8, 8);
byte[] sesshash = Arrays.copyOf(md5.digest(b), 8);
return calcResponse(ntlmHash, sesshash);
}
// Password in ASCII and UNICODE
static byte[] getP1(char[] password) {
try {
return new String(password).toUpperCase().getBytes("ISO8859_1");
} catch (UnsupportedEncodingException ex) {
return null;
}
}
static byte[] getP2(char[] password) {
try {
return new String(password).getBytes("UnicodeLittleUnmarked");
} catch (UnsupportedEncodingException ex) {
return null;
}
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.security.GeneralSecurityException;
/**
* An NTLM-related Exception
*/
public final class NTLMException extends GeneralSecurityException {
/**
* If the incoming packet is invalid.
*/
public final static int PACKET_READ_ERROR = 1;
/**
* If the client cannot get a domain value from the server and the
* caller has not provided one.
*/
public final static int NO_DOMAIN_INFO = 2;
/**
* If the domain provided by the client does not match the one received
* from server.
*/
//public final static int DOMAIN_UNMATCH = 3;
/**
* If the client name is not found on server's user database.
*/
public final static int USER_UNKNOWN = 3;
/**
* If authentication fails.
*/
public final static int AUTH_FAILED = 4;
/**
* If an illegal version string is provided.
*/
public final static int BAD_VERSION = 5;
private int errorCode;
/**
* Constructs an NTLMException object.
* @param errorCode the error code, which can be retrieved by
* the {@link #errorCode() } method.
* @param msg the string message, which can be retrived by
* the {@link Exception#getMessage() } method.
*/
public NTLMException(int errorCode, String msg) {
super(msg);
this.errorCode = errorCode;
}
/**
* Returns the error code associated with this NTLMException.
* @return the error code
*/
public int errorCode() {
return errorCode;
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
import java.util.Arrays;
import java.util.Locale;
/**
* The NTLM server, not multi-thread enabled.<p>
* Example:
* <pre>
* Server server = new Server(null, "REALM") {
* public char[] getPassword(String ntdomain, String username) {
* switch (username) {
* case "dummy": return "t0pSeCr3t".toCharArray();
* case "guest": return "".toCharArray();
* default: return null;
* }
* }
* };
* // Receive client request as type1
* byte[] type2 = server.type2(type1, nonce);
* // Send type2 to client and receive type3
* verify(type3, nonce);
* </pre>
*/
public abstract class Server extends NTLM {
final private String domain;
final private boolean allVersion;
/**
* Creates a Server instance.
* @param version the NTLM version to use, which can be:
* <ul>
* <li>NTLM: Original NTLM v1
* <li>NTLM2: NTLM v1 with Client Challenge
* <li>NTLMv2: NTLM v2
* </ul>
* If null, all versions will be supported. Please note that unless NTLM2
* is selected, authentication succeeds if one of LM (or LMv2) or
* NTLM (or NTLMv2) is verified.
* @param domain the domain, must not be null
* @throws NullPointerException if {@code domain} is null.
*/
public Server(String version, String domain) throws NTLMException {
super(version);
if (domain == null) {
throw new NullPointerException("domain cannot be null");
}
this.allVersion = (version == null);
this.domain = domain;
debug("NTLM Server: (t,version) = (%s,%s)\n", domain, version);
}
/**
* Generates the Type 2 message
* @param type1 the Type1 message received, must not be null
* @param nonce the random 8-byte array to be used in message generation,
* must not be null
* @return the message generated
* @throws NullPointerException if type1 or nonce is null
* @throws NTLMException if the incoming message is invalid
*/
public byte[] type2(byte[] type1, byte[] nonce) {
if (nonce == null) {
throw new NullPointerException("nonce cannot be null");
}
debug("NTLM Server: Type 1 received\n");
if (type1 != null) debug(type1);
Writer p = new Writer(2, 32);
int flags = 0x80205;
p.writeSecurityBuffer(12, domain, true);
p.writeInt(20, flags);
p.writeBytes(24, nonce);
debug("NTLM Server: Type 2 created\n");
debug(p.getBytes());
return p.getBytes();
}
/**
* Verifies the Type3 message received from client and returns
* various negotiated information.
* @param type3 the incoming Type3 message from client, must not be null
* @param nonce the same nonce provided in {@link #type2}, must not be null
* @return username and hostname of the client in a byte array
* @throws NullPointerException if {@code type3} or {@code nonce} is null
* @throws NTLMException if the incoming message is invalid
*/
public String[] verify(byte[] type3, byte[] nonce)
throws NTLMException {
if (type3 == null || nonce == null) {
throw new NullPointerException("type1 or nonce cannot be null");
}
debug("NTLM Server: Type 3 received\n");
if (type3 != null) debug(type3);
Reader r = new Reader(type3);
String username = r.readSecurityBuffer(36, true);
String hostname = r.readSecurityBuffer(44, true);
String incomingDomain = r.readSecurityBuffer(28, true);
/*if (incomingDomain != null && !incomingDomain.equals(domain)) {
throw new NTLMException(NTLMException.DOMAIN_UNMATCH,
"Wrong domain: " + incomingDomain +
" vs " + domain); // Needed?
}*/
boolean verified = false;
char[] password = getPassword(domain, username);
if (password == null) {
throw new NTLMException(NTLMException.USER_UNKNOWN,
"Unknown user");
}
byte[] incomingLM = r.readSecurityBuffer(12);
byte[] incomingNTLM = r.readSecurityBuffer(20);
if (!verified && (allVersion || v == Version.NTLM)) {
if (incomingLM.length > 0) {
byte[] pw1 = getP1(password);
byte[] lmhash = calcLMHash(pw1);
byte[] lmresponse = calcResponse (lmhash, nonce);
if (Arrays.equals(lmresponse, incomingLM)) {
verified = true;
}
}
if (incomingNTLM.length > 0) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
byte[] ntresponse = calcResponse (nthash, nonce);
if (Arrays.equals(ntresponse, incomingNTLM)) {
verified = true;
}
}
debug("NTLM Server: verify using NTLM: " + verified + "\n");
}
if (!verified && (allVersion || v == Version.NTLM2)) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
byte[] clientNonce = Arrays.copyOf(incomingLM, 8);
byte[] ntlmresponse = ntlm2NTLM(nthash, clientNonce, nonce);
if (Arrays.equals(incomingNTLM, ntlmresponse)) {
verified = true;
}
debug("NTLM Server: verify using NTLM2: " + verified + "\n");
}
if (!verified && (allVersion || v == Version.NTLMv2)) {
byte[] pw2 = getP2(password);
byte[] nthash = calcNTHash(pw2);
if (incomingLM.length > 0) {
byte[] clientNonce = Arrays.copyOfRange(
incomingLM, 16, incomingLM.length);
byte[] lmresponse = calcV2(nthash,
username.toUpperCase(Locale.US)+incomingDomain,
clientNonce, nonce);
if (Arrays.equals(lmresponse, incomingLM)) {
verified = true;
}
}
if (incomingNTLM.length > 0) {
byte[] clientBlob = Arrays.copyOfRange(
incomingNTLM, 16, incomingNTLM.length);
byte[] ntlmresponse = calcV2(nthash,
username.toUpperCase(Locale.US)+incomingDomain,
clientBlob, nonce);
if (Arrays.equals(ntlmresponse, incomingNTLM)) {
verified = true;
}
}
debug("NTLM Server: verify using NTLMv2: " + verified + "\n");
}
if (!verified) {
throw new NTLMException(NTLMException.AUTH_FAILED,
"None of LM and NTLM verified");
}
return new String[] {username, hostname};
}
/**
* Retrieves the password for a given user. This method should be
* overridden in a concrete class.
* @param domain can be null
* @param username must not be null
* @return the password for the user, or null if unknown
*/
public abstract char[] getPassword(String domain, String username);
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.ntlm;
enum Version {
NTLM, NTLM2, NTLMv2
}
/* /*
* Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -35,10 +35,12 @@ import java.security.PrivilegedAction; ...@@ -35,10 +35,12 @@ import java.security.PrivilegedAction;
* - CRAM-MD5 * - CRAM-MD5
* - DIGEST-MD5 * - DIGEST-MD5
* - GSSAPI/Kerberos v5 * - GSSAPI/Kerberos v5
* - NTLM
* And server support for * And server support for
* - CRAM-MD5 * - CRAM-MD5
* - DIGEST-MD5 * - DIGEST-MD5
* - GSSAPI/Kerberos v5 * - GSSAPI/Kerberos v5
* - NTLM
*/ */
public final class Provider extends java.security.Provider { public final class Provider extends java.security.Provider {
...@@ -47,8 +49,8 @@ public final class Provider extends java.security.Provider { ...@@ -47,8 +49,8 @@ public final class Provider extends java.security.Provider {
private static final String info = "Sun SASL provider" + private static final String info = "Sun SASL provider" +
"(implements client mechanisms for: " + "(implements client mechanisms for: " +
"DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5;" + "DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM;" +
" server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5)"; " server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)";
public Provider() { public Provider() {
super("SunSASL", 1.7d, info); super("SunSASL", 1.7d, info);
...@@ -58,6 +60,8 @@ public final class Provider extends java.security.Provider { ...@@ -58,6 +60,8 @@ public final class Provider extends java.security.Provider {
// Client mechanisms // Client mechanisms
put("SaslClientFactory.DIGEST-MD5", put("SaslClientFactory.DIGEST-MD5",
"com.sun.security.sasl.digest.FactoryImpl"); "com.sun.security.sasl.digest.FactoryImpl");
put("SaslClientFactory.NTLM",
"com.sun.security.sasl.ntlm.FactoryImpl");
put("SaslClientFactory.GSSAPI", put("SaslClientFactory.GSSAPI",
"com.sun.security.sasl.gsskerb.FactoryImpl"); "com.sun.security.sasl.gsskerb.FactoryImpl");
...@@ -75,6 +79,8 @@ public final class Provider extends java.security.Provider { ...@@ -75,6 +79,8 @@ public final class Provider extends java.security.Provider {
"com.sun.security.sasl.gsskerb.FactoryImpl"); "com.sun.security.sasl.gsskerb.FactoryImpl");
put("SaslServerFactory.DIGEST-MD5", put("SaslServerFactory.DIGEST-MD5",
"com.sun.security.sasl.digest.FactoryImpl"); "com.sun.security.sasl.digest.FactoryImpl");
put("SaslServerFactory.NTLM",
"com.sun.security.sasl.ntlm.FactoryImpl");
return null; return null;
} }
}); });
......
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import java.util.Map;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import com.sun.security.sasl.util.PolicyUtils;
/**
* Client and server factory for NTLM SASL client/server mechanisms.
* See NTLMClient and NTLMServer for input requirements.
*
* @since 1.7
*/
public final class FactoryImpl implements SaslClientFactory,
SaslServerFactory{
private static final String myMechs[] = { "NTLM" };
private static final int mechPolicies[] = {
PolicyUtils.NOPLAINTEXT|PolicyUtils.NOANONYMOUS
};
/**
* Empty constructor.
*/
public FactoryImpl() {
}
/**
* Returns a new instance of the NTLM SASL client mechanism.
* Argument checks are performed in SaslClient's constructor.
* @returns a new SaslClient ; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL client.
*/
public SaslClient createSaslClient(String[] mechs,
String authorizationId, String protocol, String serverName,
Map<String,?> props, CallbackHandler cbh)
throws SaslException {
for (int i=0; i<mechs.length; i++) {
if (mechs[i].equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
return new NTLMClient(mechs[i], authorizationId,
protocol, serverName, props, cbh);
}
}
return null;
}
/**
* Returns a new instance of the NTLM SASL server mechanism.
* Argument checks are performed in SaslServer's constructor.
* @returns a new SaslServer ; otherwise null if unsuccessful.
* @throws SaslException If there is an error creating the NTLM
* SASL server.
*/
public SaslServer createSaslServer(String mech,
String protocol, String serverName, Map<String,?> props, CallbackHandler cbh)
throws SaslException {
if (mech.equals("NTLM") &&
PolicyUtils.checkPolicy(mechPolicies[0], props)) {
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
}
if (cbh == null) {
throw new SaslException(
"Callback handler with support for AuthorizeCallback, "+
"RealmCallback, NameCallback, and PasswordCallback " +
"required");
}
return new NTLMServer(mech, protocol, serverName, props, cbh);
}
return null;
}
/**
* Returns the authentication mechanisms that this factory can produce.
*
* @returns String[] {"NTLM"} if policies in env match those of this
* factory.
*/
public String[] getMechanismNames(Map<String,?> env) {
return PolicyUtils.filterMechs(myMechs, mechPolicies, env);
}
}
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.security.sasl.ntlm;
import com.sun.security.ntlm.Client;
import com.sun.security.ntlm.NTLMException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Random;
import javax.security.auth.callback.Callback;
import javax.security.sasl.*;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* Required callbacks:
* - RealmCallback
* handle can provide domain info for authentication, optional
* - NameCallback
* handler must enter username to use for authentication
* - PasswordCallback
* handler must enter password for username to use for authentication
*
* Environment properties that affect behavior of implementation:
*
* javax.security.sasl.qop
* String, quality of protection; only "auth" is accepted, default "auth"
*
* com.sun.security.sasl.ntlm.version
* String, name a specific version to use; can be:
* LM/NTLM: Original NTLM v1
* LM: Original NTLM v1, LM only
* NTLM: Original NTLM v1, NTLM only
* NTLM2: NTLM v1 with Client Challenge
* LMv2/NTLMv2: NTLM v2
* LMv2: NTLM v2, LM only
* NTLMv2: NTLM v2, NTLM only
* If not specified, use system property "ntlm.version". If
* still not specified, use default value "LMv2/NTLMv2".
*
* com.sun.security.sasl.ntlm.random
* java.util.Random, the nonce source to be used in NTLM v2 or NTLM v1 with
* Client Challenge. Default null, an internal java.util.Random object
* will be used
*
* Negotiated Properties:
*
* javax.security.sasl.qop
* Always "auth"
*
* com.sun.security.sasl.html.domain
* The domain for the user, provided by the server
*
* @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>
* - Simple Authentication and Security Layer (SASL)
*
*/
final class NTLMClient implements SaslClient {
private static final String NTLM_VERSION =
"com.sun.security.sasl.ntlm.version";
private static final String NTLM_RANDOM =
"com.sun.security.sasl.ntlm.random";
private final static String NTLM_DOMAIN =
"com.sun.security.sasl.ntlm.domain";
private final static String NTLM_HOSTNAME =
"com.sun.security.sasl.ntlm.hostname";
private final Client client;
private final String mech;
private final Random random;
private int step = 0; // 0-start,1-nego,2-auth,3-done
/**
* @param mech non-null
* @param authorizationId can be null or empty and ignored
* @param protocol non-null for Sasl, useless for NTLM
* @param serverName non-null for Sasl, but can be null for NTLM
* @param props can be null
* @param cbh can be null for Sasl, but will throw NPE for NTLM
* @throws SaslException
*/
NTLMClient(String mech, String authzid, String protocol, String serverName,
Map props, CallbackHandler cbh) throws SaslException {
this.mech = mech;
String version = null;
Random rtmp = null;
String hostname = null;
if (props != null) {
String qop = (String)props.get(Sasl.QOP);
if (qop != null && !qop.equals("auth")) {
throw new SaslException("NTLM only support auth");
}
version = (String)props.get(NTLM_VERSION);
rtmp = (Random)props.get(NTLM_RANDOM);
hostname = (String)props.get(NTLM_HOSTNAME);
}
this.random = rtmp != null ? rtmp : new Random();
if (version == null) {
version = System.getProperty("ntlm.version");
}
RealmCallback dcb = (serverName != null && !serverName.isEmpty())?
new RealmCallback("Realm: ", serverName) :
new RealmCallback("Realm: ");
NameCallback ncb = (authzid != null && !authzid.isEmpty()) ?
new NameCallback("User name: ", authzid) :
new NameCallback("User name: ");
PasswordCallback pcb =
new PasswordCallback("Password: ", false);
try {
cbh.handle(new Callback[] {dcb, ncb, pcb});
} catch (UnsupportedCallbackException e) {
throw new SaslException("NTLM: Cannot perform callback to " +
"acquire realm, username or password", e);
} catch (IOException e) {
throw new SaslException(
"NTLM: Error acquiring realm, username or password", e);
}
if (hostname == null) {
try {
hostname = InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
hostname = "localhost";
}
}
try {
client = new Client(version, hostname,
ncb.getName(),
dcb.getText(),
pcb.getPassword());
} catch (NTLMException ne) {
throw new SaslException(
"NTLM: Invalid version string: " + version, ne);
}
}
@Override
public String getMechanismName() {
return mech;
}
@Override
public boolean isComplete() {
return step >= 2;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len)
throws SaslException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len)
throws SaslException {
throw new UnsupportedOperationException("Not supported.");
}
@Override
public Object getNegotiatedProperty(String propName) {
if (propName.equals(Sasl.QOP)) {
return "auth";
} else if (propName.equals(NTLM_DOMAIN)) {
return client.getDomain();
} else {
return null;
}
}
@Override
public void dispose() throws SaslException {
client.dispose();
}
@Override
public boolean hasInitialResponse() {
return true;
}
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
step++;
if (step == 1) {
return client.type1();
} else {
try {
byte[] nonce = new byte[8];
random.nextBytes(nonce);
return client.type3(challenge, nonce);
} catch (NTLMException ex) {
throw new SaslException("Type3 creation failed", ex);
}
}
}
}
此差异已折叠。
此差异已折叠。
...@@ -34,8 +34,8 @@ package java.lang; ...@@ -34,8 +34,8 @@ package java.lang;
public interface AutoCloseable { public interface AutoCloseable {
/** /**
* Close this resource, relinquishing any underlying resources. * Close this resource, relinquishing any underlying resources.
* This method is invoked automatically by the automatic resource * This method is invoked automatically by the {@code
* management block construct. * try}-with-resources statement.
* *
* <p>Classes implementing this method are strongly encouraged to * <p>Classes implementing this method are strongly encouraged to
* be declared to throw more specific exceptions (or no exception * be declared to throw more specific exceptions (or no exception
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册